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/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/AttributeCommonInfo.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/CXXFieldCollector.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Initialization.h"
36 #include "clang/Sema/Lookup.h"
37 #include "clang/Sema/ParsedTemplate.h"
38 #include "clang/Sema/Scope.h"
39 #include "clang/Sema/ScopeInfo.h"
40 #include "clang/Sema/SemaInternal.h"
41 #include "clang/Sema/Template.h"
42 #include "llvm/ADT/ScopeExit.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include <map>
47 #include <set>
48 
49 using namespace clang;
50 
51 //===----------------------------------------------------------------------===//
52 // CheckDefaultArgumentVisitor
53 //===----------------------------------------------------------------------===//
54 
55 namespace {
56 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
57 /// the default argument of a parameter to determine whether it
58 /// contains any ill-formed subexpressions. For example, this will
59 /// diagnose the use of local variables or parameters within the
60 /// default argument expression.
61 class CheckDefaultArgumentVisitor
62     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
63   Sema &S;
64   const Expr *DefaultArg;
65 
66 public:
67   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
68       : S(S), DefaultArg(DefaultArg) {}
69 
70   bool VisitExpr(const Expr *Node);
71   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
72   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
73   bool VisitLambdaExpr(const LambdaExpr *Lambda);
74   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
75 };
76 
77 /// VisitExpr - Visit all of the children of this expression.
78 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
79   bool IsInvalid = false;
80   for (const Stmt *SubStmt : Node->children())
81     IsInvalid |= Visit(SubStmt);
82   return IsInvalid;
83 }
84 
85 /// VisitDeclRefExpr - Visit a reference to a declaration, to
86 /// determine whether this declaration can be used in the default
87 /// argument expression.
88 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
89   const NamedDecl *Decl = DRE->getDecl();
90   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
91     // C++ [dcl.fct.default]p9:
92     //   [...] parameters of a function shall not be used in default
93     //   argument expressions, even if they are not evaluated. [...]
94     //
95     // C++17 [dcl.fct.default]p9 (by CWG 2082):
96     //   [...] A parameter shall not appear as a potentially-evaluated
97     //   expression in a default argument. [...]
98     //
99     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
100       return S.Diag(DRE->getBeginLoc(),
101                     diag::err_param_default_argument_references_param)
102              << Param->getDeclName() << DefaultArg->getSourceRange();
103   } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
104     // C++ [dcl.fct.default]p7:
105     //   Local variables shall not be used in default argument
106     //   expressions.
107     //
108     // C++17 [dcl.fct.default]p7 (by CWG 2082):
109     //   A local variable shall not appear as a potentially-evaluated
110     //   expression in a default argument.
111     //
112     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
113     //   Note: A local variable cannot be odr-used (6.3) in a default argument.
114     //
115     if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
116       return S.Diag(DRE->getBeginLoc(),
117                     diag::err_param_default_argument_references_local)
118              << VDecl->getDeclName() << DefaultArg->getSourceRange();
119   }
120 
121   return false;
122 }
123 
124 /// VisitCXXThisExpr - Visit a C++ "this" expression.
125 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
126   // C++ [dcl.fct.default]p8:
127   //   The keyword this shall not be used in a default argument of a
128   //   member function.
129   return S.Diag(ThisE->getBeginLoc(),
130                 diag::err_param_default_argument_references_this)
131          << ThisE->getSourceRange();
132 }
133 
134 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
135     const PseudoObjectExpr *POE) {
136   bool Invalid = false;
137   for (const Expr *E : POE->semantics()) {
138     // Look through bindings.
139     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
140       E = OVE->getSourceExpr();
141       assert(E && "pseudo-object binding without source expression?");
142     }
143 
144     Invalid |= Visit(E);
145   }
146   return Invalid;
147 }
148 
149 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
150   // C++11 [expr.lambda.prim]p13:
151   //   A lambda-expression appearing in a default argument shall not
152   //   implicitly or explicitly capture any entity.
153   if (Lambda->capture_begin() == Lambda->capture_end())
154     return false;
155 
156   return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
157 }
158 } // namespace
159 
160 void
161 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
162                                                  const CXXMethodDecl *Method) {
163   // If we have an MSAny spec already, don't bother.
164   if (!Method || ComputedEST == EST_MSAny)
165     return;
166 
167   const FunctionProtoType *Proto
168     = Method->getType()->getAs<FunctionProtoType>();
169   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
170   if (!Proto)
171     return;
172 
173   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
174 
175   // If we have a throw-all spec at this point, ignore the function.
176   if (ComputedEST == EST_None)
177     return;
178 
179   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
180     EST = EST_BasicNoexcept;
181 
182   switch (EST) {
183   case EST_Unparsed:
184   case EST_Uninstantiated:
185   case EST_Unevaluated:
186     llvm_unreachable("should not see unresolved exception specs here");
187 
188   // If this function can throw any exceptions, make a note of that.
189   case EST_MSAny:
190   case EST_None:
191     // FIXME: Whichever we see last of MSAny and None determines our result.
192     // We should make a consistent, order-independent choice here.
193     ClearExceptions();
194     ComputedEST = EST;
195     return;
196   case EST_NoexceptFalse:
197     ClearExceptions();
198     ComputedEST = EST_None;
199     return;
200   // FIXME: If the call to this decl is using any of its default arguments, we
201   // need to search them for potentially-throwing calls.
202   // If this function has a basic noexcept, it doesn't affect the outcome.
203   case EST_BasicNoexcept:
204   case EST_NoexceptTrue:
205   case EST_NoThrow:
206     return;
207   // If we're still at noexcept(true) and there's a throw() callee,
208   // change to that specification.
209   case EST_DynamicNone:
210     if (ComputedEST == EST_BasicNoexcept)
211       ComputedEST = EST_DynamicNone;
212     return;
213   case EST_DependentNoexcept:
214     llvm_unreachable(
215         "should not generate implicit declarations for dependent cases");
216   case EST_Dynamic:
217     break;
218   }
219   assert(EST == EST_Dynamic && "EST case not considered earlier.");
220   assert(ComputedEST != EST_None &&
221          "Shouldn't collect exceptions when throw-all is guaranteed.");
222   ComputedEST = EST_Dynamic;
223   // Record the exceptions in this function's exception specification.
224   for (const auto &E : Proto->exceptions())
225     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
226       Exceptions.push_back(E);
227 }
228 
229 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
230   if (!S || ComputedEST == EST_MSAny)
231     return;
232 
233   // FIXME:
234   //
235   // C++0x [except.spec]p14:
236   //   [An] implicit exception-specification specifies the type-id T if and
237   // only if T is allowed by the exception-specification of a function directly
238   // invoked by f's implicit definition; f shall allow all exceptions if any
239   // function it directly invokes allows all exceptions, and f shall allow no
240   // exceptions if every function it directly invokes allows no exceptions.
241   //
242   // Note in particular that if an implicit exception-specification is generated
243   // for a function containing a throw-expression, that specification can still
244   // be noexcept(true).
245   //
246   // Note also that 'directly invoked' is not defined in the standard, and there
247   // is no indication that we should only consider potentially-evaluated calls.
248   //
249   // Ultimately we should implement the intent of the standard: the exception
250   // specification should be the set of exceptions which can be thrown by the
251   // implicit definition. For now, we assume that any non-nothrow expression can
252   // throw any exception.
253 
254   if (Self->canThrow(S))
255     ComputedEST = EST_None;
256 }
257 
258 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
259                                              SourceLocation EqualLoc) {
260   if (RequireCompleteType(Param->getLocation(), Param->getType(),
261                           diag::err_typecheck_decl_incomplete_type))
262     return true;
263 
264   // C++ [dcl.fct.default]p5
265   //   A default argument expression is implicitly converted (clause
266   //   4) to the parameter type. The default argument expression has
267   //   the same semantic constraints as the initializer expression in
268   //   a declaration of a variable of the parameter type, using the
269   //   copy-initialization semantics (8.5).
270   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
271                                                                     Param);
272   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
273                                                            EqualLoc);
274   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276   if (Result.isInvalid())
277     return true;
278   Arg = Result.getAs<Expr>();
279 
280   CheckCompletedExpr(Arg, EqualLoc);
281   Arg = MaybeCreateExprWithCleanups(Arg);
282 
283   return Arg;
284 }
285 
286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
287                                    SourceLocation EqualLoc) {
288   // Add the default argument to the parameter
289   Param->setDefaultArg(Arg);
290 
291   // We have already instantiated this parameter; provide each of the
292   // instantiations with the uninstantiated default argument.
293   UnparsedDefaultArgInstantiationsMap::iterator InstPos
294     = UnparsedDefaultArgInstantiations.find(Param);
295   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
297       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
298 
299     // We're done tracking this parameter's instantiations.
300     UnparsedDefaultArgInstantiations.erase(InstPos);
301   }
302 }
303 
304 /// ActOnParamDefaultArgument - Check whether the default argument
305 /// provided for a function parameter is well-formed. If so, attach it
306 /// to the parameter declaration.
307 void
308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
309                                 Expr *DefaultArg) {
310   if (!param || !DefaultArg)
311     return;
312 
313   ParmVarDecl *Param = cast<ParmVarDecl>(param);
314   UnparsedDefaultArgLocs.erase(Param);
315 
316   auto Fail = [&] {
317     Param->setInvalidDecl();
318     Param->setDefaultArg(new (Context) OpaqueValueExpr(
319         EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
320   };
321 
322   // Default arguments are only permitted in C++
323   if (!getLangOpts().CPlusPlus) {
324     Diag(EqualLoc, diag::err_param_default_argument)
325       << DefaultArg->getSourceRange();
326     return Fail();
327   }
328 
329   // Check for unexpanded parameter packs.
330   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
331     return Fail();
332   }
333 
334   // C++11 [dcl.fct.default]p3
335   //   A default argument expression [...] shall not be specified for a
336   //   parameter pack.
337   if (Param->isParameterPack()) {
338     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339         << DefaultArg->getSourceRange();
340     // Recover by discarding the default argument.
341     Param->setDefaultArg(nullptr);
342     return;
343   }
344 
345   ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346   if (Result.isInvalid())
347     return Fail();
348 
349   DefaultArg = Result.getAs<Expr>();
350 
351   // Check that the default argument is well-formed
352   CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353   if (DefaultArgChecker.Visit(DefaultArg))
354     return Fail();
355 
356   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
357 }
358 
359 /// ActOnParamUnparsedDefaultArgument - We've seen a default
360 /// argument for a function parameter, but we can't parse it yet
361 /// because we're inside a class definition. Note that this default
362 /// argument will be parsed later.
363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
364                                              SourceLocation EqualLoc,
365                                              SourceLocation ArgLoc) {
366   if (!param)
367     return;
368 
369   ParmVarDecl *Param = cast<ParmVarDecl>(param);
370   Param->setUnparsedDefaultArg();
371   UnparsedDefaultArgLocs[Param] = ArgLoc;
372 }
373 
374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375 /// the default argument for the parameter param failed.
376 void Sema::ActOnParamDefaultArgumentError(Decl *param,
377                                           SourceLocation EqualLoc) {
378   if (!param)
379     return;
380 
381   ParmVarDecl *Param = cast<ParmVarDecl>(param);
382   Param->setInvalidDecl();
383   UnparsedDefaultArgLocs.erase(Param);
384   Param->setDefaultArg(new (Context) OpaqueValueExpr(
385       EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
386 }
387 
388 /// CheckExtraCXXDefaultArguments - Check for any extra default
389 /// arguments in the declarator, which is not a function declaration
390 /// or definition and therefore is not permitted to have default
391 /// arguments. This routine should be invoked for every declarator
392 /// that is not a function declaration or definition.
393 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
394   // C++ [dcl.fct.default]p3
395   //   A default argument expression shall be specified only in the
396   //   parameter-declaration-clause of a function declaration or in a
397   //   template-parameter (14.1). It shall not be specified for a
398   //   parameter pack. If it is specified in a
399   //   parameter-declaration-clause, it shall not occur within a
400   //   declarator or abstract-declarator of a parameter-declaration.
401   bool MightBeFunction = D.isFunctionDeclarationContext();
402   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
403     DeclaratorChunk &chunk = D.getTypeObject(i);
404     if (chunk.Kind == DeclaratorChunk::Function) {
405       if (MightBeFunction) {
406         // This is a function declaration. It can have default arguments, but
407         // keep looking in case its return type is a function type with default
408         // arguments.
409         MightBeFunction = false;
410         continue;
411       }
412       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
413            ++argIdx) {
414         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
415         if (Param->hasUnparsedDefaultArg()) {
416           std::unique_ptr<CachedTokens> Toks =
417               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
418           SourceRange SR;
419           if (Toks->size() > 1)
420             SR = SourceRange((*Toks)[1].getLocation(),
421                              Toks->back().getLocation());
422           else
423             SR = UnparsedDefaultArgLocs[Param];
424           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
425             << SR;
426         } else if (Param->getDefaultArg()) {
427           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
428             << Param->getDefaultArg()->getSourceRange();
429           Param->setDefaultArg(nullptr);
430         }
431       }
432     } else if (chunk.Kind != DeclaratorChunk::Paren) {
433       MightBeFunction = false;
434     }
435   }
436 }
437 
438 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
439   return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
440     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
441   });
442 }
443 
444 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
445 /// function, once we already know that they have the same
446 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
447 /// error, false otherwise.
448 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
449                                 Scope *S) {
450   bool Invalid = false;
451 
452   // The declaration context corresponding to the scope is the semantic
453   // parent, unless this is a local function declaration, in which case
454   // it is that surrounding function.
455   DeclContext *ScopeDC = New->isLocalExternDecl()
456                              ? New->getLexicalDeclContext()
457                              : New->getDeclContext();
458 
459   // Find the previous declaration for the purpose of default arguments.
460   FunctionDecl *PrevForDefaultArgs = Old;
461   for (/**/; PrevForDefaultArgs;
462        // Don't bother looking back past the latest decl if this is a local
463        // extern declaration; nothing else could work.
464        PrevForDefaultArgs = New->isLocalExternDecl()
465                                 ? nullptr
466                                 : PrevForDefaultArgs->getPreviousDecl()) {
467     // Ignore hidden declarations.
468     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
469       continue;
470 
471     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
472         !New->isCXXClassMember()) {
473       // Ignore default arguments of old decl if they are not in
474       // the same scope and this is not an out-of-line definition of
475       // a member function.
476       continue;
477     }
478 
479     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
480       // If only one of these is a local function declaration, then they are
481       // declared in different scopes, even though isDeclInScope may think
482       // they're in the same scope. (If both are local, the scope check is
483       // sufficient, and if neither is local, then they are in the same scope.)
484       continue;
485     }
486 
487     // We found the right previous declaration.
488     break;
489   }
490 
491   // C++ [dcl.fct.default]p4:
492   //   For non-template functions, default arguments can be added in
493   //   later declarations of a function in the same
494   //   scope. Declarations in different scopes have completely
495   //   distinct sets of default arguments. That is, declarations in
496   //   inner scopes do not acquire default arguments from
497   //   declarations in outer scopes, and vice versa. In a given
498   //   function declaration, all parameters subsequent to a
499   //   parameter with a default argument shall have default
500   //   arguments supplied in this or previous declarations. A
501   //   default argument shall not be redefined by a later
502   //   declaration (not even to the same value).
503   //
504   // C++ [dcl.fct.default]p6:
505   //   Except for member functions of class templates, the default arguments
506   //   in a member function definition that appears outside of the class
507   //   definition are added to the set of default arguments provided by the
508   //   member function declaration in the class definition.
509   for (unsigned p = 0, NumParams = PrevForDefaultArgs
510                                        ? PrevForDefaultArgs->getNumParams()
511                                        : 0;
512        p < NumParams; ++p) {
513     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
514     ParmVarDecl *NewParam = New->getParamDecl(p);
515 
516     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
517     bool NewParamHasDfl = NewParam->hasDefaultArg();
518 
519     if (OldParamHasDfl && NewParamHasDfl) {
520       unsigned DiagDefaultParamID =
521         diag::err_param_default_argument_redefinition;
522 
523       // MSVC accepts that default parameters be redefined for member functions
524       // of template class. The new default parameter's value is ignored.
525       Invalid = true;
526       if (getLangOpts().MicrosoftExt) {
527         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
528         if (MD && MD->getParent()->getDescribedClassTemplate()) {
529           // Merge the old default argument into the new parameter.
530           NewParam->setHasInheritedDefaultArg();
531           if (OldParam->hasUninstantiatedDefaultArg())
532             NewParam->setUninstantiatedDefaultArg(
533                                       OldParam->getUninstantiatedDefaultArg());
534           else
535             NewParam->setDefaultArg(OldParam->getInit());
536           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
537           Invalid = false;
538         }
539       }
540 
541       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
542       // hint here. Alternatively, we could walk the type-source information
543       // for NewParam to find the last source location in the type... but it
544       // isn't worth the effort right now. This is the kind of test case that
545       // is hard to get right:
546       //   int f(int);
547       //   void g(int (*fp)(int) = f);
548       //   void g(int (*fp)(int) = &f);
549       Diag(NewParam->getLocation(), DiagDefaultParamID)
550         << NewParam->getDefaultArgRange();
551 
552       // Look for the function declaration where the default argument was
553       // actually written, which may be a declaration prior to Old.
554       for (auto Older = PrevForDefaultArgs;
555            OldParam->hasInheritedDefaultArg(); /**/) {
556         Older = Older->getPreviousDecl();
557         OldParam = Older->getParamDecl(p);
558       }
559 
560       Diag(OldParam->getLocation(), diag::note_previous_definition)
561         << OldParam->getDefaultArgRange();
562     } else if (OldParamHasDfl) {
563       // Merge the old default argument into the new parameter unless the new
564       // function is a friend declaration in a template class. In the latter
565       // case the default arguments will be inherited when the friend
566       // declaration will be instantiated.
567       if (New->getFriendObjectKind() == Decl::FOK_None ||
568           !New->getLexicalDeclContext()->isDependentContext()) {
569         // It's important to use getInit() here;  getDefaultArg()
570         // strips off any top-level ExprWithCleanups.
571         NewParam->setHasInheritedDefaultArg();
572         if (OldParam->hasUnparsedDefaultArg())
573           NewParam->setUnparsedDefaultArg();
574         else if (OldParam->hasUninstantiatedDefaultArg())
575           NewParam->setUninstantiatedDefaultArg(
576                                        OldParam->getUninstantiatedDefaultArg());
577         else
578           NewParam->setDefaultArg(OldParam->getInit());
579       }
580     } else if (NewParamHasDfl) {
581       if (New->getDescribedFunctionTemplate()) {
582         // Paragraph 4, quoted above, only applies to non-template functions.
583         Diag(NewParam->getLocation(),
584              diag::err_param_default_argument_template_redecl)
585           << NewParam->getDefaultArgRange();
586         Diag(PrevForDefaultArgs->getLocation(),
587              diag::note_template_prev_declaration)
588             << false;
589       } else if (New->getTemplateSpecializationKind()
590                    != TSK_ImplicitInstantiation &&
591                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
592         // C++ [temp.expr.spec]p21:
593         //   Default function arguments shall not be specified in a declaration
594         //   or a definition for one of the following explicit specializations:
595         //     - the explicit specialization of a function template;
596         //     - the explicit specialization of a member function template;
597         //     - the explicit specialization of a member function of a class
598         //       template where the class template specialization to which the
599         //       member function specialization belongs is implicitly
600         //       instantiated.
601         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
602           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
603           << New->getDeclName()
604           << NewParam->getDefaultArgRange();
605       } else if (New->getDeclContext()->isDependentContext()) {
606         // C++ [dcl.fct.default]p6 (DR217):
607         //   Default arguments for a member function of a class template shall
608         //   be specified on the initial declaration of the member function
609         //   within the class template.
610         //
611         // Reading the tea leaves a bit in DR217 and its reference to DR205
612         // leads me to the conclusion that one cannot add default function
613         // arguments for an out-of-line definition of a member function of a
614         // dependent type.
615         int WhichKind = 2;
616         if (CXXRecordDecl *Record
617               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
618           if (Record->getDescribedClassTemplate())
619             WhichKind = 0;
620           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
621             WhichKind = 1;
622           else
623             WhichKind = 2;
624         }
625 
626         Diag(NewParam->getLocation(),
627              diag::err_param_default_argument_member_template_redecl)
628           << WhichKind
629           << NewParam->getDefaultArgRange();
630       }
631     }
632   }
633 
634   // DR1344: If a default argument is added outside a class definition and that
635   // default argument makes the function a special member function, the program
636   // is ill-formed. This can only happen for constructors.
637   if (isa<CXXConstructorDecl>(New) &&
638       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
639     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
640                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
641     if (NewSM != OldSM) {
642       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
643       assert(NewParam->hasDefaultArg());
644       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
645         << NewParam->getDefaultArgRange() << NewSM;
646       Diag(Old->getLocation(), diag::note_previous_declaration);
647     }
648   }
649 
650   const FunctionDecl *Def;
651   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
652   // template has a constexpr specifier then all its declarations shall
653   // contain the constexpr specifier.
654   if (New->getConstexprKind() != Old->getConstexprKind()) {
655     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
656         << New << static_cast<int>(New->getConstexprKind())
657         << static_cast<int>(Old->getConstexprKind());
658     Diag(Old->getLocation(), diag::note_previous_declaration);
659     Invalid = true;
660   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
661              Old->isDefined(Def) &&
662              // If a friend function is inlined but does not have 'inline'
663              // specifier, it is a definition. Do not report attribute conflict
664              // in this case, redefinition will be diagnosed later.
665              (New->isInlineSpecified() ||
666               New->getFriendObjectKind() == Decl::FOK_None)) {
667     // C++11 [dcl.fcn.spec]p4:
668     //   If the definition of a function appears in a translation unit before its
669     //   first declaration as inline, the program is ill-formed.
670     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
671     Diag(Def->getLocation(), diag::note_previous_definition);
672     Invalid = true;
673   }
674 
675   // C++17 [temp.deduct.guide]p3:
676   //   Two deduction guide declarations in the same translation unit
677   //   for the same class template shall not have equivalent
678   //   parameter-declaration-clauses.
679   if (isa<CXXDeductionGuideDecl>(New) &&
680       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
681     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
682     Diag(Old->getLocation(), diag::note_previous_declaration);
683   }
684 
685   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
686   // argument expression, that declaration shall be a definition and shall be
687   // the only declaration of the function or function template in the
688   // translation unit.
689   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
690       functionDeclHasDefaultArgument(Old)) {
691     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
692     Diag(Old->getLocation(), diag::note_previous_declaration);
693     Invalid = true;
694   }
695 
696   // C++11 [temp.friend]p4 (DR329):
697   //   When a function is defined in a friend function declaration in a class
698   //   template, the function is instantiated when the function is odr-used.
699   //   The same restrictions on multiple declarations and definitions that
700   //   apply to non-template function declarations and definitions also apply
701   //   to these implicit definitions.
702   const FunctionDecl *OldDefinition = nullptr;
703   if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
704       Old->isDefined(OldDefinition, true))
705     CheckForFunctionRedefinition(New, OldDefinition);
706 
707   return Invalid;
708 }
709 
710 NamedDecl *
711 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
712                                    MultiTemplateParamsArg TemplateParamLists) {
713   assert(D.isDecompositionDeclarator());
714   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
715 
716   // The syntax only allows a decomposition declarator as a simple-declaration,
717   // a for-range-declaration, or a condition in Clang, but we parse it in more
718   // cases than that.
719   if (!D.mayHaveDecompositionDeclarator()) {
720     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
721       << Decomp.getSourceRange();
722     return nullptr;
723   }
724 
725   if (!TemplateParamLists.empty()) {
726     // FIXME: There's no rule against this, but there are also no rules that
727     // would actually make it usable, so we reject it for now.
728     Diag(TemplateParamLists.front()->getTemplateLoc(),
729          diag::err_decomp_decl_template);
730     return nullptr;
731   }
732 
733   Diag(Decomp.getLSquareLoc(),
734        !getLangOpts().CPlusPlus17
735            ? diag::ext_decomp_decl
736            : D.getContext() == DeclaratorContext::Condition
737                  ? diag::ext_decomp_decl_cond
738                  : diag::warn_cxx14_compat_decomp_decl)
739       << Decomp.getSourceRange();
740 
741   // The semantic context is always just the current context.
742   DeclContext *const DC = CurContext;
743 
744   // C++17 [dcl.dcl]/8:
745   //   The decl-specifier-seq shall contain only the type-specifier auto
746   //   and cv-qualifiers.
747   // C++2a [dcl.dcl]/8:
748   //   If decl-specifier-seq contains any decl-specifier other than static,
749   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
750   auto &DS = D.getDeclSpec();
751   {
752     SmallVector<StringRef, 8> BadSpecifiers;
753     SmallVector<SourceLocation, 8> BadSpecifierLocs;
754     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
755     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
756     if (auto SCS = DS.getStorageClassSpec()) {
757       if (SCS == DeclSpec::SCS_static) {
758         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
759         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
760       } else {
761         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
762         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
763       }
764     }
765     if (auto TSCS = DS.getThreadStorageClassSpec()) {
766       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
767       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
768     }
769     if (DS.hasConstexprSpecifier()) {
770       BadSpecifiers.push_back(
771           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
772       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
773     }
774     if (DS.isInlineSpecified()) {
775       BadSpecifiers.push_back("inline");
776       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
777     }
778     if (!BadSpecifiers.empty()) {
779       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
780       Err << (int)BadSpecifiers.size()
781           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
782       // Don't add FixItHints to remove the specifiers; we do still respect
783       // them when building the underlying variable.
784       for (auto Loc : BadSpecifierLocs)
785         Err << SourceRange(Loc, Loc);
786     } else if (!CPlusPlus20Specifiers.empty()) {
787       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
788                          getLangOpts().CPlusPlus20
789                              ? diag::warn_cxx17_compat_decomp_decl_spec
790                              : diag::ext_decomp_decl_spec);
791       Warn << (int)CPlusPlus20Specifiers.size()
792            << llvm::join(CPlusPlus20Specifiers.begin(),
793                          CPlusPlus20Specifiers.end(), " ");
794       for (auto Loc : CPlusPlus20SpecifierLocs)
795         Warn << SourceRange(Loc, Loc);
796     }
797     // We can't recover from it being declared as a typedef.
798     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
799       return nullptr;
800   }
801 
802   // C++2a [dcl.struct.bind]p1:
803   //   A cv that includes volatile is deprecated
804   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
805       getLangOpts().CPlusPlus20)
806     Diag(DS.getVolatileSpecLoc(),
807          diag::warn_deprecated_volatile_structured_binding);
808 
809   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
810   QualType R = TInfo->getType();
811 
812   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
813                                       UPPC_DeclarationType))
814     D.setInvalidType();
815 
816   // The syntax only allows a single ref-qualifier prior to the decomposition
817   // declarator. No other declarator chunks are permitted. Also check the type
818   // specifier here.
819   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
820       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
821       (D.getNumTypeObjects() == 1 &&
822        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
823     Diag(Decomp.getLSquareLoc(),
824          (D.hasGroupingParens() ||
825           (D.getNumTypeObjects() &&
826            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
827              ? diag::err_decomp_decl_parens
828              : diag::err_decomp_decl_type)
829         << R;
830 
831     // In most cases, there's no actual problem with an explicitly-specified
832     // type, but a function type won't work here, and ActOnVariableDeclarator
833     // shouldn't be called for such a type.
834     if (R->isFunctionType())
835       D.setInvalidType();
836   }
837 
838   // Build the BindingDecls.
839   SmallVector<BindingDecl*, 8> Bindings;
840 
841   // Build the BindingDecls.
842   for (auto &B : D.getDecompositionDeclarator().bindings()) {
843     // Check for name conflicts.
844     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
845     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
846                           ForVisibleRedeclaration);
847     LookupName(Previous, S,
848                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
849 
850     // It's not permitted to shadow a template parameter name.
851     if (Previous.isSingleResult() &&
852         Previous.getFoundDecl()->isTemplateParameter()) {
853       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
854                                       Previous.getFoundDecl());
855       Previous.clear();
856     }
857 
858     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
859 
860     // Find the shadowed declaration before filtering for scope.
861     NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
862                                   ? getShadowedDeclaration(BD, Previous)
863                                   : nullptr;
864 
865     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
866                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
867     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
868                          /*AllowInlineNamespace*/false);
869 
870     if (!Previous.empty()) {
871       auto *Old = Previous.getRepresentativeDecl();
872       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
873       Diag(Old->getLocation(), diag::note_previous_definition);
874     } else if (ShadowedDecl && !D.isRedeclaration()) {
875       CheckShadow(BD, ShadowedDecl, Previous);
876     }
877     PushOnScopeChains(BD, S, true);
878     Bindings.push_back(BD);
879     ParsingInitForAutoVars.insert(BD);
880   }
881 
882   // There are no prior lookup results for the variable itself, because it
883   // is unnamed.
884   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
885                                Decomp.getLSquareLoc());
886   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
887                         ForVisibleRedeclaration);
888 
889   // Build the variable that holds the non-decomposed object.
890   bool AddToScope = true;
891   NamedDecl *New =
892       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
893                               MultiTemplateParamsArg(), AddToScope, Bindings);
894   if (AddToScope) {
895     S->AddDecl(New);
896     CurContext->addHiddenDecl(New);
897   }
898 
899   if (isInOpenMPDeclareTargetContext())
900     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
901 
902   return New;
903 }
904 
905 static bool checkSimpleDecomposition(
906     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
907     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
908     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
909   if ((int64_t)Bindings.size() != NumElems) {
910     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
911         << DecompType << (unsigned)Bindings.size()
912         << (unsigned)NumElems.getLimitedValue(UINT_MAX)
913         << toString(NumElems, 10) << (NumElems < Bindings.size());
914     return true;
915   }
916 
917   unsigned I = 0;
918   for (auto *B : Bindings) {
919     SourceLocation Loc = B->getLocation();
920     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
921     if (E.isInvalid())
922       return true;
923     E = GetInit(Loc, E.get(), I++);
924     if (E.isInvalid())
925       return true;
926     B->setBinding(ElemType, E.get());
927   }
928 
929   return false;
930 }
931 
932 static bool checkArrayLikeDecomposition(Sema &S,
933                                         ArrayRef<BindingDecl *> Bindings,
934                                         ValueDecl *Src, QualType DecompType,
935                                         const llvm::APSInt &NumElems,
936                                         QualType ElemType) {
937   return checkSimpleDecomposition(
938       S, Bindings, Src, DecompType, NumElems, ElemType,
939       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
940         ExprResult E = S.ActOnIntegerConstant(Loc, I);
941         if (E.isInvalid())
942           return ExprError();
943         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
944       });
945 }
946 
947 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
948                                     ValueDecl *Src, QualType DecompType,
949                                     const ConstantArrayType *CAT) {
950   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
951                                      llvm::APSInt(CAT->getSize()),
952                                      CAT->getElementType());
953 }
954 
955 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
956                                      ValueDecl *Src, QualType DecompType,
957                                      const VectorType *VT) {
958   return checkArrayLikeDecomposition(
959       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
960       S.Context.getQualifiedType(VT->getElementType(),
961                                  DecompType.getQualifiers()));
962 }
963 
964 static bool checkComplexDecomposition(Sema &S,
965                                       ArrayRef<BindingDecl *> Bindings,
966                                       ValueDecl *Src, QualType DecompType,
967                                       const ComplexType *CT) {
968   return checkSimpleDecomposition(
969       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
970       S.Context.getQualifiedType(CT->getElementType(),
971                                  DecompType.getQualifiers()),
972       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
973         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
974       });
975 }
976 
977 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
978                                      TemplateArgumentListInfo &Args,
979                                      const TemplateParameterList *Params) {
980   SmallString<128> SS;
981   llvm::raw_svector_ostream OS(SS);
982   bool First = true;
983   unsigned I = 0;
984   for (auto &Arg : Args.arguments()) {
985     if (!First)
986       OS << ", ";
987     Arg.getArgument().print(PrintingPolicy, OS,
988                             TemplateParameterList::shouldIncludeTypeForArgument(
989                                 PrintingPolicy, Params, I));
990     First = false;
991     I++;
992   }
993   return std::string(OS.str());
994 }
995 
996 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
997                                      SourceLocation Loc, StringRef Trait,
998                                      TemplateArgumentListInfo &Args,
999                                      unsigned DiagID) {
1000   auto DiagnoseMissing = [&] {
1001     if (DiagID)
1002       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1003                                                Args, /*Params*/ nullptr);
1004     return true;
1005   };
1006 
1007   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1008   NamespaceDecl *Std = S.getStdNamespace();
1009   if (!Std)
1010     return DiagnoseMissing();
1011 
1012   // Look up the trait itself, within namespace std. We can diagnose various
1013   // problems with this lookup even if we've been asked to not diagnose a
1014   // missing specialization, because this can only fail if the user has been
1015   // declaring their own names in namespace std or we don't support the
1016   // standard library implementation in use.
1017   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1018                       Loc, Sema::LookupOrdinaryName);
1019   if (!S.LookupQualifiedName(Result, Std))
1020     return DiagnoseMissing();
1021   if (Result.isAmbiguous())
1022     return true;
1023 
1024   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1025   if (!TraitTD) {
1026     Result.suppressDiagnostics();
1027     NamedDecl *Found = *Result.begin();
1028     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1029     S.Diag(Found->getLocation(), diag::note_declared_at);
1030     return true;
1031   }
1032 
1033   // Build the template-id.
1034   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1035   if (TraitTy.isNull())
1036     return true;
1037   if (!S.isCompleteType(Loc, TraitTy)) {
1038     if (DiagID)
1039       S.RequireCompleteType(
1040           Loc, TraitTy, DiagID,
1041           printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1042                             TraitTD->getTemplateParameters()));
1043     return true;
1044   }
1045 
1046   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1047   assert(RD && "specialization of class template is not a class?");
1048 
1049   // Look up the member of the trait type.
1050   S.LookupQualifiedName(TraitMemberLookup, RD);
1051   return TraitMemberLookup.isAmbiguous();
1052 }
1053 
1054 static TemplateArgumentLoc
1055 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1056                                    uint64_t I) {
1057   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1058   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1059 }
1060 
1061 static TemplateArgumentLoc
1062 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1063   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1064 }
1065 
1066 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1067 
1068 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1069                                llvm::APSInt &Size) {
1070   EnterExpressionEvaluationContext ContextRAII(
1071       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1072 
1073   DeclarationName Value = S.PP.getIdentifierInfo("value");
1074   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1075 
1076   // Form template argument list for tuple_size<T>.
1077   TemplateArgumentListInfo Args(Loc, Loc);
1078   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1079 
1080   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1081   // it's not tuple-like.
1082   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1083       R.empty())
1084     return IsTupleLike::NotTupleLike;
1085 
1086   // If we get this far, we've committed to the tuple interpretation, but
1087   // we can still fail if there actually isn't a usable ::value.
1088 
1089   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1090     LookupResult &R;
1091     TemplateArgumentListInfo &Args;
1092     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1093         : R(R), Args(Args) {}
1094     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1095                                                SourceLocation Loc) override {
1096       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1097              << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1098                                   /*Params*/ nullptr);
1099     }
1100   } Diagnoser(R, Args);
1101 
1102   ExprResult E =
1103       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1104   if (E.isInvalid())
1105     return IsTupleLike::Error;
1106 
1107   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1108   if (E.isInvalid())
1109     return IsTupleLike::Error;
1110 
1111   return IsTupleLike::TupleLike;
1112 }
1113 
1114 /// \return std::tuple_element<I, T>::type.
1115 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1116                                         unsigned I, QualType T) {
1117   // Form template argument list for tuple_element<I, T>.
1118   TemplateArgumentListInfo Args(Loc, Loc);
1119   Args.addArgument(
1120       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1121   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1122 
1123   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1124   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1125   if (lookupStdTypeTraitMember(
1126           S, R, Loc, "tuple_element", Args,
1127           diag::err_decomp_decl_std_tuple_element_not_specialized))
1128     return QualType();
1129 
1130   auto *TD = R.getAsSingle<TypeDecl>();
1131   if (!TD) {
1132     R.suppressDiagnostics();
1133     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1134         << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1135                              /*Params*/ nullptr);
1136     if (!R.empty())
1137       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1138     return QualType();
1139   }
1140 
1141   return S.Context.getTypeDeclType(TD);
1142 }
1143 
1144 namespace {
1145 struct InitializingBinding {
1146   Sema &S;
1147   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1148     Sema::CodeSynthesisContext Ctx;
1149     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1150     Ctx.PointOfInstantiation = BD->getLocation();
1151     Ctx.Entity = BD;
1152     S.pushCodeSynthesisContext(Ctx);
1153   }
1154   ~InitializingBinding() {
1155     S.popCodeSynthesisContext();
1156   }
1157 };
1158 }
1159 
1160 static bool checkTupleLikeDecomposition(Sema &S,
1161                                         ArrayRef<BindingDecl *> Bindings,
1162                                         VarDecl *Src, QualType DecompType,
1163                                         const llvm::APSInt &TupleSize) {
1164   if ((int64_t)Bindings.size() != TupleSize) {
1165     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1166         << DecompType << (unsigned)Bindings.size()
1167         << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1168         << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1169     return true;
1170   }
1171 
1172   if (Bindings.empty())
1173     return false;
1174 
1175   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1176 
1177   // [dcl.decomp]p3:
1178   //   The unqualified-id get is looked up in the scope of E by class member
1179   //   access lookup ...
1180   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1181   bool UseMemberGet = false;
1182   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1183     if (auto *RD = DecompType->getAsCXXRecordDecl())
1184       S.LookupQualifiedName(MemberGet, RD);
1185     if (MemberGet.isAmbiguous())
1186       return true;
1187     //   ... and if that finds at least one declaration that is a function
1188     //   template whose first template parameter is a non-type parameter ...
1189     for (NamedDecl *D : MemberGet) {
1190       if (FunctionTemplateDecl *FTD =
1191               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1192         TemplateParameterList *TPL = FTD->getTemplateParameters();
1193         if (TPL->size() != 0 &&
1194             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1195           //   ... the initializer is e.get<i>().
1196           UseMemberGet = true;
1197           break;
1198         }
1199       }
1200     }
1201   }
1202 
1203   unsigned I = 0;
1204   for (auto *B : Bindings) {
1205     InitializingBinding InitContext(S, B);
1206     SourceLocation Loc = B->getLocation();
1207 
1208     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1209     if (E.isInvalid())
1210       return true;
1211 
1212     //   e is an lvalue if the type of the entity is an lvalue reference and
1213     //   an xvalue otherwise
1214     if (!Src->getType()->isLValueReferenceType())
1215       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1216                                    E.get(), nullptr, VK_XValue,
1217                                    FPOptionsOverride());
1218 
1219     TemplateArgumentListInfo Args(Loc, Loc);
1220     Args.addArgument(
1221         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1222 
1223     if (UseMemberGet) {
1224       //   if [lookup of member get] finds at least one declaration, the
1225       //   initializer is e.get<i-1>().
1226       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1227                                      CXXScopeSpec(), SourceLocation(), nullptr,
1228                                      MemberGet, &Args, nullptr);
1229       if (E.isInvalid())
1230         return true;
1231 
1232       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1233     } else {
1234       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1235       //   in the associated namespaces.
1236       Expr *Get = UnresolvedLookupExpr::Create(
1237           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1238           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1239           UnresolvedSetIterator(), UnresolvedSetIterator());
1240 
1241       Expr *Arg = E.get();
1242       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1243     }
1244     if (E.isInvalid())
1245       return true;
1246     Expr *Init = E.get();
1247 
1248     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1249     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1250     if (T.isNull())
1251       return true;
1252 
1253     //   each vi is a variable of type "reference to T" initialized with the
1254     //   initializer, where the reference is an lvalue reference if the
1255     //   initializer is an lvalue and an rvalue reference otherwise
1256     QualType RefType =
1257         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1258     if (RefType.isNull())
1259       return true;
1260     auto *RefVD = VarDecl::Create(
1261         S.Context, Src->getDeclContext(), Loc, Loc,
1262         B->getDeclName().getAsIdentifierInfo(), RefType,
1263         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1264     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1265     RefVD->setTSCSpec(Src->getTSCSpec());
1266     RefVD->setImplicit();
1267     if (Src->isInlineSpecified())
1268       RefVD->setInlineSpecified();
1269     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1270 
1271     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1272     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1273     InitializationSequence Seq(S, Entity, Kind, Init);
1274     E = Seq.Perform(S, Entity, Kind, Init);
1275     if (E.isInvalid())
1276       return true;
1277     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1278     if (E.isInvalid())
1279       return true;
1280     RefVD->setInit(E.get());
1281     S.CheckCompleteVariableDeclaration(RefVD);
1282 
1283     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1284                                    DeclarationNameInfo(B->getDeclName(), Loc),
1285                                    RefVD);
1286     if (E.isInvalid())
1287       return true;
1288 
1289     B->setBinding(T, E.get());
1290     I++;
1291   }
1292 
1293   return false;
1294 }
1295 
1296 /// Find the base class to decompose in a built-in decomposition of a class type.
1297 /// This base class search is, unfortunately, not quite like any other that we
1298 /// perform anywhere else in C++.
1299 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1300                                                 const CXXRecordDecl *RD,
1301                                                 CXXCastPath &BasePath) {
1302   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1303                           CXXBasePath &Path) {
1304     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1305   };
1306 
1307   const CXXRecordDecl *ClassWithFields = nullptr;
1308   AccessSpecifier AS = AS_public;
1309   if (RD->hasDirectFields())
1310     // [dcl.decomp]p4:
1311     //   Otherwise, all of E's non-static data members shall be public direct
1312     //   members of E ...
1313     ClassWithFields = RD;
1314   else {
1315     //   ... or of ...
1316     CXXBasePaths Paths;
1317     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1318     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1319       // If no classes have fields, just decompose RD itself. (This will work
1320       // if and only if zero bindings were provided.)
1321       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1322     }
1323 
1324     CXXBasePath *BestPath = nullptr;
1325     for (auto &P : Paths) {
1326       if (!BestPath)
1327         BestPath = &P;
1328       else if (!S.Context.hasSameType(P.back().Base->getType(),
1329                                       BestPath->back().Base->getType())) {
1330         //   ... the same ...
1331         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1332           << false << RD << BestPath->back().Base->getType()
1333           << P.back().Base->getType();
1334         return DeclAccessPair();
1335       } else if (P.Access < BestPath->Access) {
1336         BestPath = &P;
1337       }
1338     }
1339 
1340     //   ... unambiguous ...
1341     QualType BaseType = BestPath->back().Base->getType();
1342     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1343       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1344         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1345       return DeclAccessPair();
1346     }
1347 
1348     //   ... [accessible, implied by other rules] base class of E.
1349     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1350                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1351     AS = BestPath->Access;
1352 
1353     ClassWithFields = BaseType->getAsCXXRecordDecl();
1354     S.BuildBasePathArray(Paths, BasePath);
1355   }
1356 
1357   // The above search did not check whether the selected class itself has base
1358   // classes with fields, so check that now.
1359   CXXBasePaths Paths;
1360   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1361     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1362       << (ClassWithFields == RD) << RD << ClassWithFields
1363       << Paths.front().back().Base->getType();
1364     return DeclAccessPair();
1365   }
1366 
1367   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1368 }
1369 
1370 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1371                                      ValueDecl *Src, QualType DecompType,
1372                                      const CXXRecordDecl *OrigRD) {
1373   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1374                             diag::err_incomplete_type))
1375     return true;
1376 
1377   CXXCastPath BasePath;
1378   DeclAccessPair BasePair =
1379       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1380   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1381   if (!RD)
1382     return true;
1383   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1384                                                  DecompType.getQualifiers());
1385 
1386   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1387     unsigned NumFields = llvm::count_if(
1388         RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1389     assert(Bindings.size() != NumFields);
1390     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1391         << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1392         << (NumFields < Bindings.size());
1393     return true;
1394   };
1395 
1396   //   all of E's non-static data members shall be [...] well-formed
1397   //   when named as e.name in the context of the structured binding,
1398   //   E shall not have an anonymous union member, ...
1399   unsigned I = 0;
1400   for (auto *FD : RD->fields()) {
1401     if (FD->isUnnamedBitfield())
1402       continue;
1403 
1404     // All the non-static data members are required to be nameable, so they
1405     // must all have names.
1406     if (!FD->getDeclName()) {
1407       if (RD->isLambda()) {
1408         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1409         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1410         return true;
1411       }
1412 
1413       if (FD->isAnonymousStructOrUnion()) {
1414         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1415           << DecompType << FD->getType()->isUnionType();
1416         S.Diag(FD->getLocation(), diag::note_declared_at);
1417         return true;
1418       }
1419 
1420       // FIXME: Are there any other ways we could have an anonymous member?
1421     }
1422 
1423     // We have a real field to bind.
1424     if (I >= Bindings.size())
1425       return DiagnoseBadNumberOfBindings();
1426     auto *B = Bindings[I++];
1427     SourceLocation Loc = B->getLocation();
1428 
1429     // The field must be accessible in the context of the structured binding.
1430     // We already checked that the base class is accessible.
1431     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1432     // const_cast here.
1433     S.CheckStructuredBindingMemberAccess(
1434         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1435         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1436                                      BasePair.getAccess(), FD->getAccess())));
1437 
1438     // Initialize the binding to Src.FD.
1439     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1440     if (E.isInvalid())
1441       return true;
1442     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1443                             VK_LValue, &BasePath);
1444     if (E.isInvalid())
1445       return true;
1446     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1447                                   CXXScopeSpec(), FD,
1448                                   DeclAccessPair::make(FD, FD->getAccess()),
1449                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1450     if (E.isInvalid())
1451       return true;
1452 
1453     // If the type of the member is T, the referenced type is cv T, where cv is
1454     // the cv-qualification of the decomposition expression.
1455     //
1456     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1457     // 'const' to the type of the field.
1458     Qualifiers Q = DecompType.getQualifiers();
1459     if (FD->isMutable())
1460       Q.removeConst();
1461     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1462   }
1463 
1464   if (I != Bindings.size())
1465     return DiagnoseBadNumberOfBindings();
1466 
1467   return false;
1468 }
1469 
1470 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1471   QualType DecompType = DD->getType();
1472 
1473   // If the type of the decomposition is dependent, then so is the type of
1474   // each binding.
1475   if (DecompType->isDependentType()) {
1476     for (auto *B : DD->bindings())
1477       B->setType(Context.DependentTy);
1478     return;
1479   }
1480 
1481   DecompType = DecompType.getNonReferenceType();
1482   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1483 
1484   // C++1z [dcl.decomp]/2:
1485   //   If E is an array type [...]
1486   // As an extension, we also support decomposition of built-in complex and
1487   // vector types.
1488   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1489     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1490       DD->setInvalidDecl();
1491     return;
1492   }
1493   if (auto *VT = DecompType->getAs<VectorType>()) {
1494     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1495       DD->setInvalidDecl();
1496     return;
1497   }
1498   if (auto *CT = DecompType->getAs<ComplexType>()) {
1499     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1500       DD->setInvalidDecl();
1501     return;
1502   }
1503 
1504   // C++1z [dcl.decomp]/3:
1505   //   if the expression std::tuple_size<E>::value is a well-formed integral
1506   //   constant expression, [...]
1507   llvm::APSInt TupleSize(32);
1508   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1509   case IsTupleLike::Error:
1510     DD->setInvalidDecl();
1511     return;
1512 
1513   case IsTupleLike::TupleLike:
1514     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1515       DD->setInvalidDecl();
1516     return;
1517 
1518   case IsTupleLike::NotTupleLike:
1519     break;
1520   }
1521 
1522   // C++1z [dcl.dcl]/8:
1523   //   [E shall be of array or non-union class type]
1524   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1525   if (!RD || RD->isUnion()) {
1526     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1527         << DD << !RD << DecompType;
1528     DD->setInvalidDecl();
1529     return;
1530   }
1531 
1532   // C++1z [dcl.decomp]/4:
1533   //   all of E's non-static data members shall be [...] direct members of
1534   //   E or of the same unambiguous public base class of E, ...
1535   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1536     DD->setInvalidDecl();
1537 }
1538 
1539 /// Merge the exception specifications of two variable declarations.
1540 ///
1541 /// This is called when there's a redeclaration of a VarDecl. The function
1542 /// checks if the redeclaration might have an exception specification and
1543 /// validates compatibility and merges the specs if necessary.
1544 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1545   // Shortcut if exceptions are disabled.
1546   if (!getLangOpts().CXXExceptions)
1547     return;
1548 
1549   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1550          "Should only be called if types are otherwise the same.");
1551 
1552   QualType NewType = New->getType();
1553   QualType OldType = Old->getType();
1554 
1555   // We're only interested in pointers and references to functions, as well
1556   // as pointers to member functions.
1557   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1558     NewType = R->getPointeeType();
1559     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1560   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1561     NewType = P->getPointeeType();
1562     OldType = OldType->castAs<PointerType>()->getPointeeType();
1563   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1564     NewType = M->getPointeeType();
1565     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1566   }
1567 
1568   if (!NewType->isFunctionProtoType())
1569     return;
1570 
1571   // There's lots of special cases for functions. For function pointers, system
1572   // libraries are hopefully not as broken so that we don't need these
1573   // workarounds.
1574   if (CheckEquivalentExceptionSpec(
1575         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1576         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1577     New->setInvalidDecl();
1578   }
1579 }
1580 
1581 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1582 /// function declaration are well-formed according to C++
1583 /// [dcl.fct.default].
1584 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1585   unsigned NumParams = FD->getNumParams();
1586   unsigned ParamIdx = 0;
1587 
1588   // This checking doesn't make sense for explicit specializations; their
1589   // default arguments are determined by the declaration we're specializing,
1590   // not by FD.
1591   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1592     return;
1593   if (auto *FTD = FD->getDescribedFunctionTemplate())
1594     if (FTD->isMemberSpecialization())
1595       return;
1596 
1597   // Find first parameter with a default argument
1598   for (; ParamIdx < NumParams; ++ParamIdx) {
1599     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1600     if (Param->hasDefaultArg())
1601       break;
1602   }
1603 
1604   // C++20 [dcl.fct.default]p4:
1605   //   In a given function declaration, each parameter subsequent to a parameter
1606   //   with a default argument shall have a default argument supplied in this or
1607   //   a previous declaration, unless the parameter was expanded from a
1608   //   parameter pack, or shall be a function parameter pack.
1609   for (; ParamIdx < NumParams; ++ParamIdx) {
1610     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1611     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1612         !(CurrentInstantiationScope &&
1613           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1614       if (Param->isInvalidDecl())
1615         /* We already complained about this parameter. */;
1616       else if (Param->getIdentifier())
1617         Diag(Param->getLocation(),
1618              diag::err_param_default_argument_missing_name)
1619           << Param->getIdentifier();
1620       else
1621         Diag(Param->getLocation(),
1622              diag::err_param_default_argument_missing);
1623     }
1624   }
1625 }
1626 
1627 /// Check that the given type is a literal type. Issue a diagnostic if not,
1628 /// if Kind is Diagnose.
1629 /// \return \c true if a problem has been found (and optionally diagnosed).
1630 template <typename... Ts>
1631 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1632                              SourceLocation Loc, QualType T, unsigned DiagID,
1633                              Ts &&...DiagArgs) {
1634   if (T->isDependentType())
1635     return false;
1636 
1637   switch (Kind) {
1638   case Sema::CheckConstexprKind::Diagnose:
1639     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1640                                       std::forward<Ts>(DiagArgs)...);
1641 
1642   case Sema::CheckConstexprKind::CheckValid:
1643     return !T->isLiteralType(SemaRef.Context);
1644   }
1645 
1646   llvm_unreachable("unknown CheckConstexprKind");
1647 }
1648 
1649 /// Determine whether a destructor cannot be constexpr due to
1650 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1651                                                const CXXDestructorDecl *DD,
1652                                                Sema::CheckConstexprKind Kind) {
1653   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1654     const CXXRecordDecl *RD =
1655         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1656     if (!RD || RD->hasConstexprDestructor())
1657       return true;
1658 
1659     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1660       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1661           << static_cast<int>(DD->getConstexprKind()) << !FD
1662           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1663       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1664           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1665     }
1666     return false;
1667   };
1668 
1669   const CXXRecordDecl *RD = DD->getParent();
1670   for (const CXXBaseSpecifier &B : RD->bases())
1671     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1672       return false;
1673   for (const FieldDecl *FD : RD->fields())
1674     if (!Check(FD->getLocation(), FD->getType(), FD))
1675       return false;
1676   return true;
1677 }
1678 
1679 /// Check whether a function's parameter types are all literal types. If so,
1680 /// return true. If not, produce a suitable diagnostic and return false.
1681 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1682                                          const FunctionDecl *FD,
1683                                          Sema::CheckConstexprKind Kind) {
1684   unsigned ArgIndex = 0;
1685   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1686   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1687                                               e = FT->param_type_end();
1688        i != e; ++i, ++ArgIndex) {
1689     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1690     SourceLocation ParamLoc = PD->getLocation();
1691     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1692                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1693                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1694                          FD->isConsteval()))
1695       return false;
1696   }
1697   return true;
1698 }
1699 
1700 /// Check whether a function's return type is a literal type. If so, return
1701 /// true. If not, produce a suitable diagnostic and return false.
1702 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1703                                      Sema::CheckConstexprKind Kind) {
1704   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1705                        diag::err_constexpr_non_literal_return,
1706                        FD->isConsteval()))
1707     return false;
1708   return true;
1709 }
1710 
1711 /// Get diagnostic %select index for tag kind for
1712 /// record diagnostic message.
1713 /// WARNING: Indexes apply to particular diagnostics only!
1714 ///
1715 /// \returns diagnostic %select index.
1716 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1717   switch (Tag) {
1718   case TTK_Struct: return 0;
1719   case TTK_Interface: return 1;
1720   case TTK_Class:  return 2;
1721   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1722   }
1723 }
1724 
1725 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1726                                        Stmt *Body,
1727                                        Sema::CheckConstexprKind Kind);
1728 
1729 // Check whether a function declaration satisfies the requirements of a
1730 // constexpr function definition or a constexpr constructor definition. If so,
1731 // return true. If not, produce appropriate diagnostics (unless asked not to by
1732 // Kind) and return false.
1733 //
1734 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1735 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1736                                             CheckConstexprKind Kind) {
1737   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1738   if (MD && MD->isInstance()) {
1739     // C++11 [dcl.constexpr]p4:
1740     //  The definition of a constexpr constructor shall satisfy the following
1741     //  constraints:
1742     //  - the class shall not have any virtual base classes;
1743     //
1744     // FIXME: This only applies to constructors and destructors, not arbitrary
1745     // member functions.
1746     const CXXRecordDecl *RD = MD->getParent();
1747     if (RD->getNumVBases()) {
1748       if (Kind == CheckConstexprKind::CheckValid)
1749         return false;
1750 
1751       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1752         << isa<CXXConstructorDecl>(NewFD)
1753         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1754       for (const auto &I : RD->vbases())
1755         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1756             << I.getSourceRange();
1757       return false;
1758     }
1759   }
1760 
1761   if (!isa<CXXConstructorDecl>(NewFD)) {
1762     // C++11 [dcl.constexpr]p3:
1763     //  The definition of a constexpr function shall satisfy the following
1764     //  constraints:
1765     // - it shall not be virtual; (removed in C++20)
1766     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1767     if (Method && Method->isVirtual()) {
1768       if (getLangOpts().CPlusPlus20) {
1769         if (Kind == CheckConstexprKind::Diagnose)
1770           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1771       } else {
1772         if (Kind == CheckConstexprKind::CheckValid)
1773           return false;
1774 
1775         Method = Method->getCanonicalDecl();
1776         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1777 
1778         // If it's not obvious why this function is virtual, find an overridden
1779         // function which uses the 'virtual' keyword.
1780         const CXXMethodDecl *WrittenVirtual = Method;
1781         while (!WrittenVirtual->isVirtualAsWritten())
1782           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1783         if (WrittenVirtual != Method)
1784           Diag(WrittenVirtual->getLocation(),
1785                diag::note_overridden_virtual_function);
1786         return false;
1787       }
1788     }
1789 
1790     // - its return type shall be a literal type;
1791     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1792       return false;
1793   }
1794 
1795   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1796     // A destructor can be constexpr only if the defaulted destructor could be;
1797     // we don't need to check the members and bases if we already know they all
1798     // have constexpr destructors.
1799     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1800       if (Kind == CheckConstexprKind::CheckValid)
1801         return false;
1802       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1803         return false;
1804     }
1805   }
1806 
1807   // - each of its parameter types shall be a literal type;
1808   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1809     return false;
1810 
1811   Stmt *Body = NewFD->getBody();
1812   assert(Body &&
1813          "CheckConstexprFunctionDefinition called on function with no body");
1814   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1815 }
1816 
1817 /// Check the given declaration statement is legal within a constexpr function
1818 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1819 ///
1820 /// \return true if the body is OK (maybe only as an extension), false if we
1821 ///         have diagnosed a problem.
1822 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1823                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1824                                    Sema::CheckConstexprKind Kind) {
1825   // C++11 [dcl.constexpr]p3 and p4:
1826   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1827   //  contain only
1828   for (const auto *DclIt : DS->decls()) {
1829     switch (DclIt->getKind()) {
1830     case Decl::StaticAssert:
1831     case Decl::Using:
1832     case Decl::UsingShadow:
1833     case Decl::UsingDirective:
1834     case Decl::UnresolvedUsingTypename:
1835     case Decl::UnresolvedUsingValue:
1836     case Decl::UsingEnum:
1837       //   - static_assert-declarations
1838       //   - using-declarations,
1839       //   - using-directives,
1840       //   - using-enum-declaration
1841       continue;
1842 
1843     case Decl::Typedef:
1844     case Decl::TypeAlias: {
1845       //   - typedef declarations and alias-declarations that do not define
1846       //     classes or enumerations,
1847       const auto *TN = cast<TypedefNameDecl>(DclIt);
1848       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1849         // Don't allow variably-modified types in constexpr functions.
1850         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1851           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1852           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1853             << TL.getSourceRange() << TL.getType()
1854             << isa<CXXConstructorDecl>(Dcl);
1855         }
1856         return false;
1857       }
1858       continue;
1859     }
1860 
1861     case Decl::Enum:
1862     case Decl::CXXRecord:
1863       // C++1y allows types to be defined, not just declared.
1864       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1865         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866           SemaRef.Diag(DS->getBeginLoc(),
1867                        SemaRef.getLangOpts().CPlusPlus14
1868                            ? diag::warn_cxx11_compat_constexpr_type_definition
1869                            : diag::ext_constexpr_type_definition)
1870               << isa<CXXConstructorDecl>(Dcl);
1871         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1872           return false;
1873         }
1874       }
1875       continue;
1876 
1877     case Decl::EnumConstant:
1878     case Decl::IndirectField:
1879     case Decl::ParmVar:
1880       // These can only appear with other declarations which are banned in
1881       // C++11 and permitted in C++1y, so ignore them.
1882       continue;
1883 
1884     case Decl::Var:
1885     case Decl::Decomposition: {
1886       // C++1y [dcl.constexpr]p3 allows anything except:
1887       //   a definition of a variable of non-literal type or of static or
1888       //   thread storage duration or [before C++2a] for which no
1889       //   initialization is performed.
1890       const auto *VD = cast<VarDecl>(DclIt);
1891       if (VD->isThisDeclarationADefinition()) {
1892         if (VD->isStaticLocal()) {
1893           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1894             SemaRef.Diag(VD->getLocation(),
1895                          SemaRef.getLangOpts().CPlusPlus2b
1896                              ? diag::warn_cxx20_compat_constexpr_var
1897                              : diag::ext_constexpr_static_var)
1898                 << isa<CXXConstructorDecl>(Dcl)
1899                 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1900           } else if (!SemaRef.getLangOpts().CPlusPlus2b) {
1901             return false;
1902           }
1903         }
1904         if (SemaRef.LangOpts.CPlusPlus2b) {
1905           CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1906                            diag::warn_cxx20_compat_constexpr_var,
1907                            isa<CXXConstructorDecl>(Dcl),
1908                            /*variable of non-literal type*/ 2);
1909         } else if (CheckLiteralType(
1910                        SemaRef, Kind, VD->getLocation(), VD->getType(),
1911                        diag::err_constexpr_local_var_non_literal_type,
1912                        isa<CXXConstructorDecl>(Dcl))) {
1913           return false;
1914         }
1915         if (!VD->getType()->isDependentType() &&
1916             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1917           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1918             SemaRef.Diag(
1919                 VD->getLocation(),
1920                 SemaRef.getLangOpts().CPlusPlus20
1921                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1922                     : diag::ext_constexpr_local_var_no_init)
1923                 << isa<CXXConstructorDecl>(Dcl);
1924           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1925             return false;
1926           }
1927           continue;
1928         }
1929       }
1930       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1931         SemaRef.Diag(VD->getLocation(),
1932                      SemaRef.getLangOpts().CPlusPlus14
1933                       ? diag::warn_cxx11_compat_constexpr_local_var
1934                       : diag::ext_constexpr_local_var)
1935           << isa<CXXConstructorDecl>(Dcl);
1936       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1937         return false;
1938       }
1939       continue;
1940     }
1941 
1942     case Decl::NamespaceAlias:
1943     case Decl::Function:
1944       // These are disallowed in C++11 and permitted in C++1y. Allow them
1945       // everywhere as an extension.
1946       if (!Cxx1yLoc.isValid())
1947         Cxx1yLoc = DS->getBeginLoc();
1948       continue;
1949 
1950     default:
1951       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1952         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1953             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1954       }
1955       return false;
1956     }
1957   }
1958 
1959   return true;
1960 }
1961 
1962 /// Check that the given field is initialized within a constexpr constructor.
1963 ///
1964 /// \param Dcl The constexpr constructor being checked.
1965 /// \param Field The field being checked. This may be a member of an anonymous
1966 ///        struct or union nested within the class being checked.
1967 /// \param Inits All declarations, including anonymous struct/union members and
1968 ///        indirect members, for which any initialization was provided.
1969 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1970 ///        multiple notes for different members to the same error.
1971 /// \param Kind Whether we're diagnosing a constructor as written or determining
1972 ///        whether the formal requirements are satisfied.
1973 /// \return \c false if we're checking for validity and the constructor does
1974 ///         not satisfy the requirements on a constexpr constructor.
1975 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1976                                           const FunctionDecl *Dcl,
1977                                           FieldDecl *Field,
1978                                           llvm::SmallSet<Decl*, 16> &Inits,
1979                                           bool &Diagnosed,
1980                                           Sema::CheckConstexprKind Kind) {
1981   // In C++20 onwards, there's nothing to check for validity.
1982   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1983       SemaRef.getLangOpts().CPlusPlus20)
1984     return true;
1985 
1986   if (Field->isInvalidDecl())
1987     return true;
1988 
1989   if (Field->isUnnamedBitfield())
1990     return true;
1991 
1992   // Anonymous unions with no variant members and empty anonymous structs do not
1993   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1994   // indirect fields don't need initializing.
1995   if (Field->isAnonymousStructOrUnion() &&
1996       (Field->getType()->isUnionType()
1997            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1998            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1999     return true;
2000 
2001   if (!Inits.count(Field)) {
2002     if (Kind == Sema::CheckConstexprKind::Diagnose) {
2003       if (!Diagnosed) {
2004         SemaRef.Diag(Dcl->getLocation(),
2005                      SemaRef.getLangOpts().CPlusPlus20
2006                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2007                          : diag::ext_constexpr_ctor_missing_init);
2008         Diagnosed = true;
2009       }
2010       SemaRef.Diag(Field->getLocation(),
2011                    diag::note_constexpr_ctor_missing_init);
2012     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2013       return false;
2014     }
2015   } else if (Field->isAnonymousStructOrUnion()) {
2016     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2017     for (auto *I : RD->fields())
2018       // If an anonymous union contains an anonymous struct of which any member
2019       // is initialized, all members must be initialized.
2020       if (!RD->isUnion() || Inits.count(I))
2021         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2022                                            Kind))
2023           return false;
2024   }
2025   return true;
2026 }
2027 
2028 /// Check the provided statement is allowed in a constexpr function
2029 /// definition.
2030 static bool
2031 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2032                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2033                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2034                            SourceLocation &Cxx2bLoc,
2035                            Sema::CheckConstexprKind Kind) {
2036   // - its function-body shall be [...] a compound-statement that contains only
2037   switch (S->getStmtClass()) {
2038   case Stmt::NullStmtClass:
2039     //   - null statements,
2040     return true;
2041 
2042   case Stmt::DeclStmtClass:
2043     //   - static_assert-declarations
2044     //   - using-declarations,
2045     //   - using-directives,
2046     //   - typedef declarations and alias-declarations that do not define
2047     //     classes or enumerations,
2048     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2049       return false;
2050     return true;
2051 
2052   case Stmt::ReturnStmtClass:
2053     //   - and exactly one return statement;
2054     if (isa<CXXConstructorDecl>(Dcl)) {
2055       // C++1y allows return statements in constexpr constructors.
2056       if (!Cxx1yLoc.isValid())
2057         Cxx1yLoc = S->getBeginLoc();
2058       return true;
2059     }
2060 
2061     ReturnStmts.push_back(S->getBeginLoc());
2062     return true;
2063 
2064   case Stmt::AttributedStmtClass:
2065     // Attributes on a statement don't affect its formal kind and hence don't
2066     // affect its validity in a constexpr function.
2067     return CheckConstexprFunctionStmt(
2068         SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2069         Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2070 
2071   case Stmt::CompoundStmtClass: {
2072     // C++1y allows compound-statements.
2073     if (!Cxx1yLoc.isValid())
2074       Cxx1yLoc = S->getBeginLoc();
2075 
2076     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2077     for (auto *BodyIt : CompStmt->body()) {
2078       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2079                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2080         return false;
2081     }
2082     return true;
2083   }
2084 
2085   case Stmt::IfStmtClass: {
2086     // C++1y allows if-statements.
2087     if (!Cxx1yLoc.isValid())
2088       Cxx1yLoc = S->getBeginLoc();
2089 
2090     IfStmt *If = cast<IfStmt>(S);
2091     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2092                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2093       return false;
2094     if (If->getElse() &&
2095         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2096                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2097       return false;
2098     return true;
2099   }
2100 
2101   case Stmt::WhileStmtClass:
2102   case Stmt::DoStmtClass:
2103   case Stmt::ForStmtClass:
2104   case Stmt::CXXForRangeStmtClass:
2105   case Stmt::ContinueStmtClass:
2106     // C++1y allows all of these. We don't allow them as extensions in C++11,
2107     // because they don't make sense without variable mutation.
2108     if (!SemaRef.getLangOpts().CPlusPlus14)
2109       break;
2110     if (!Cxx1yLoc.isValid())
2111       Cxx1yLoc = S->getBeginLoc();
2112     for (Stmt *SubStmt : S->children()) {
2113       if (SubStmt &&
2114           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2115                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2116         return false;
2117     }
2118     return true;
2119 
2120   case Stmt::SwitchStmtClass:
2121   case Stmt::CaseStmtClass:
2122   case Stmt::DefaultStmtClass:
2123   case Stmt::BreakStmtClass:
2124     // C++1y allows switch-statements, and since they don't need variable
2125     // mutation, we can reasonably allow them in C++11 as an extension.
2126     if (!Cxx1yLoc.isValid())
2127       Cxx1yLoc = S->getBeginLoc();
2128     for (Stmt *SubStmt : S->children()) {
2129       if (SubStmt &&
2130           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2131                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2132         return false;
2133     }
2134     return true;
2135 
2136   case Stmt::LabelStmtClass:
2137   case Stmt::GotoStmtClass:
2138     if (Cxx2bLoc.isInvalid())
2139       Cxx2bLoc = S->getBeginLoc();
2140     for (Stmt *SubStmt : S->children()) {
2141       if (SubStmt &&
2142           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2143                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2144         return false;
2145     }
2146     return true;
2147 
2148   case Stmt::GCCAsmStmtClass:
2149   case Stmt::MSAsmStmtClass:
2150     // C++2a allows inline assembly statements.
2151   case Stmt::CXXTryStmtClass:
2152     if (Cxx2aLoc.isInvalid())
2153       Cxx2aLoc = S->getBeginLoc();
2154     for (Stmt *SubStmt : S->children()) {
2155       if (SubStmt &&
2156           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2157                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2158         return false;
2159     }
2160     return true;
2161 
2162   case Stmt::CXXCatchStmtClass:
2163     // Do not bother checking the language mode (already covered by the
2164     // try block check).
2165     if (!CheckConstexprFunctionStmt(
2166             SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2167             Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2168       return false;
2169     return true;
2170 
2171   default:
2172     if (!isa<Expr>(S))
2173       break;
2174 
2175     // C++1y allows expression-statements.
2176     if (!Cxx1yLoc.isValid())
2177       Cxx1yLoc = S->getBeginLoc();
2178     return true;
2179   }
2180 
2181   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2182     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2183         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2184   }
2185   return false;
2186 }
2187 
2188 /// Check the body for the given constexpr function declaration only contains
2189 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2190 ///
2191 /// \return true if the body is OK, false if we have found or diagnosed a
2192 /// problem.
2193 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2194                                        Stmt *Body,
2195                                        Sema::CheckConstexprKind Kind) {
2196   SmallVector<SourceLocation, 4> ReturnStmts;
2197 
2198   if (isa<CXXTryStmt>(Body)) {
2199     // C++11 [dcl.constexpr]p3:
2200     //  The definition of a constexpr function shall satisfy the following
2201     //  constraints: [...]
2202     // - its function-body shall be = delete, = default, or a
2203     //   compound-statement
2204     //
2205     // C++11 [dcl.constexpr]p4:
2206     //  In the definition of a constexpr constructor, [...]
2207     // - its function-body shall not be a function-try-block;
2208     //
2209     // This restriction is lifted in C++2a, as long as inner statements also
2210     // apply the general constexpr rules.
2211     switch (Kind) {
2212     case Sema::CheckConstexprKind::CheckValid:
2213       if (!SemaRef.getLangOpts().CPlusPlus20)
2214         return false;
2215       break;
2216 
2217     case Sema::CheckConstexprKind::Diagnose:
2218       SemaRef.Diag(Body->getBeginLoc(),
2219            !SemaRef.getLangOpts().CPlusPlus20
2220                ? diag::ext_constexpr_function_try_block_cxx20
2221                : diag::warn_cxx17_compat_constexpr_function_try_block)
2222           << isa<CXXConstructorDecl>(Dcl);
2223       break;
2224     }
2225   }
2226 
2227   // - its function-body shall be [...] a compound-statement that contains only
2228   //   [... list of cases ...]
2229   //
2230   // Note that walking the children here is enough to properly check for
2231   // CompoundStmt and CXXTryStmt body.
2232   SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2233   for (Stmt *SubStmt : Body->children()) {
2234     if (SubStmt &&
2235         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2236                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2237       return false;
2238   }
2239 
2240   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2241     // If this is only valid as an extension, report that we don't satisfy the
2242     // constraints of the current language.
2243     if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) ||
2244         (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2245         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2246       return false;
2247   } else if (Cxx2bLoc.isValid()) {
2248     SemaRef.Diag(Cxx2bLoc,
2249                  SemaRef.getLangOpts().CPlusPlus2b
2250                      ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2251                      : diag::ext_constexpr_body_invalid_stmt_cxx2b)
2252         << isa<CXXConstructorDecl>(Dcl);
2253   } else if (Cxx2aLoc.isValid()) {
2254     SemaRef.Diag(Cxx2aLoc,
2255          SemaRef.getLangOpts().CPlusPlus20
2256            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2257            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2258       << isa<CXXConstructorDecl>(Dcl);
2259   } else if (Cxx1yLoc.isValid()) {
2260     SemaRef.Diag(Cxx1yLoc,
2261          SemaRef.getLangOpts().CPlusPlus14
2262            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2263            : diag::ext_constexpr_body_invalid_stmt)
2264       << isa<CXXConstructorDecl>(Dcl);
2265   }
2266 
2267   if (const CXXConstructorDecl *Constructor
2268         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2269     const CXXRecordDecl *RD = Constructor->getParent();
2270     // DR1359:
2271     // - every non-variant non-static data member and base class sub-object
2272     //   shall be initialized;
2273     // DR1460:
2274     // - if the class is a union having variant members, exactly one of them
2275     //   shall be initialized;
2276     if (RD->isUnion()) {
2277       if (Constructor->getNumCtorInitializers() == 0 &&
2278           RD->hasVariantMembers()) {
2279         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2280           SemaRef.Diag(
2281               Dcl->getLocation(),
2282               SemaRef.getLangOpts().CPlusPlus20
2283                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2284                   : diag::ext_constexpr_union_ctor_no_init);
2285         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2286           return false;
2287         }
2288       }
2289     } else if (!Constructor->isDependentContext() &&
2290                !Constructor->isDelegatingConstructor()) {
2291       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2292 
2293       // Skip detailed checking if we have enough initializers, and we would
2294       // allow at most one initializer per member.
2295       bool AnyAnonStructUnionMembers = false;
2296       unsigned Fields = 0;
2297       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2298            E = RD->field_end(); I != E; ++I, ++Fields) {
2299         if (I->isAnonymousStructOrUnion()) {
2300           AnyAnonStructUnionMembers = true;
2301           break;
2302         }
2303       }
2304       // DR1460:
2305       // - if the class is a union-like class, but is not a union, for each of
2306       //   its anonymous union members having variant members, exactly one of
2307       //   them shall be initialized;
2308       if (AnyAnonStructUnionMembers ||
2309           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2310         // Check initialization of non-static data members. Base classes are
2311         // always initialized so do not need to be checked. Dependent bases
2312         // might not have initializers in the member initializer list.
2313         llvm::SmallSet<Decl*, 16> Inits;
2314         for (const auto *I: Constructor->inits()) {
2315           if (FieldDecl *FD = I->getMember())
2316             Inits.insert(FD);
2317           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2318             Inits.insert(ID->chain_begin(), ID->chain_end());
2319         }
2320 
2321         bool Diagnosed = false;
2322         for (auto *I : RD->fields())
2323           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2324                                              Kind))
2325             return false;
2326       }
2327     }
2328   } else {
2329     if (ReturnStmts.empty()) {
2330       // C++1y doesn't require constexpr functions to contain a 'return'
2331       // statement. We still do, unless the return type might be void, because
2332       // otherwise if there's no return statement, the function cannot
2333       // be used in a core constant expression.
2334       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2335                 (Dcl->getReturnType()->isVoidType() ||
2336                  Dcl->getReturnType()->isDependentType());
2337       switch (Kind) {
2338       case Sema::CheckConstexprKind::Diagnose:
2339         SemaRef.Diag(Dcl->getLocation(),
2340                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2341                         : diag::err_constexpr_body_no_return)
2342             << Dcl->isConsteval();
2343         if (!OK)
2344           return false;
2345         break;
2346 
2347       case Sema::CheckConstexprKind::CheckValid:
2348         // The formal requirements don't include this rule in C++14, even
2349         // though the "must be able to produce a constant expression" rules
2350         // still imply it in some cases.
2351         if (!SemaRef.getLangOpts().CPlusPlus14)
2352           return false;
2353         break;
2354       }
2355     } else if (ReturnStmts.size() > 1) {
2356       switch (Kind) {
2357       case Sema::CheckConstexprKind::Diagnose:
2358         SemaRef.Diag(
2359             ReturnStmts.back(),
2360             SemaRef.getLangOpts().CPlusPlus14
2361                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2362                 : diag::ext_constexpr_body_multiple_return);
2363         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2364           SemaRef.Diag(ReturnStmts[I],
2365                        diag::note_constexpr_body_previous_return);
2366         break;
2367 
2368       case Sema::CheckConstexprKind::CheckValid:
2369         if (!SemaRef.getLangOpts().CPlusPlus14)
2370           return false;
2371         break;
2372       }
2373     }
2374   }
2375 
2376   // C++11 [dcl.constexpr]p5:
2377   //   if no function argument values exist such that the function invocation
2378   //   substitution would produce a constant expression, the program is
2379   //   ill-formed; no diagnostic required.
2380   // C++11 [dcl.constexpr]p3:
2381   //   - every constructor call and implicit conversion used in initializing the
2382   //     return value shall be one of those allowed in a constant expression.
2383   // C++11 [dcl.constexpr]p4:
2384   //   - every constructor involved in initializing non-static data members and
2385   //     base class sub-objects shall be a constexpr constructor.
2386   //
2387   // Note that this rule is distinct from the "requirements for a constexpr
2388   // function", so is not checked in CheckValid mode.
2389   SmallVector<PartialDiagnosticAt, 8> Diags;
2390   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2391       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2392     SemaRef.Diag(Dcl->getLocation(),
2393                  diag::ext_constexpr_function_never_constant_expr)
2394         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2395     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2396       SemaRef.Diag(Diags[I].first, Diags[I].second);
2397     // Don't return false here: we allow this for compatibility in
2398     // system headers.
2399   }
2400 
2401   return true;
2402 }
2403 
2404 /// Get the class that is directly named by the current context. This is the
2405 /// class for which an unqualified-id in this scope could name a constructor
2406 /// or destructor.
2407 ///
2408 /// If the scope specifier denotes a class, this will be that class.
2409 /// If the scope specifier is empty, this will be the class whose
2410 /// member-specification we are currently within. Otherwise, there
2411 /// is no such class.
2412 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2413   assert(getLangOpts().CPlusPlus && "No class names in C!");
2414 
2415   if (SS && SS->isInvalid())
2416     return nullptr;
2417 
2418   if (SS && SS->isNotEmpty()) {
2419     DeclContext *DC = computeDeclContext(*SS, true);
2420     return dyn_cast_or_null<CXXRecordDecl>(DC);
2421   }
2422 
2423   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2424 }
2425 
2426 /// isCurrentClassName - Determine whether the identifier II is the
2427 /// name of the class type currently being defined. In the case of
2428 /// nested classes, this will only return true if II is the name of
2429 /// the innermost class.
2430 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2431                               const CXXScopeSpec *SS) {
2432   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2433   return CurDecl && &II == CurDecl->getIdentifier();
2434 }
2435 
2436 /// Determine whether the identifier II is a typo for the name of
2437 /// the class type currently being defined. If so, update it to the identifier
2438 /// that should have been used.
2439 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2440   assert(getLangOpts().CPlusPlus && "No class names in C!");
2441 
2442   if (!getLangOpts().SpellChecking)
2443     return false;
2444 
2445   CXXRecordDecl *CurDecl;
2446   if (SS && SS->isSet() && !SS->isInvalid()) {
2447     DeclContext *DC = computeDeclContext(*SS, true);
2448     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2449   } else
2450     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2451 
2452   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2453       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2454           < II->getLength()) {
2455     II = CurDecl->getIdentifier();
2456     return true;
2457   }
2458 
2459   return false;
2460 }
2461 
2462 /// Determine whether the given class is a base class of the given
2463 /// class, including looking at dependent bases.
2464 static bool findCircularInheritance(const CXXRecordDecl *Class,
2465                                     const CXXRecordDecl *Current) {
2466   SmallVector<const CXXRecordDecl*, 8> Queue;
2467 
2468   Class = Class->getCanonicalDecl();
2469   while (true) {
2470     for (const auto &I : Current->bases()) {
2471       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2472       if (!Base)
2473         continue;
2474 
2475       Base = Base->getDefinition();
2476       if (!Base)
2477         continue;
2478 
2479       if (Base->getCanonicalDecl() == Class)
2480         return true;
2481 
2482       Queue.push_back(Base);
2483     }
2484 
2485     if (Queue.empty())
2486       return false;
2487 
2488     Current = Queue.pop_back_val();
2489   }
2490 
2491   return false;
2492 }
2493 
2494 /// Check the validity of a C++ base class specifier.
2495 ///
2496 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2497 /// and returns NULL otherwise.
2498 CXXBaseSpecifier *
2499 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2500                          SourceRange SpecifierRange,
2501                          bool Virtual, AccessSpecifier Access,
2502                          TypeSourceInfo *TInfo,
2503                          SourceLocation EllipsisLoc) {
2504   QualType BaseType = TInfo->getType();
2505   if (BaseType->containsErrors()) {
2506     // Already emitted a diagnostic when parsing the error type.
2507     return nullptr;
2508   }
2509   // C++ [class.union]p1:
2510   //   A union shall not have base classes.
2511   if (Class->isUnion()) {
2512     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2513       << SpecifierRange;
2514     return nullptr;
2515   }
2516 
2517   if (EllipsisLoc.isValid() &&
2518       !TInfo->getType()->containsUnexpandedParameterPack()) {
2519     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2520       << TInfo->getTypeLoc().getSourceRange();
2521     EllipsisLoc = SourceLocation();
2522   }
2523 
2524   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2525 
2526   if (BaseType->isDependentType()) {
2527     // Make sure that we don't have circular inheritance among our dependent
2528     // bases. For non-dependent bases, the check for completeness below handles
2529     // this.
2530     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2531       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2532           ((BaseDecl = BaseDecl->getDefinition()) &&
2533            findCircularInheritance(Class, BaseDecl))) {
2534         Diag(BaseLoc, diag::err_circular_inheritance)
2535           << BaseType << Context.getTypeDeclType(Class);
2536 
2537         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2538           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2539             << BaseType;
2540 
2541         return nullptr;
2542       }
2543     }
2544 
2545     // Make sure that we don't make an ill-formed AST where the type of the
2546     // Class is non-dependent and its attached base class specifier is an
2547     // dependent type, which violates invariants in many clang code paths (e.g.
2548     // constexpr evaluator). If this case happens (in errory-recovery mode), we
2549     // explicitly mark the Class decl invalid. The diagnostic was already
2550     // emitted.
2551     if (!Class->getTypeForDecl()->isDependentType())
2552       Class->setInvalidDecl();
2553     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2554                                           Class->getTagKind() == TTK_Class,
2555                                           Access, TInfo, EllipsisLoc);
2556   }
2557 
2558   // Base specifiers must be record types.
2559   if (!BaseType->isRecordType()) {
2560     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2561     return nullptr;
2562   }
2563 
2564   // C++ [class.union]p1:
2565   //   A union shall not be used as a base class.
2566   if (BaseType->isUnionType()) {
2567     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2568     return nullptr;
2569   }
2570 
2571   // For the MS ABI, propagate DLL attributes to base class templates.
2572   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2573     if (Attr *ClassAttr = getDLLAttr(Class)) {
2574       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2575               BaseType->getAsCXXRecordDecl())) {
2576         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2577                                             BaseLoc);
2578       }
2579     }
2580   }
2581 
2582   // C++ [class.derived]p2:
2583   //   The class-name in a base-specifier shall not be an incompletely
2584   //   defined class.
2585   if (RequireCompleteType(BaseLoc, BaseType,
2586                           diag::err_incomplete_base_class, SpecifierRange)) {
2587     Class->setInvalidDecl();
2588     return nullptr;
2589   }
2590 
2591   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2592   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2593   assert(BaseDecl && "Record type has no declaration");
2594   BaseDecl = BaseDecl->getDefinition();
2595   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2596   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2597   assert(CXXBaseDecl && "Base type is not a C++ type");
2598 
2599   // Microsoft docs say:
2600   // "If a base-class has a code_seg attribute, derived classes must have the
2601   // same attribute."
2602   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2603   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2604   if ((DerivedCSA || BaseCSA) &&
2605       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2606     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2607     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2608       << CXXBaseDecl;
2609     return nullptr;
2610   }
2611 
2612   // A class which contains a flexible array member is not suitable for use as a
2613   // base class:
2614   //   - If the layout determines that a base comes before another base,
2615   //     the flexible array member would index into the subsequent base.
2616   //   - If the layout determines that base comes before the derived class,
2617   //     the flexible array member would index into the derived class.
2618   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2619     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2620       << CXXBaseDecl->getDeclName();
2621     return nullptr;
2622   }
2623 
2624   // C++ [class]p3:
2625   //   If a class is marked final and it appears as a base-type-specifier in
2626   //   base-clause, the program is ill-formed.
2627   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2628     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2629       << CXXBaseDecl->getDeclName()
2630       << FA->isSpelledAsSealed();
2631     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2632         << CXXBaseDecl->getDeclName() << FA->getRange();
2633     return nullptr;
2634   }
2635 
2636   if (BaseDecl->isInvalidDecl())
2637     Class->setInvalidDecl();
2638 
2639   // Create the base specifier.
2640   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2641                                         Class->getTagKind() == TTK_Class,
2642                                         Access, TInfo, EllipsisLoc);
2643 }
2644 
2645 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2646 /// one entry in the base class list of a class specifier, for
2647 /// example:
2648 ///    class foo : public bar, virtual private baz {
2649 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2650 BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2651                                     const ParsedAttributesView &Attributes,
2652                                     bool Virtual, AccessSpecifier Access,
2653                                     ParsedType basetype, SourceLocation BaseLoc,
2654                                     SourceLocation EllipsisLoc) {
2655   if (!classdecl)
2656     return true;
2657 
2658   AdjustDeclIfTemplate(classdecl);
2659   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2660   if (!Class)
2661     return true;
2662 
2663   // We haven't yet attached the base specifiers.
2664   Class->setIsParsingBaseSpecifiers();
2665 
2666   // We do not support any C++11 attributes on base-specifiers yet.
2667   // Diagnose any attributes we see.
2668   for (const ParsedAttr &AL : Attributes) {
2669     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2670       continue;
2671     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2672                           ? (unsigned)diag::warn_unknown_attribute_ignored
2673                           : (unsigned)diag::err_base_specifier_attribute)
2674         << AL << AL.getRange();
2675   }
2676 
2677   TypeSourceInfo *TInfo = nullptr;
2678   GetTypeFromParser(basetype, &TInfo);
2679 
2680   if (EllipsisLoc.isInvalid() &&
2681       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2682                                       UPPC_BaseType))
2683     return true;
2684 
2685   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2686                                                       Virtual, Access, TInfo,
2687                                                       EllipsisLoc))
2688     return BaseSpec;
2689   else
2690     Class->setInvalidDecl();
2691 
2692   return true;
2693 }
2694 
2695 /// Use small set to collect indirect bases.  As this is only used
2696 /// locally, there's no need to abstract the small size parameter.
2697 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2698 
2699 /// Recursively add the bases of Type.  Don't add Type itself.
2700 static void
2701 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2702                   const QualType &Type)
2703 {
2704   // Even though the incoming type is a base, it might not be
2705   // a class -- it could be a template parm, for instance.
2706   if (auto Rec = Type->getAs<RecordType>()) {
2707     auto Decl = Rec->getAsCXXRecordDecl();
2708 
2709     // Iterate over its bases.
2710     for (const auto &BaseSpec : Decl->bases()) {
2711       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2712         .getUnqualifiedType();
2713       if (Set.insert(Base).second)
2714         // If we've not already seen it, recurse.
2715         NoteIndirectBases(Context, Set, Base);
2716     }
2717   }
2718 }
2719 
2720 /// Performs the actual work of attaching the given base class
2721 /// specifiers to a C++ class.
2722 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2723                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2724  if (Bases.empty())
2725     return false;
2726 
2727   // Used to keep track of which base types we have already seen, so
2728   // that we can properly diagnose redundant direct base types. Note
2729   // that the key is always the unqualified canonical type of the base
2730   // class.
2731   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2732 
2733   // Used to track indirect bases so we can see if a direct base is
2734   // ambiguous.
2735   IndirectBaseSet IndirectBaseTypes;
2736 
2737   // Copy non-redundant base specifiers into permanent storage.
2738   unsigned NumGoodBases = 0;
2739   bool Invalid = false;
2740   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2741     QualType NewBaseType
2742       = Context.getCanonicalType(Bases[idx]->getType());
2743     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2744 
2745     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2746     if (KnownBase) {
2747       // C++ [class.mi]p3:
2748       //   A class shall not be specified as a direct base class of a
2749       //   derived class more than once.
2750       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2751           << KnownBase->getType() << Bases[idx]->getSourceRange();
2752 
2753       // Delete the duplicate base class specifier; we're going to
2754       // overwrite its pointer later.
2755       Context.Deallocate(Bases[idx]);
2756 
2757       Invalid = true;
2758     } else {
2759       // Okay, add this new base class.
2760       KnownBase = Bases[idx];
2761       Bases[NumGoodBases++] = Bases[idx];
2762 
2763       if (NewBaseType->isDependentType())
2764         continue;
2765       // Note this base's direct & indirect bases, if there could be ambiguity.
2766       if (Bases.size() > 1)
2767         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2768 
2769       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2770         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2771         if (Class->isInterface() &&
2772               (!RD->isInterfaceLike() ||
2773                KnownBase->getAccessSpecifier() != AS_public)) {
2774           // The Microsoft extension __interface does not permit bases that
2775           // are not themselves public interfaces.
2776           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2777               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2778               << RD->getSourceRange();
2779           Invalid = true;
2780         }
2781         if (RD->hasAttr<WeakAttr>())
2782           Class->addAttr(WeakAttr::CreateImplicit(Context));
2783       }
2784     }
2785   }
2786 
2787   // Attach the remaining base class specifiers to the derived class.
2788   Class->setBases(Bases.data(), NumGoodBases);
2789 
2790   // Check that the only base classes that are duplicate are virtual.
2791   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2792     // Check whether this direct base is inaccessible due to ambiguity.
2793     QualType BaseType = Bases[idx]->getType();
2794 
2795     // Skip all dependent types in templates being used as base specifiers.
2796     // Checks below assume that the base specifier is a CXXRecord.
2797     if (BaseType->isDependentType())
2798       continue;
2799 
2800     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2801       .getUnqualifiedType();
2802 
2803     if (IndirectBaseTypes.count(CanonicalBase)) {
2804       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2805                          /*DetectVirtual=*/true);
2806       bool found
2807         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2808       assert(found);
2809       (void)found;
2810 
2811       if (Paths.isAmbiguous(CanonicalBase))
2812         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2813             << BaseType << getAmbiguousPathsDisplayString(Paths)
2814             << Bases[idx]->getSourceRange();
2815       else
2816         assert(Bases[idx]->isVirtual());
2817     }
2818 
2819     // Delete the base class specifier, since its data has been copied
2820     // into the CXXRecordDecl.
2821     Context.Deallocate(Bases[idx]);
2822   }
2823 
2824   return Invalid;
2825 }
2826 
2827 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2828 /// class, after checking whether there are any duplicate base
2829 /// classes.
2830 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2831                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2832   if (!ClassDecl || Bases.empty())
2833     return;
2834 
2835   AdjustDeclIfTemplate(ClassDecl);
2836   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2837 }
2838 
2839 /// Determine whether the type \p Derived is a C++ class that is
2840 /// derived from the type \p Base.
2841 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2842   if (!getLangOpts().CPlusPlus)
2843     return false;
2844 
2845   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2846   if (!DerivedRD)
2847     return false;
2848 
2849   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2850   if (!BaseRD)
2851     return false;
2852 
2853   // If either the base or the derived type is invalid, don't try to
2854   // check whether one is derived from the other.
2855   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2856     return false;
2857 
2858   // FIXME: In a modules build, do we need the entire path to be visible for us
2859   // to be able to use the inheritance relationship?
2860   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2861     return false;
2862 
2863   return DerivedRD->isDerivedFrom(BaseRD);
2864 }
2865 
2866 /// Determine whether the type \p Derived is a C++ class that is
2867 /// derived from the type \p Base.
2868 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2869                          CXXBasePaths &Paths) {
2870   if (!getLangOpts().CPlusPlus)
2871     return false;
2872 
2873   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2874   if (!DerivedRD)
2875     return false;
2876 
2877   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2878   if (!BaseRD)
2879     return false;
2880 
2881   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2882     return false;
2883 
2884   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2885 }
2886 
2887 static void BuildBasePathArray(const CXXBasePath &Path,
2888                                CXXCastPath &BasePathArray) {
2889   // We first go backward and check if we have a virtual base.
2890   // FIXME: It would be better if CXXBasePath had the base specifier for
2891   // the nearest virtual base.
2892   unsigned Start = 0;
2893   for (unsigned I = Path.size(); I != 0; --I) {
2894     if (Path[I - 1].Base->isVirtual()) {
2895       Start = I - 1;
2896       break;
2897     }
2898   }
2899 
2900   // Now add all bases.
2901   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2902     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2903 }
2904 
2905 
2906 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2907                               CXXCastPath &BasePathArray) {
2908   assert(BasePathArray.empty() && "Base path array must be empty!");
2909   assert(Paths.isRecordingPaths() && "Must record paths!");
2910   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2911 }
2912 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2913 /// conversion (where Derived and Base are class types) is
2914 /// well-formed, meaning that the conversion is unambiguous (and
2915 /// that all of the base classes are accessible). Returns true
2916 /// and emits a diagnostic if the code is ill-formed, returns false
2917 /// otherwise. Loc is the location where this routine should point to
2918 /// if there is an error, and Range is the source range to highlight
2919 /// if there is an error.
2920 ///
2921 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2922 /// diagnostic for the respective type of error will be suppressed, but the
2923 /// check for ill-formed code will still be performed.
2924 bool
2925 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2926                                    unsigned InaccessibleBaseID,
2927                                    unsigned AmbiguousBaseConvID,
2928                                    SourceLocation Loc, SourceRange Range,
2929                                    DeclarationName Name,
2930                                    CXXCastPath *BasePath,
2931                                    bool IgnoreAccess) {
2932   // First, determine whether the path from Derived to Base is
2933   // ambiguous. This is slightly more expensive than checking whether
2934   // the Derived to Base conversion exists, because here we need to
2935   // explore multiple paths to determine if there is an ambiguity.
2936   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2937                      /*DetectVirtual=*/false);
2938   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2939   if (!DerivationOkay)
2940     return true;
2941 
2942   const CXXBasePath *Path = nullptr;
2943   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2944     Path = &Paths.front();
2945 
2946   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2947   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2948   // user to access such bases.
2949   if (!Path && getLangOpts().MSVCCompat) {
2950     for (const CXXBasePath &PossiblePath : Paths) {
2951       if (PossiblePath.size() == 1) {
2952         Path = &PossiblePath;
2953         if (AmbiguousBaseConvID)
2954           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2955               << Base << Derived << Range;
2956         break;
2957       }
2958     }
2959   }
2960 
2961   if (Path) {
2962     if (!IgnoreAccess) {
2963       // Check that the base class can be accessed.
2964       switch (
2965           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2966       case AR_inaccessible:
2967         return true;
2968       case AR_accessible:
2969       case AR_dependent:
2970       case AR_delayed:
2971         break;
2972       }
2973     }
2974 
2975     // Build a base path if necessary.
2976     if (BasePath)
2977       ::BuildBasePathArray(*Path, *BasePath);
2978     return false;
2979   }
2980 
2981   if (AmbiguousBaseConvID) {
2982     // We know that the derived-to-base conversion is ambiguous, and
2983     // we're going to produce a diagnostic. Perform the derived-to-base
2984     // search just one more time to compute all of the possible paths so
2985     // that we can print them out. This is more expensive than any of
2986     // the previous derived-to-base checks we've done, but at this point
2987     // performance isn't as much of an issue.
2988     Paths.clear();
2989     Paths.setRecordingPaths(true);
2990     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2991     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2992     (void)StillOkay;
2993 
2994     // Build up a textual representation of the ambiguous paths, e.g.,
2995     // D -> B -> A, that will be used to illustrate the ambiguous
2996     // conversions in the diagnostic. We only print one of the paths
2997     // to each base class subobject.
2998     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2999 
3000     Diag(Loc, AmbiguousBaseConvID)
3001     << Derived << Base << PathDisplayStr << Range << Name;
3002   }
3003   return true;
3004 }
3005 
3006 bool
3007 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3008                                    SourceLocation Loc, SourceRange Range,
3009                                    CXXCastPath *BasePath,
3010                                    bool IgnoreAccess) {
3011   return CheckDerivedToBaseConversion(
3012       Derived, Base, diag::err_upcast_to_inaccessible_base,
3013       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3014       BasePath, IgnoreAccess);
3015 }
3016 
3017 
3018 /// Builds a string representing ambiguous paths from a
3019 /// specific derived class to different subobjects of the same base
3020 /// class.
3021 ///
3022 /// This function builds a string that can be used in error messages
3023 /// to show the different paths that one can take through the
3024 /// inheritance hierarchy to go from the derived class to different
3025 /// subobjects of a base class. The result looks something like this:
3026 /// @code
3027 /// struct D -> struct B -> struct A
3028 /// struct D -> struct C -> struct A
3029 /// @endcode
3030 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3031   std::string PathDisplayStr;
3032   std::set<unsigned> DisplayedPaths;
3033   for (CXXBasePaths::paths_iterator Path = Paths.begin();
3034        Path != Paths.end(); ++Path) {
3035     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3036       // We haven't displayed a path to this particular base
3037       // class subobject yet.
3038       PathDisplayStr += "\n    ";
3039       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3040       for (CXXBasePath::const_iterator Element = Path->begin();
3041            Element != Path->end(); ++Element)
3042         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3043     }
3044   }
3045 
3046   return PathDisplayStr;
3047 }
3048 
3049 //===----------------------------------------------------------------------===//
3050 // C++ class member Handling
3051 //===----------------------------------------------------------------------===//
3052 
3053 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3054 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3055                                 SourceLocation ColonLoc,
3056                                 const ParsedAttributesView &Attrs) {
3057   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3058   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3059                                                   ASLoc, ColonLoc);
3060   CurContext->addHiddenDecl(ASDecl);
3061   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3062 }
3063 
3064 /// CheckOverrideControl - Check C++11 override control semantics.
3065 void Sema::CheckOverrideControl(NamedDecl *D) {
3066   if (D->isInvalidDecl())
3067     return;
3068 
3069   // We only care about "override" and "final" declarations.
3070   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3071     return;
3072 
3073   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3074 
3075   // We can't check dependent instance methods.
3076   if (MD && MD->isInstance() &&
3077       (MD->getParent()->hasAnyDependentBases() ||
3078        MD->getType()->isDependentType()))
3079     return;
3080 
3081   if (MD && !MD->isVirtual()) {
3082     // If we have a non-virtual method, check if if hides a virtual method.
3083     // (In that case, it's most likely the method has the wrong type.)
3084     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3085     FindHiddenVirtualMethods(MD, OverloadedMethods);
3086 
3087     if (!OverloadedMethods.empty()) {
3088       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3089         Diag(OA->getLocation(),
3090              diag::override_keyword_hides_virtual_member_function)
3091           << "override" << (OverloadedMethods.size() > 1);
3092       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3093         Diag(FA->getLocation(),
3094              diag::override_keyword_hides_virtual_member_function)
3095           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3096           << (OverloadedMethods.size() > 1);
3097       }
3098       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3099       MD->setInvalidDecl();
3100       return;
3101     }
3102     // Fall through into the general case diagnostic.
3103     // FIXME: We might want to attempt typo correction here.
3104   }
3105 
3106   if (!MD || !MD->isVirtual()) {
3107     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3108       Diag(OA->getLocation(),
3109            diag::override_keyword_only_allowed_on_virtual_member_functions)
3110         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3111       D->dropAttr<OverrideAttr>();
3112     }
3113     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3114       Diag(FA->getLocation(),
3115            diag::override_keyword_only_allowed_on_virtual_member_functions)
3116         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3117         << FixItHint::CreateRemoval(FA->getLocation());
3118       D->dropAttr<FinalAttr>();
3119     }
3120     return;
3121   }
3122 
3123   // C++11 [class.virtual]p5:
3124   //   If a function is marked with the virt-specifier override and
3125   //   does not override a member function of a base class, the program is
3126   //   ill-formed.
3127   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3128   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3129     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3130       << MD->getDeclName();
3131 }
3132 
3133 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3134   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3135     return;
3136   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3137   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3138     return;
3139 
3140   SourceLocation Loc = MD->getLocation();
3141   SourceLocation SpellingLoc = Loc;
3142   if (getSourceManager().isMacroArgExpansion(Loc))
3143     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3144   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3145   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3146       return;
3147 
3148   if (MD->size_overridden_methods() > 0) {
3149     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3150       unsigned DiagID =
3151           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3152               ? DiagInconsistent
3153               : DiagSuggest;
3154       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3155       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3156       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3157     };
3158     if (isa<CXXDestructorDecl>(MD))
3159       EmitDiag(
3160           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3161           diag::warn_suggest_destructor_marked_not_override_overriding);
3162     else
3163       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3164                diag::warn_suggest_function_marked_not_override_overriding);
3165   }
3166 }
3167 
3168 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3169 /// function overrides a virtual member function marked 'final', according to
3170 /// C++11 [class.virtual]p4.
3171 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3172                                                   const CXXMethodDecl *Old) {
3173   FinalAttr *FA = Old->getAttr<FinalAttr>();
3174   if (!FA)
3175     return false;
3176 
3177   Diag(New->getLocation(), diag::err_final_function_overridden)
3178     << New->getDeclName()
3179     << FA->isSpelledAsSealed();
3180   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3181   return true;
3182 }
3183 
3184 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3185   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3186   // FIXME: Destruction of ObjC lifetime types has side-effects.
3187   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3188     return !RD->isCompleteDefinition() ||
3189            !RD->hasTrivialDefaultConstructor() ||
3190            !RD->hasTrivialDestructor();
3191   return false;
3192 }
3193 
3194 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3195   ParsedAttributesView::const_iterator Itr =
3196       llvm::find_if(list, [](const ParsedAttr &AL) {
3197         return AL.isDeclspecPropertyAttribute();
3198       });
3199   if (Itr != list.end())
3200     return &*Itr;
3201   return nullptr;
3202 }
3203 
3204 // Check if there is a field shadowing.
3205 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3206                                       DeclarationName FieldName,
3207                                       const CXXRecordDecl *RD,
3208                                       bool DeclIsField) {
3209   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3210     return;
3211 
3212   // To record a shadowed field in a base
3213   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3214   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3215                            CXXBasePath &Path) {
3216     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3217     // Record an ambiguous path directly
3218     if (Bases.find(Base) != Bases.end())
3219       return true;
3220     for (const auto Field : Base->lookup(FieldName)) {
3221       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3222           Field->getAccess() != AS_private) {
3223         assert(Field->getAccess() != AS_none);
3224         assert(Bases.find(Base) == Bases.end());
3225         Bases[Base] = Field;
3226         return true;
3227       }
3228     }
3229     return false;
3230   };
3231 
3232   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3233                      /*DetectVirtual=*/true);
3234   if (!RD->lookupInBases(FieldShadowed, Paths))
3235     return;
3236 
3237   for (const auto &P : Paths) {
3238     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3239     auto It = Bases.find(Base);
3240     // Skip duplicated bases
3241     if (It == Bases.end())
3242       continue;
3243     auto BaseField = It->second;
3244     assert(BaseField->getAccess() != AS_private);
3245     if (AS_none !=
3246         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3247       Diag(Loc, diag::warn_shadow_field)
3248         << FieldName << RD << Base << DeclIsField;
3249       Diag(BaseField->getLocation(), diag::note_shadow_field);
3250       Bases.erase(It);
3251     }
3252   }
3253 }
3254 
3255 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3256 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3257 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3258 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3259 /// present (but parsing it has been deferred).
3260 NamedDecl *
3261 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3262                                MultiTemplateParamsArg TemplateParameterLists,
3263                                Expr *BW, const VirtSpecifiers &VS,
3264                                InClassInitStyle InitStyle) {
3265   const DeclSpec &DS = D.getDeclSpec();
3266   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3267   DeclarationName Name = NameInfo.getName();
3268   SourceLocation Loc = NameInfo.getLoc();
3269 
3270   // For anonymous bitfields, the location should point to the type.
3271   if (Loc.isInvalid())
3272     Loc = D.getBeginLoc();
3273 
3274   Expr *BitWidth = static_cast<Expr*>(BW);
3275 
3276   assert(isa<CXXRecordDecl>(CurContext));
3277   assert(!DS.isFriendSpecified());
3278 
3279   bool isFunc = D.isDeclarationOfFunction();
3280   const ParsedAttr *MSPropertyAttr =
3281       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3282 
3283   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3284     // The Microsoft extension __interface only permits public member functions
3285     // and prohibits constructors, destructors, operators, non-public member
3286     // functions, static methods and data members.
3287     unsigned InvalidDecl;
3288     bool ShowDeclName = true;
3289     if (!isFunc &&
3290         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3291       InvalidDecl = 0;
3292     else if (!isFunc)
3293       InvalidDecl = 1;
3294     else if (AS != AS_public)
3295       InvalidDecl = 2;
3296     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3297       InvalidDecl = 3;
3298     else switch (Name.getNameKind()) {
3299       case DeclarationName::CXXConstructorName:
3300         InvalidDecl = 4;
3301         ShowDeclName = false;
3302         break;
3303 
3304       case DeclarationName::CXXDestructorName:
3305         InvalidDecl = 5;
3306         ShowDeclName = false;
3307         break;
3308 
3309       case DeclarationName::CXXOperatorName:
3310       case DeclarationName::CXXConversionFunctionName:
3311         InvalidDecl = 6;
3312         break;
3313 
3314       default:
3315         InvalidDecl = 0;
3316         break;
3317     }
3318 
3319     if (InvalidDecl) {
3320       if (ShowDeclName)
3321         Diag(Loc, diag::err_invalid_member_in_interface)
3322           << (InvalidDecl-1) << Name;
3323       else
3324         Diag(Loc, diag::err_invalid_member_in_interface)
3325           << (InvalidDecl-1) << "";
3326       return nullptr;
3327     }
3328   }
3329 
3330   // C++ 9.2p6: A member shall not be declared to have automatic storage
3331   // duration (auto, register) or with the extern storage-class-specifier.
3332   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3333   // data members and cannot be applied to names declared const or static,
3334   // and cannot be applied to reference members.
3335   switch (DS.getStorageClassSpec()) {
3336   case DeclSpec::SCS_unspecified:
3337   case DeclSpec::SCS_typedef:
3338   case DeclSpec::SCS_static:
3339     break;
3340   case DeclSpec::SCS_mutable:
3341     if (isFunc) {
3342       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3343 
3344       // FIXME: It would be nicer if the keyword was ignored only for this
3345       // declarator. Otherwise we could get follow-up errors.
3346       D.getMutableDeclSpec().ClearStorageClassSpecs();
3347     }
3348     break;
3349   default:
3350     Diag(DS.getStorageClassSpecLoc(),
3351          diag::err_storageclass_invalid_for_member);
3352     D.getMutableDeclSpec().ClearStorageClassSpecs();
3353     break;
3354   }
3355 
3356   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3357                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3358                       !isFunc);
3359 
3360   if (DS.hasConstexprSpecifier() && isInstField) {
3361     SemaDiagnosticBuilder B =
3362         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3363     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3364     if (InitStyle == ICIS_NoInit) {
3365       B << 0 << 0;
3366       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3367         B << FixItHint::CreateRemoval(ConstexprLoc);
3368       else {
3369         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3370         D.getMutableDeclSpec().ClearConstexprSpec();
3371         const char *PrevSpec;
3372         unsigned DiagID;
3373         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3374             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3375         (void)Failed;
3376         assert(!Failed && "Making a constexpr member const shouldn't fail");
3377       }
3378     } else {
3379       B << 1;
3380       const char *PrevSpec;
3381       unsigned DiagID;
3382       if (D.getMutableDeclSpec().SetStorageClassSpec(
3383           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3384           Context.getPrintingPolicy())) {
3385         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3386                "This is the only DeclSpec that should fail to be applied");
3387         B << 1;
3388       } else {
3389         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3390         isInstField = false;
3391       }
3392     }
3393   }
3394 
3395   NamedDecl *Member;
3396   if (isInstField) {
3397     CXXScopeSpec &SS = D.getCXXScopeSpec();
3398 
3399     // Data members must have identifiers for names.
3400     if (!Name.isIdentifier()) {
3401       Diag(Loc, diag::err_bad_variable_name)
3402         << Name;
3403       return nullptr;
3404     }
3405 
3406     IdentifierInfo *II = Name.getAsIdentifierInfo();
3407 
3408     // Member field could not be with "template" keyword.
3409     // So TemplateParameterLists should be empty in this case.
3410     if (TemplateParameterLists.size()) {
3411       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3412       if (TemplateParams->size()) {
3413         // There is no such thing as a member field template.
3414         Diag(D.getIdentifierLoc(), diag::err_template_member)
3415             << II
3416             << SourceRange(TemplateParams->getTemplateLoc(),
3417                 TemplateParams->getRAngleLoc());
3418       } else {
3419         // There is an extraneous 'template<>' for this member.
3420         Diag(TemplateParams->getTemplateLoc(),
3421             diag::err_template_member_noparams)
3422             << II
3423             << SourceRange(TemplateParams->getTemplateLoc(),
3424                 TemplateParams->getRAngleLoc());
3425       }
3426       return nullptr;
3427     }
3428 
3429     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3430       Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3431           << II
3432           << SourceRange(D.getName().TemplateId->LAngleLoc,
3433                          D.getName().TemplateId->RAngleLoc)
3434           << D.getName().TemplateId->LAngleLoc;
3435       D.SetIdentifier(Name.getAsIdentifierInfo(), Loc);
3436     }
3437 
3438     if (SS.isSet() && !SS.isInvalid()) {
3439       // The user provided a superfluous scope specifier inside a class
3440       // definition:
3441       //
3442       // class X {
3443       //   int X::member;
3444       // };
3445       if (DeclContext *DC = computeDeclContext(SS, false))
3446         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3447                                      D.getName().getKind() ==
3448                                          UnqualifiedIdKind::IK_TemplateId);
3449       else
3450         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3451           << Name << SS.getRange();
3452 
3453       SS.clear();
3454     }
3455 
3456     if (MSPropertyAttr) {
3457       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3458                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3459       if (!Member)
3460         return nullptr;
3461       isInstField = false;
3462     } else {
3463       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3464                                 BitWidth, InitStyle, AS);
3465       if (!Member)
3466         return nullptr;
3467     }
3468 
3469     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3470   } else {
3471     Member = HandleDeclarator(S, D, TemplateParameterLists);
3472     if (!Member)
3473       return nullptr;
3474 
3475     // Non-instance-fields can't have a bitfield.
3476     if (BitWidth) {
3477       if (Member->isInvalidDecl()) {
3478         // don't emit another diagnostic.
3479       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3480         // C++ 9.6p3: A bit-field shall not be a static member.
3481         // "static member 'A' cannot be a bit-field"
3482         Diag(Loc, diag::err_static_not_bitfield)
3483           << Name << BitWidth->getSourceRange();
3484       } else if (isa<TypedefDecl>(Member)) {
3485         // "typedef member 'x' cannot be a bit-field"
3486         Diag(Loc, diag::err_typedef_not_bitfield)
3487           << Name << BitWidth->getSourceRange();
3488       } else {
3489         // A function typedef ("typedef int f(); f a;").
3490         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3491         Diag(Loc, diag::err_not_integral_type_bitfield)
3492           << Name << cast<ValueDecl>(Member)->getType()
3493           << BitWidth->getSourceRange();
3494       }
3495 
3496       BitWidth = nullptr;
3497       Member->setInvalidDecl();
3498     }
3499 
3500     NamedDecl *NonTemplateMember = Member;
3501     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3502       NonTemplateMember = FunTmpl->getTemplatedDecl();
3503     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3504       NonTemplateMember = VarTmpl->getTemplatedDecl();
3505 
3506     Member->setAccess(AS);
3507 
3508     // If we have declared a member function template or static data member
3509     // template, set the access of the templated declaration as well.
3510     if (NonTemplateMember != Member)
3511       NonTemplateMember->setAccess(AS);
3512 
3513     // C++ [temp.deduct.guide]p3:
3514     //   A deduction guide [...] for a member class template [shall be
3515     //   declared] with the same access [as the template].
3516     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3517       auto *TD = DG->getDeducedTemplate();
3518       // Access specifiers are only meaningful if both the template and the
3519       // deduction guide are from the same scope.
3520       if (AS != TD->getAccess() &&
3521           TD->getDeclContext()->getRedeclContext()->Equals(
3522               DG->getDeclContext()->getRedeclContext())) {
3523         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3524         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3525             << TD->getAccess();
3526         const AccessSpecDecl *LastAccessSpec = nullptr;
3527         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3528           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3529             LastAccessSpec = AccessSpec;
3530         }
3531         assert(LastAccessSpec && "differing access with no access specifier");
3532         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3533             << AS;
3534       }
3535     }
3536   }
3537 
3538   if (VS.isOverrideSpecified())
3539     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3540                                          AttributeCommonInfo::AS_Keyword));
3541   if (VS.isFinalSpecified())
3542     Member->addAttr(FinalAttr::Create(
3543         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3544         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3545 
3546   if (VS.getLastLocation().isValid()) {
3547     // Update the end location of a method that has a virt-specifiers.
3548     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3549       MD->setRangeEnd(VS.getLastLocation());
3550   }
3551 
3552   CheckOverrideControl(Member);
3553 
3554   assert((Name || isInstField) && "No identifier for non-field ?");
3555 
3556   if (isInstField) {
3557     FieldDecl *FD = cast<FieldDecl>(Member);
3558     FieldCollector->Add(FD);
3559 
3560     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3561       // Remember all explicit private FieldDecls that have a name, no side
3562       // effects and are not part of a dependent type declaration.
3563       if (!FD->isImplicit() && FD->getDeclName() &&
3564           FD->getAccess() == AS_private &&
3565           !FD->hasAttr<UnusedAttr>() &&
3566           !FD->getParent()->isDependentContext() &&
3567           !InitializationHasSideEffects(*FD))
3568         UnusedPrivateFields.insert(FD);
3569     }
3570   }
3571 
3572   return Member;
3573 }
3574 
3575 namespace {
3576   class UninitializedFieldVisitor
3577       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3578     Sema &S;
3579     // List of Decls to generate a warning on.  Also remove Decls that become
3580     // initialized.
3581     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3582     // List of base classes of the record.  Classes are removed after their
3583     // initializers.
3584     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3585     // Vector of decls to be removed from the Decl set prior to visiting the
3586     // nodes.  These Decls may have been initialized in the prior initializer.
3587     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3588     // If non-null, add a note to the warning pointing back to the constructor.
3589     const CXXConstructorDecl *Constructor;
3590     // Variables to hold state when processing an initializer list.  When
3591     // InitList is true, special case initialization of FieldDecls matching
3592     // InitListFieldDecl.
3593     bool InitList;
3594     FieldDecl *InitListFieldDecl;
3595     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3596 
3597   public:
3598     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3599     UninitializedFieldVisitor(Sema &S,
3600                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3601                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3602       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3603         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3604 
3605     // Returns true if the use of ME is not an uninitialized use.
3606     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3607                                          bool CheckReferenceOnly) {
3608       llvm::SmallVector<FieldDecl*, 4> Fields;
3609       bool ReferenceField = false;
3610       while (ME) {
3611         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3612         if (!FD)
3613           return false;
3614         Fields.push_back(FD);
3615         if (FD->getType()->isReferenceType())
3616           ReferenceField = true;
3617         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3618       }
3619 
3620       // Binding a reference to an uninitialized field is not an
3621       // uninitialized use.
3622       if (CheckReferenceOnly && !ReferenceField)
3623         return true;
3624 
3625       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3626       // Discard the first field since it is the field decl that is being
3627       // initialized.
3628       for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3629         UsedFieldIndex.push_back(FD->getFieldIndex());
3630 
3631       for (auto UsedIter = UsedFieldIndex.begin(),
3632                 UsedEnd = UsedFieldIndex.end(),
3633                 OrigIter = InitFieldIndex.begin(),
3634                 OrigEnd = InitFieldIndex.end();
3635            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3636         if (*UsedIter < *OrigIter)
3637           return true;
3638         if (*UsedIter > *OrigIter)
3639           break;
3640       }
3641 
3642       return false;
3643     }
3644 
3645     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3646                           bool AddressOf) {
3647       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3648         return;
3649 
3650       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3651       // or union.
3652       MemberExpr *FieldME = ME;
3653 
3654       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3655 
3656       Expr *Base = ME;
3657       while (MemberExpr *SubME =
3658                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3659 
3660         if (isa<VarDecl>(SubME->getMemberDecl()))
3661           return;
3662 
3663         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3664           if (!FD->isAnonymousStructOrUnion())
3665             FieldME = SubME;
3666 
3667         if (!FieldME->getType().isPODType(S.Context))
3668           AllPODFields = false;
3669 
3670         Base = SubME->getBase();
3671       }
3672 
3673       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3674         Visit(Base);
3675         return;
3676       }
3677 
3678       if (AddressOf && AllPODFields)
3679         return;
3680 
3681       ValueDecl* FoundVD = FieldME->getMemberDecl();
3682 
3683       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3684         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3685           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3686         }
3687 
3688         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3689           QualType T = BaseCast->getType();
3690           if (T->isPointerType() &&
3691               BaseClasses.count(T->getPointeeType())) {
3692             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3693                 << T->getPointeeType() << FoundVD;
3694           }
3695         }
3696       }
3697 
3698       if (!Decls.count(FoundVD))
3699         return;
3700 
3701       const bool IsReference = FoundVD->getType()->isReferenceType();
3702 
3703       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3704         // Special checking for initializer lists.
3705         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3706           return;
3707         }
3708       } else {
3709         // Prevent double warnings on use of unbounded references.
3710         if (CheckReferenceOnly && !IsReference)
3711           return;
3712       }
3713 
3714       unsigned diag = IsReference
3715           ? diag::warn_reference_field_is_uninit
3716           : diag::warn_field_is_uninit;
3717       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3718       if (Constructor)
3719         S.Diag(Constructor->getLocation(),
3720                diag::note_uninit_in_this_constructor)
3721           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3722 
3723     }
3724 
3725     void HandleValue(Expr *E, bool AddressOf) {
3726       E = E->IgnoreParens();
3727 
3728       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3729         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3730                          AddressOf /*AddressOf*/);
3731         return;
3732       }
3733 
3734       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3735         Visit(CO->getCond());
3736         HandleValue(CO->getTrueExpr(), AddressOf);
3737         HandleValue(CO->getFalseExpr(), AddressOf);
3738         return;
3739       }
3740 
3741       if (BinaryConditionalOperator *BCO =
3742               dyn_cast<BinaryConditionalOperator>(E)) {
3743         Visit(BCO->getCond());
3744         HandleValue(BCO->getFalseExpr(), AddressOf);
3745         return;
3746       }
3747 
3748       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3749         HandleValue(OVE->getSourceExpr(), AddressOf);
3750         return;
3751       }
3752 
3753       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3754         switch (BO->getOpcode()) {
3755         default:
3756           break;
3757         case(BO_PtrMemD):
3758         case(BO_PtrMemI):
3759           HandleValue(BO->getLHS(), AddressOf);
3760           Visit(BO->getRHS());
3761           return;
3762         case(BO_Comma):
3763           Visit(BO->getLHS());
3764           HandleValue(BO->getRHS(), AddressOf);
3765           return;
3766         }
3767       }
3768 
3769       Visit(E);
3770     }
3771 
3772     void CheckInitListExpr(InitListExpr *ILE) {
3773       InitFieldIndex.push_back(0);
3774       for (auto Child : ILE->children()) {
3775         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3776           CheckInitListExpr(SubList);
3777         } else {
3778           Visit(Child);
3779         }
3780         ++InitFieldIndex.back();
3781       }
3782       InitFieldIndex.pop_back();
3783     }
3784 
3785     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3786                           FieldDecl *Field, const Type *BaseClass) {
3787       // Remove Decls that may have been initialized in the previous
3788       // initializer.
3789       for (ValueDecl* VD : DeclsToRemove)
3790         Decls.erase(VD);
3791       DeclsToRemove.clear();
3792 
3793       Constructor = FieldConstructor;
3794       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3795 
3796       if (ILE && Field) {
3797         InitList = true;
3798         InitListFieldDecl = Field;
3799         InitFieldIndex.clear();
3800         CheckInitListExpr(ILE);
3801       } else {
3802         InitList = false;
3803         Visit(E);
3804       }
3805 
3806       if (Field)
3807         Decls.erase(Field);
3808       if (BaseClass)
3809         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3810     }
3811 
3812     void VisitMemberExpr(MemberExpr *ME) {
3813       // All uses of unbounded reference fields will warn.
3814       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3815     }
3816 
3817     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3818       if (E->getCastKind() == CK_LValueToRValue) {
3819         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3820         return;
3821       }
3822 
3823       Inherited::VisitImplicitCastExpr(E);
3824     }
3825 
3826     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3827       if (E->getConstructor()->isCopyConstructor()) {
3828         Expr *ArgExpr = E->getArg(0);
3829         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3830           if (ILE->getNumInits() == 1)
3831             ArgExpr = ILE->getInit(0);
3832         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3833           if (ICE->getCastKind() == CK_NoOp)
3834             ArgExpr = ICE->getSubExpr();
3835         HandleValue(ArgExpr, false /*AddressOf*/);
3836         return;
3837       }
3838       Inherited::VisitCXXConstructExpr(E);
3839     }
3840 
3841     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3842       Expr *Callee = E->getCallee();
3843       if (isa<MemberExpr>(Callee)) {
3844         HandleValue(Callee, false /*AddressOf*/);
3845         for (auto Arg : E->arguments())
3846           Visit(Arg);
3847         return;
3848       }
3849 
3850       Inherited::VisitCXXMemberCallExpr(E);
3851     }
3852 
3853     void VisitCallExpr(CallExpr *E) {
3854       // Treat std::move as a use.
3855       if (E->isCallToStdMove()) {
3856         HandleValue(E->getArg(0), /*AddressOf=*/false);
3857         return;
3858       }
3859 
3860       Inherited::VisitCallExpr(E);
3861     }
3862 
3863     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3864       Expr *Callee = E->getCallee();
3865 
3866       if (isa<UnresolvedLookupExpr>(Callee))
3867         return Inherited::VisitCXXOperatorCallExpr(E);
3868 
3869       Visit(Callee);
3870       for (auto Arg : E->arguments())
3871         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3872     }
3873 
3874     void VisitBinaryOperator(BinaryOperator *E) {
3875       // If a field assignment is detected, remove the field from the
3876       // uninitiailized field set.
3877       if (E->getOpcode() == BO_Assign)
3878         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3879           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3880             if (!FD->getType()->isReferenceType())
3881               DeclsToRemove.push_back(FD);
3882 
3883       if (E->isCompoundAssignmentOp()) {
3884         HandleValue(E->getLHS(), false /*AddressOf*/);
3885         Visit(E->getRHS());
3886         return;
3887       }
3888 
3889       Inherited::VisitBinaryOperator(E);
3890     }
3891 
3892     void VisitUnaryOperator(UnaryOperator *E) {
3893       if (E->isIncrementDecrementOp()) {
3894         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3895         return;
3896       }
3897       if (E->getOpcode() == UO_AddrOf) {
3898         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3899           HandleValue(ME->getBase(), true /*AddressOf*/);
3900           return;
3901         }
3902       }
3903 
3904       Inherited::VisitUnaryOperator(E);
3905     }
3906   };
3907 
3908   // Diagnose value-uses of fields to initialize themselves, e.g.
3909   //   foo(foo)
3910   // where foo is not also a parameter to the constructor.
3911   // Also diagnose across field uninitialized use such as
3912   //   x(y), y(x)
3913   // TODO: implement -Wuninitialized and fold this into that framework.
3914   static void DiagnoseUninitializedFields(
3915       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3916 
3917     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3918                                            Constructor->getLocation())) {
3919       return;
3920     }
3921 
3922     if (Constructor->isInvalidDecl())
3923       return;
3924 
3925     const CXXRecordDecl *RD = Constructor->getParent();
3926 
3927     if (RD->isDependentContext())
3928       return;
3929 
3930     // Holds fields that are uninitialized.
3931     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3932 
3933     // At the beginning, all fields are uninitialized.
3934     for (auto *I : RD->decls()) {
3935       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3936         UninitializedFields.insert(FD);
3937       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3938         UninitializedFields.insert(IFD->getAnonField());
3939       }
3940     }
3941 
3942     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3943     for (auto I : RD->bases())
3944       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3945 
3946     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3947       return;
3948 
3949     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3950                                                    UninitializedFields,
3951                                                    UninitializedBaseClasses);
3952 
3953     for (const auto *FieldInit : Constructor->inits()) {
3954       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3955         break;
3956 
3957       Expr *InitExpr = FieldInit->getInit();
3958       if (!InitExpr)
3959         continue;
3960 
3961       if (CXXDefaultInitExpr *Default =
3962               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3963         InitExpr = Default->getExpr();
3964         if (!InitExpr)
3965           continue;
3966         // In class initializers will point to the constructor.
3967         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3968                                               FieldInit->getAnyMember(),
3969                                               FieldInit->getBaseClass());
3970       } else {
3971         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3972                                               FieldInit->getAnyMember(),
3973                                               FieldInit->getBaseClass());
3974       }
3975     }
3976   }
3977 } // namespace
3978 
3979 /// Enter a new C++ default initializer scope. After calling this, the
3980 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3981 /// parsing or instantiating the initializer failed.
3982 void Sema::ActOnStartCXXInClassMemberInitializer() {
3983   // Create a synthetic function scope to represent the call to the constructor
3984   // that notionally surrounds a use of this initializer.
3985   PushFunctionScope();
3986 }
3987 
3988 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3989   if (!D.isFunctionDeclarator())
3990     return;
3991   auto &FTI = D.getFunctionTypeInfo();
3992   if (!FTI.Params)
3993     return;
3994   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3995                                                           FTI.NumParams)) {
3996     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3997     if (ParamDecl->getDeclName())
3998       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3999   }
4000 }
4001 
4002 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4003   return ActOnRequiresClause(ConstraintExpr);
4004 }
4005 
4006 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4007   if (ConstraintExpr.isInvalid())
4008     return ExprError();
4009 
4010   ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4011   if (ConstraintExpr.isInvalid())
4012     return ExprError();
4013 
4014   if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4015                                       UPPC_RequiresClause))
4016     return ExprError();
4017 
4018   return ConstraintExpr;
4019 }
4020 
4021 /// This is invoked after parsing an in-class initializer for a
4022 /// non-static C++ class member, and after instantiating an in-class initializer
4023 /// in a class template. Such actions are deferred until the class is complete.
4024 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4025                                                   SourceLocation InitLoc,
4026                                                   Expr *InitExpr) {
4027   // Pop the notional constructor scope we created earlier.
4028   PopFunctionScopeInfo(nullptr, D);
4029 
4030   FieldDecl *FD = dyn_cast<FieldDecl>(D);
4031   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4032          "must set init style when field is created");
4033 
4034   if (!InitExpr) {
4035     D->setInvalidDecl();
4036     if (FD)
4037       FD->removeInClassInitializer();
4038     return;
4039   }
4040 
4041   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4042     FD->setInvalidDecl();
4043     FD->removeInClassInitializer();
4044     return;
4045   }
4046 
4047   ExprResult Init = InitExpr;
4048   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
4049     InitializedEntity Entity =
4050         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4051     InitializationKind Kind =
4052         FD->getInClassInitStyle() == ICIS_ListInit
4053             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4054                                                    InitExpr->getBeginLoc(),
4055                                                    InitExpr->getEndLoc())
4056             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4057     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4058     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4059     if (Init.isInvalid()) {
4060       FD->setInvalidDecl();
4061       return;
4062     }
4063   }
4064 
4065   // C++11 [class.base.init]p7:
4066   //   The initialization of each base and member constitutes a
4067   //   full-expression.
4068   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4069   if (Init.isInvalid()) {
4070     FD->setInvalidDecl();
4071     return;
4072   }
4073 
4074   InitExpr = Init.get();
4075 
4076   FD->setInClassInitializer(InitExpr);
4077 }
4078 
4079 /// Find the direct and/or virtual base specifiers that
4080 /// correspond to the given base type, for use in base initialization
4081 /// within a constructor.
4082 static bool FindBaseInitializer(Sema &SemaRef,
4083                                 CXXRecordDecl *ClassDecl,
4084                                 QualType BaseType,
4085                                 const CXXBaseSpecifier *&DirectBaseSpec,
4086                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4087   // First, check for a direct base class.
4088   DirectBaseSpec = nullptr;
4089   for (const auto &Base : ClassDecl->bases()) {
4090     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4091       // We found a direct base of this type. That's what we're
4092       // initializing.
4093       DirectBaseSpec = &Base;
4094       break;
4095     }
4096   }
4097 
4098   // Check for a virtual base class.
4099   // FIXME: We might be able to short-circuit this if we know in advance that
4100   // there are no virtual bases.
4101   VirtualBaseSpec = nullptr;
4102   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4103     // We haven't found a base yet; search the class hierarchy for a
4104     // virtual base class.
4105     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4106                        /*DetectVirtual=*/false);
4107     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4108                               SemaRef.Context.getTypeDeclType(ClassDecl),
4109                               BaseType, Paths)) {
4110       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4111            Path != Paths.end(); ++Path) {
4112         if (Path->back().Base->isVirtual()) {
4113           VirtualBaseSpec = Path->back().Base;
4114           break;
4115         }
4116       }
4117     }
4118   }
4119 
4120   return DirectBaseSpec || VirtualBaseSpec;
4121 }
4122 
4123 /// Handle a C++ member initializer using braced-init-list syntax.
4124 MemInitResult
4125 Sema::ActOnMemInitializer(Decl *ConstructorD,
4126                           Scope *S,
4127                           CXXScopeSpec &SS,
4128                           IdentifierInfo *MemberOrBase,
4129                           ParsedType TemplateTypeTy,
4130                           const DeclSpec &DS,
4131                           SourceLocation IdLoc,
4132                           Expr *InitList,
4133                           SourceLocation EllipsisLoc) {
4134   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4135                              DS, IdLoc, InitList,
4136                              EllipsisLoc);
4137 }
4138 
4139 /// Handle a C++ member initializer using parentheses syntax.
4140 MemInitResult
4141 Sema::ActOnMemInitializer(Decl *ConstructorD,
4142                           Scope *S,
4143                           CXXScopeSpec &SS,
4144                           IdentifierInfo *MemberOrBase,
4145                           ParsedType TemplateTypeTy,
4146                           const DeclSpec &DS,
4147                           SourceLocation IdLoc,
4148                           SourceLocation LParenLoc,
4149                           ArrayRef<Expr *> Args,
4150                           SourceLocation RParenLoc,
4151                           SourceLocation EllipsisLoc) {
4152   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4153   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4154                              DS, IdLoc, List, EllipsisLoc);
4155 }
4156 
4157 namespace {
4158 
4159 // Callback to only accept typo corrections that can be a valid C++ member
4160 // initializer: either a non-static field member or a base class.
4161 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4162 public:
4163   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4164       : ClassDecl(ClassDecl) {}
4165 
4166   bool ValidateCandidate(const TypoCorrection &candidate) override {
4167     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4168       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4169         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4170       return isa<TypeDecl>(ND);
4171     }
4172     return false;
4173   }
4174 
4175   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4176     return std::make_unique<MemInitializerValidatorCCC>(*this);
4177   }
4178 
4179 private:
4180   CXXRecordDecl *ClassDecl;
4181 };
4182 
4183 }
4184 
4185 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4186                                              CXXScopeSpec &SS,
4187                                              ParsedType TemplateTypeTy,
4188                                              IdentifierInfo *MemberOrBase) {
4189   if (SS.getScopeRep() || TemplateTypeTy)
4190     return nullptr;
4191   for (auto *D : ClassDecl->lookup(MemberOrBase))
4192     if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4193       return cast<ValueDecl>(D);
4194   return nullptr;
4195 }
4196 
4197 /// Handle a C++ member initializer.
4198 MemInitResult
4199 Sema::BuildMemInitializer(Decl *ConstructorD,
4200                           Scope *S,
4201                           CXXScopeSpec &SS,
4202                           IdentifierInfo *MemberOrBase,
4203                           ParsedType TemplateTypeTy,
4204                           const DeclSpec &DS,
4205                           SourceLocation IdLoc,
4206                           Expr *Init,
4207                           SourceLocation EllipsisLoc) {
4208   ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4209                                              /*RecoverUncorrectedTypos=*/true);
4210   if (!Res.isUsable())
4211     return true;
4212   Init = Res.get();
4213 
4214   if (!ConstructorD)
4215     return true;
4216 
4217   AdjustDeclIfTemplate(ConstructorD);
4218 
4219   CXXConstructorDecl *Constructor
4220     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4221   if (!Constructor) {
4222     // The user wrote a constructor initializer on a function that is
4223     // not a C++ constructor. Ignore the error for now, because we may
4224     // have more member initializers coming; we'll diagnose it just
4225     // once in ActOnMemInitializers.
4226     return true;
4227   }
4228 
4229   CXXRecordDecl *ClassDecl = Constructor->getParent();
4230 
4231   // C++ [class.base.init]p2:
4232   //   Names in a mem-initializer-id are looked up in the scope of the
4233   //   constructor's class and, if not found in that scope, are looked
4234   //   up in the scope containing the constructor's definition.
4235   //   [Note: if the constructor's class contains a member with the
4236   //   same name as a direct or virtual base class of the class, a
4237   //   mem-initializer-id naming the member or base class and composed
4238   //   of a single identifier refers to the class member. A
4239   //   mem-initializer-id for the hidden base class may be specified
4240   //   using a qualified name. ]
4241 
4242   // Look for a member, first.
4243   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4244           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4245     if (EllipsisLoc.isValid())
4246       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4247           << MemberOrBase
4248           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4249 
4250     return BuildMemberInitializer(Member, Init, IdLoc);
4251   }
4252   // It didn't name a member, so see if it names a class.
4253   QualType BaseType;
4254   TypeSourceInfo *TInfo = nullptr;
4255 
4256   if (TemplateTypeTy) {
4257     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4258     if (BaseType.isNull())
4259       return true;
4260   } else if (DS.getTypeSpecType() == TST_decltype) {
4261     BaseType = BuildDecltypeType(DS.getRepAsExpr());
4262   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4263     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4264     return true;
4265   } else {
4266     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4267     LookupParsedName(R, S, &SS);
4268 
4269     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4270     if (!TyD) {
4271       if (R.isAmbiguous()) return true;
4272 
4273       // We don't want access-control diagnostics here.
4274       R.suppressDiagnostics();
4275 
4276       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4277         bool NotUnknownSpecialization = false;
4278         DeclContext *DC = computeDeclContext(SS, false);
4279         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4280           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4281 
4282         if (!NotUnknownSpecialization) {
4283           // When the scope specifier can refer to a member of an unknown
4284           // specialization, we take it as a type name.
4285           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4286                                        SS.getWithLocInContext(Context),
4287                                        *MemberOrBase, IdLoc);
4288           if (BaseType.isNull())
4289             return true;
4290 
4291           TInfo = Context.CreateTypeSourceInfo(BaseType);
4292           DependentNameTypeLoc TL =
4293               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4294           if (!TL.isNull()) {
4295             TL.setNameLoc(IdLoc);
4296             TL.setElaboratedKeywordLoc(SourceLocation());
4297             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4298           }
4299 
4300           R.clear();
4301           R.setLookupName(MemberOrBase);
4302         }
4303       }
4304 
4305       // If no results were found, try to correct typos.
4306       TypoCorrection Corr;
4307       MemInitializerValidatorCCC CCC(ClassDecl);
4308       if (R.empty() && BaseType.isNull() &&
4309           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4310                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4311         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4312           // We have found a non-static data member with a similar
4313           // name to what was typed; complain and initialize that
4314           // member.
4315           diagnoseTypo(Corr,
4316                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4317                          << MemberOrBase << true);
4318           return BuildMemberInitializer(Member, Init, IdLoc);
4319         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4320           const CXXBaseSpecifier *DirectBaseSpec;
4321           const CXXBaseSpecifier *VirtualBaseSpec;
4322           if (FindBaseInitializer(*this, ClassDecl,
4323                                   Context.getTypeDeclType(Type),
4324                                   DirectBaseSpec, VirtualBaseSpec)) {
4325             // We have found a direct or virtual base class with a
4326             // similar name to what was typed; complain and initialize
4327             // that base class.
4328             diagnoseTypo(Corr,
4329                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4330                            << MemberOrBase << false,
4331                          PDiag() /*Suppress note, we provide our own.*/);
4332 
4333             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4334                                                               : VirtualBaseSpec;
4335             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4336                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4337 
4338             TyD = Type;
4339           }
4340         }
4341       }
4342 
4343       if (!TyD && BaseType.isNull()) {
4344         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4345           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4346         return true;
4347       }
4348     }
4349 
4350     if (BaseType.isNull()) {
4351       BaseType = Context.getTypeDeclType(TyD);
4352       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4353       if (SS.isSet()) {
4354         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4355                                              BaseType);
4356         TInfo = Context.CreateTypeSourceInfo(BaseType);
4357         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4358         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4359         TL.setElaboratedKeywordLoc(SourceLocation());
4360         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4361       }
4362     }
4363   }
4364 
4365   if (!TInfo)
4366     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4367 
4368   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4369 }
4370 
4371 MemInitResult
4372 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4373                              SourceLocation IdLoc) {
4374   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4375   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4376   assert((DirectMember || IndirectMember) &&
4377          "Member must be a FieldDecl or IndirectFieldDecl");
4378 
4379   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4380     return true;
4381 
4382   if (Member->isInvalidDecl())
4383     return true;
4384 
4385   MultiExprArg Args;
4386   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4387     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4388   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4389     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4390   } else {
4391     // Template instantiation doesn't reconstruct ParenListExprs for us.
4392     Args = Init;
4393   }
4394 
4395   SourceRange InitRange = Init->getSourceRange();
4396 
4397   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4398     // Can't check initialization for a member of dependent type or when
4399     // any of the arguments are type-dependent expressions.
4400     DiscardCleanupsInEvaluationContext();
4401   } else {
4402     bool InitList = false;
4403     if (isa<InitListExpr>(Init)) {
4404       InitList = true;
4405       Args = Init;
4406     }
4407 
4408     // Initialize the member.
4409     InitializedEntity MemberEntity =
4410       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4411                    : InitializedEntity::InitializeMember(IndirectMember,
4412                                                          nullptr);
4413     InitializationKind Kind =
4414         InitList ? InitializationKind::CreateDirectList(
4415                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4416                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4417                                                     InitRange.getEnd());
4418 
4419     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4420     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4421                                             nullptr);
4422     if (!MemberInit.isInvalid()) {
4423       // C++11 [class.base.init]p7:
4424       //   The initialization of each base and member constitutes a
4425       //   full-expression.
4426       MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4427                                        /*DiscardedValue*/ false);
4428     }
4429 
4430     if (MemberInit.isInvalid()) {
4431       // Args were sensible expressions but we couldn't initialize the member
4432       // from them. Preserve them in a RecoveryExpr instead.
4433       Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4434                                 Member->getType())
4435                  .get();
4436       if (!Init)
4437         return true;
4438     } else {
4439       Init = MemberInit.get();
4440     }
4441   }
4442 
4443   if (DirectMember) {
4444     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4445                                             InitRange.getBegin(), Init,
4446                                             InitRange.getEnd());
4447   } else {
4448     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4449                                             InitRange.getBegin(), Init,
4450                                             InitRange.getEnd());
4451   }
4452 }
4453 
4454 MemInitResult
4455 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4456                                  CXXRecordDecl *ClassDecl) {
4457   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4458   if (!LangOpts.CPlusPlus11)
4459     return Diag(NameLoc, diag::err_delegating_ctor)
4460       << TInfo->getTypeLoc().getLocalSourceRange();
4461   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4462 
4463   bool InitList = true;
4464   MultiExprArg Args = Init;
4465   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4466     InitList = false;
4467     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4468   }
4469 
4470   SourceRange InitRange = Init->getSourceRange();
4471   // Initialize the object.
4472   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4473                                      QualType(ClassDecl->getTypeForDecl(), 0));
4474   InitializationKind Kind =
4475       InitList ? InitializationKind::CreateDirectList(
4476                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4477                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4478                                                   InitRange.getEnd());
4479   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4480   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4481                                               Args, nullptr);
4482   if (!DelegationInit.isInvalid()) {
4483     assert((DelegationInit.get()->containsErrors() ||
4484             cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4485            "Delegating constructor with no target?");
4486 
4487     // C++11 [class.base.init]p7:
4488     //   The initialization of each base and member constitutes a
4489     //   full-expression.
4490     DelegationInit = ActOnFinishFullExpr(
4491         DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4492   }
4493 
4494   if (DelegationInit.isInvalid()) {
4495     DelegationInit =
4496         CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4497                            QualType(ClassDecl->getTypeForDecl(), 0));
4498     if (DelegationInit.isInvalid())
4499       return true;
4500   } else {
4501     // If we are in a dependent context, template instantiation will
4502     // perform this type-checking again. Just save the arguments that we
4503     // received in a ParenListExpr.
4504     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4505     // of the information that we have about the base
4506     // initializer. However, deconstructing the ASTs is a dicey process,
4507     // and this approach is far more likely to get the corner cases right.
4508     if (CurContext->isDependentContext())
4509       DelegationInit = Init;
4510   }
4511 
4512   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4513                                           DelegationInit.getAs<Expr>(),
4514                                           InitRange.getEnd());
4515 }
4516 
4517 MemInitResult
4518 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4519                            Expr *Init, CXXRecordDecl *ClassDecl,
4520                            SourceLocation EllipsisLoc) {
4521   SourceLocation BaseLoc
4522     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4523 
4524   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4525     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4526              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4527 
4528   // C++ [class.base.init]p2:
4529   //   [...] Unless the mem-initializer-id names a nonstatic data
4530   //   member of the constructor's class or a direct or virtual base
4531   //   of that class, the mem-initializer is ill-formed. A
4532   //   mem-initializer-list can initialize a base class using any
4533   //   name that denotes that base class type.
4534 
4535   // We can store the initializers in "as-written" form and delay analysis until
4536   // instantiation if the constructor is dependent. But not for dependent
4537   // (broken) code in a non-template! SetCtorInitializers does not expect this.
4538   bool Dependent = CurContext->isDependentContext() &&
4539                    (BaseType->isDependentType() || Init->isTypeDependent());
4540 
4541   SourceRange InitRange = Init->getSourceRange();
4542   if (EllipsisLoc.isValid()) {
4543     // This is a pack expansion.
4544     if (!BaseType->containsUnexpandedParameterPack())  {
4545       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4546         << SourceRange(BaseLoc, InitRange.getEnd());
4547 
4548       EllipsisLoc = SourceLocation();
4549     }
4550   } else {
4551     // Check for any unexpanded parameter packs.
4552     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4553       return true;
4554 
4555     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4556       return true;
4557   }
4558 
4559   // Check for direct and virtual base classes.
4560   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4561   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4562   if (!Dependent) {
4563     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4564                                        BaseType))
4565       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4566 
4567     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4568                         VirtualBaseSpec);
4569 
4570     // C++ [base.class.init]p2:
4571     // Unless the mem-initializer-id names a nonstatic data member of the
4572     // constructor's class or a direct or virtual base of that class, the
4573     // mem-initializer is ill-formed.
4574     if (!DirectBaseSpec && !VirtualBaseSpec) {
4575       // If the class has any dependent bases, then it's possible that
4576       // one of those types will resolve to the same type as
4577       // BaseType. Therefore, just treat this as a dependent base
4578       // class initialization.  FIXME: Should we try to check the
4579       // initialization anyway? It seems odd.
4580       if (ClassDecl->hasAnyDependentBases())
4581         Dependent = true;
4582       else
4583         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4584           << BaseType << Context.getTypeDeclType(ClassDecl)
4585           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4586     }
4587   }
4588 
4589   if (Dependent) {
4590     DiscardCleanupsInEvaluationContext();
4591 
4592     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4593                                             /*IsVirtual=*/false,
4594                                             InitRange.getBegin(), Init,
4595                                             InitRange.getEnd(), EllipsisLoc);
4596   }
4597 
4598   // C++ [base.class.init]p2:
4599   //   If a mem-initializer-id is ambiguous because it designates both
4600   //   a direct non-virtual base class and an inherited virtual base
4601   //   class, the mem-initializer is ill-formed.
4602   if (DirectBaseSpec && VirtualBaseSpec)
4603     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4604       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4605 
4606   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4607   if (!BaseSpec)
4608     BaseSpec = VirtualBaseSpec;
4609 
4610   // Initialize the base.
4611   bool InitList = true;
4612   MultiExprArg Args = Init;
4613   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4614     InitList = false;
4615     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4616   }
4617 
4618   InitializedEntity BaseEntity =
4619     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4620   InitializationKind Kind =
4621       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4622                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4623                                                   InitRange.getEnd());
4624   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4625   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4626   if (!BaseInit.isInvalid()) {
4627     // C++11 [class.base.init]p7:
4628     //   The initialization of each base and member constitutes a
4629     //   full-expression.
4630     BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4631                                    /*DiscardedValue*/ false);
4632   }
4633 
4634   if (BaseInit.isInvalid()) {
4635     BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4636                                   Args, BaseType);
4637     if (BaseInit.isInvalid())
4638       return true;
4639   } else {
4640     // If we are in a dependent context, template instantiation will
4641     // perform this type-checking again. Just save the arguments that we
4642     // received in a ParenListExpr.
4643     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4644     // of the information that we have about the base
4645     // initializer. However, deconstructing the ASTs is a dicey process,
4646     // and this approach is far more likely to get the corner cases right.
4647     if (CurContext->isDependentContext())
4648       BaseInit = Init;
4649   }
4650 
4651   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4652                                           BaseSpec->isVirtual(),
4653                                           InitRange.getBegin(),
4654                                           BaseInit.getAs<Expr>(),
4655                                           InitRange.getEnd(), EllipsisLoc);
4656 }
4657 
4658 // Create a static_cast\<T&&>(expr).
4659 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4660   if (T.isNull()) T = E->getType();
4661   QualType TargetType = SemaRef.BuildReferenceType(
4662       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4663   SourceLocation ExprLoc = E->getBeginLoc();
4664   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4665       TargetType, ExprLoc);
4666 
4667   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4668                                    SourceRange(ExprLoc, ExprLoc),
4669                                    E->getSourceRange()).get();
4670 }
4671 
4672 /// ImplicitInitializerKind - How an implicit base or member initializer should
4673 /// initialize its base or member.
4674 enum ImplicitInitializerKind {
4675   IIK_Default,
4676   IIK_Copy,
4677   IIK_Move,
4678   IIK_Inherit
4679 };
4680 
4681 static bool
4682 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4683                              ImplicitInitializerKind ImplicitInitKind,
4684                              CXXBaseSpecifier *BaseSpec,
4685                              bool IsInheritedVirtualBase,
4686                              CXXCtorInitializer *&CXXBaseInit) {
4687   InitializedEntity InitEntity
4688     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4689                                         IsInheritedVirtualBase);
4690 
4691   ExprResult BaseInit;
4692 
4693   switch (ImplicitInitKind) {
4694   case IIK_Inherit:
4695   case IIK_Default: {
4696     InitializationKind InitKind
4697       = InitializationKind::CreateDefault(Constructor->getLocation());
4698     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4699     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4700     break;
4701   }
4702 
4703   case IIK_Move:
4704   case IIK_Copy: {
4705     bool Moving = ImplicitInitKind == IIK_Move;
4706     ParmVarDecl *Param = Constructor->getParamDecl(0);
4707     QualType ParamType = Param->getType().getNonReferenceType();
4708 
4709     Expr *CopyCtorArg =
4710       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4711                           SourceLocation(), Param, false,
4712                           Constructor->getLocation(), ParamType,
4713                           VK_LValue, nullptr);
4714 
4715     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4716 
4717     // Cast to the base class to avoid ambiguities.
4718     QualType ArgTy =
4719       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4720                                        ParamType.getQualifiers());
4721 
4722     if (Moving) {
4723       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4724     }
4725 
4726     CXXCastPath BasePath;
4727     BasePath.push_back(BaseSpec);
4728     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4729                                             CK_UncheckedDerivedToBase,
4730                                             Moving ? VK_XValue : VK_LValue,
4731                                             &BasePath).get();
4732 
4733     InitializationKind InitKind
4734       = InitializationKind::CreateDirect(Constructor->getLocation(),
4735                                          SourceLocation(), SourceLocation());
4736     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4737     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4738     break;
4739   }
4740   }
4741 
4742   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4743   if (BaseInit.isInvalid())
4744     return true;
4745 
4746   CXXBaseInit =
4747     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4748                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4749                                                         SourceLocation()),
4750                                              BaseSpec->isVirtual(),
4751                                              SourceLocation(),
4752                                              BaseInit.getAs<Expr>(),
4753                                              SourceLocation(),
4754                                              SourceLocation());
4755 
4756   return false;
4757 }
4758 
4759 static bool RefersToRValueRef(Expr *MemRef) {
4760   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4761   return Referenced->getType()->isRValueReferenceType();
4762 }
4763 
4764 static bool
4765 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4766                                ImplicitInitializerKind ImplicitInitKind,
4767                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4768                                CXXCtorInitializer *&CXXMemberInit) {
4769   if (Field->isInvalidDecl())
4770     return true;
4771 
4772   SourceLocation Loc = Constructor->getLocation();
4773 
4774   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4775     bool Moving = ImplicitInitKind == IIK_Move;
4776     ParmVarDecl *Param = Constructor->getParamDecl(0);
4777     QualType ParamType = Param->getType().getNonReferenceType();
4778 
4779     // Suppress copying zero-width bitfields.
4780     if (Field->isZeroLengthBitField(SemaRef.Context))
4781       return false;
4782 
4783     Expr *MemberExprBase =
4784       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4785                           SourceLocation(), Param, false,
4786                           Loc, ParamType, VK_LValue, nullptr);
4787 
4788     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4789 
4790     if (Moving) {
4791       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4792     }
4793 
4794     // Build a reference to this field within the parameter.
4795     CXXScopeSpec SS;
4796     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4797                               Sema::LookupMemberName);
4798     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4799                                   : cast<ValueDecl>(Field), AS_public);
4800     MemberLookup.resolveKind();
4801     ExprResult CtorArg
4802       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4803                                          ParamType, Loc,
4804                                          /*IsArrow=*/false,
4805                                          SS,
4806                                          /*TemplateKWLoc=*/SourceLocation(),
4807                                          /*FirstQualifierInScope=*/nullptr,
4808                                          MemberLookup,
4809                                          /*TemplateArgs=*/nullptr,
4810                                          /*S*/nullptr);
4811     if (CtorArg.isInvalid())
4812       return true;
4813 
4814     // C++11 [class.copy]p15:
4815     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4816     //     with static_cast<T&&>(x.m);
4817     if (RefersToRValueRef(CtorArg.get())) {
4818       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4819     }
4820 
4821     InitializedEntity Entity =
4822         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4823                                                        /*Implicit*/ true)
4824                  : InitializedEntity::InitializeMember(Field, nullptr,
4825                                                        /*Implicit*/ true);
4826 
4827     // Direct-initialize to use the copy constructor.
4828     InitializationKind InitKind =
4829       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4830 
4831     Expr *CtorArgE = CtorArg.getAs<Expr>();
4832     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4833     ExprResult MemberInit =
4834         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4835     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4836     if (MemberInit.isInvalid())
4837       return true;
4838 
4839     if (Indirect)
4840       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4841           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4842     else
4843       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4844           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4845     return false;
4846   }
4847 
4848   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4849          "Unhandled implicit init kind!");
4850 
4851   QualType FieldBaseElementType =
4852     SemaRef.Context.getBaseElementType(Field->getType());
4853 
4854   if (FieldBaseElementType->isRecordType()) {
4855     InitializedEntity InitEntity =
4856         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4857                                                        /*Implicit*/ true)
4858                  : InitializedEntity::InitializeMember(Field, nullptr,
4859                                                        /*Implicit*/ true);
4860     InitializationKind InitKind =
4861       InitializationKind::CreateDefault(Loc);
4862 
4863     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4864     ExprResult MemberInit =
4865       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4866 
4867     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4868     if (MemberInit.isInvalid())
4869       return true;
4870 
4871     if (Indirect)
4872       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4873                                                                Indirect, Loc,
4874                                                                Loc,
4875                                                                MemberInit.get(),
4876                                                                Loc);
4877     else
4878       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4879                                                                Field, Loc, Loc,
4880                                                                MemberInit.get(),
4881                                                                Loc);
4882     return false;
4883   }
4884 
4885   if (!Field->getParent()->isUnion()) {
4886     if (FieldBaseElementType->isReferenceType()) {
4887       SemaRef.Diag(Constructor->getLocation(),
4888                    diag::err_uninitialized_member_in_ctor)
4889       << (int)Constructor->isImplicit()
4890       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4891       << 0 << Field->getDeclName();
4892       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4893       return true;
4894     }
4895 
4896     if (FieldBaseElementType.isConstQualified()) {
4897       SemaRef.Diag(Constructor->getLocation(),
4898                    diag::err_uninitialized_member_in_ctor)
4899       << (int)Constructor->isImplicit()
4900       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4901       << 1 << Field->getDeclName();
4902       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4903       return true;
4904     }
4905   }
4906 
4907   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4908     // ARC and Weak:
4909     //   Default-initialize Objective-C pointers to NULL.
4910     CXXMemberInit
4911       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4912                                                  Loc, Loc,
4913                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4914                                                  Loc);
4915     return false;
4916   }
4917 
4918   // Nothing to initialize.
4919   CXXMemberInit = nullptr;
4920   return false;
4921 }
4922 
4923 namespace {
4924 struct BaseAndFieldInfo {
4925   Sema &S;
4926   CXXConstructorDecl *Ctor;
4927   bool AnyErrorsInInits;
4928   ImplicitInitializerKind IIK;
4929   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4930   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4931   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4932 
4933   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4934     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4935     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4936     if (Ctor->getInheritedConstructor())
4937       IIK = IIK_Inherit;
4938     else if (Generated && Ctor->isCopyConstructor())
4939       IIK = IIK_Copy;
4940     else if (Generated && Ctor->isMoveConstructor())
4941       IIK = IIK_Move;
4942     else
4943       IIK = IIK_Default;
4944   }
4945 
4946   bool isImplicitCopyOrMove() const {
4947     switch (IIK) {
4948     case IIK_Copy:
4949     case IIK_Move:
4950       return true;
4951 
4952     case IIK_Default:
4953     case IIK_Inherit:
4954       return false;
4955     }
4956 
4957     llvm_unreachable("Invalid ImplicitInitializerKind!");
4958   }
4959 
4960   bool addFieldInitializer(CXXCtorInitializer *Init) {
4961     AllToInit.push_back(Init);
4962 
4963     // Check whether this initializer makes the field "used".
4964     if (Init->getInit()->HasSideEffects(S.Context))
4965       S.UnusedPrivateFields.remove(Init->getAnyMember());
4966 
4967     return false;
4968   }
4969 
4970   bool isInactiveUnionMember(FieldDecl *Field) {
4971     RecordDecl *Record = Field->getParent();
4972     if (!Record->isUnion())
4973       return false;
4974 
4975     if (FieldDecl *Active =
4976             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4977       return Active != Field->getCanonicalDecl();
4978 
4979     // In an implicit copy or move constructor, ignore any in-class initializer.
4980     if (isImplicitCopyOrMove())
4981       return true;
4982 
4983     // If there's no explicit initialization, the field is active only if it
4984     // has an in-class initializer...
4985     if (Field->hasInClassInitializer())
4986       return false;
4987     // ... or it's an anonymous struct or union whose class has an in-class
4988     // initializer.
4989     if (!Field->isAnonymousStructOrUnion())
4990       return true;
4991     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4992     return !FieldRD->hasInClassInitializer();
4993   }
4994 
4995   /// Determine whether the given field is, or is within, a union member
4996   /// that is inactive (because there was an initializer given for a different
4997   /// member of the union, or because the union was not initialized at all).
4998   bool isWithinInactiveUnionMember(FieldDecl *Field,
4999                                    IndirectFieldDecl *Indirect) {
5000     if (!Indirect)
5001       return isInactiveUnionMember(Field);
5002 
5003     for (auto *C : Indirect->chain()) {
5004       FieldDecl *Field = dyn_cast<FieldDecl>(C);
5005       if (Field && isInactiveUnionMember(Field))
5006         return true;
5007     }
5008     return false;
5009   }
5010 };
5011 }
5012 
5013 /// Determine whether the given type is an incomplete or zero-lenfgth
5014 /// array type.
5015 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5016   if (T->isIncompleteArrayType())
5017     return true;
5018 
5019   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5020     if (!ArrayT->getSize())
5021       return true;
5022 
5023     T = ArrayT->getElementType();
5024   }
5025 
5026   return false;
5027 }
5028 
5029 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5030                                     FieldDecl *Field,
5031                                     IndirectFieldDecl *Indirect = nullptr) {
5032   if (Field->isInvalidDecl())
5033     return false;
5034 
5035   // Overwhelmingly common case: we have a direct initializer for this field.
5036   if (CXXCtorInitializer *Init =
5037           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5038     return Info.addFieldInitializer(Init);
5039 
5040   // C++11 [class.base.init]p8:
5041   //   if the entity is a non-static data member that has a
5042   //   brace-or-equal-initializer and either
5043   //   -- the constructor's class is a union and no other variant member of that
5044   //      union is designated by a mem-initializer-id or
5045   //   -- the constructor's class is not a union, and, if the entity is a member
5046   //      of an anonymous union, no other member of that union is designated by
5047   //      a mem-initializer-id,
5048   //   the entity is initialized as specified in [dcl.init].
5049   //
5050   // We also apply the same rules to handle anonymous structs within anonymous
5051   // unions.
5052   if (Info.isWithinInactiveUnionMember(Field, Indirect))
5053     return false;
5054 
5055   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5056     ExprResult DIE =
5057         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5058     if (DIE.isInvalid())
5059       return true;
5060 
5061     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5062     SemaRef.checkInitializerLifetime(Entity, DIE.get());
5063 
5064     CXXCtorInitializer *Init;
5065     if (Indirect)
5066       Init = new (SemaRef.Context)
5067           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5068                              SourceLocation(), DIE.get(), SourceLocation());
5069     else
5070       Init = new (SemaRef.Context)
5071           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5072                              SourceLocation(), DIE.get(), SourceLocation());
5073     return Info.addFieldInitializer(Init);
5074   }
5075 
5076   // Don't initialize incomplete or zero-length arrays.
5077   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5078     return false;
5079 
5080   // Don't try to build an implicit initializer if there were semantic
5081   // errors in any of the initializers (and therefore we might be
5082   // missing some that the user actually wrote).
5083   if (Info.AnyErrorsInInits)
5084     return false;
5085 
5086   CXXCtorInitializer *Init = nullptr;
5087   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5088                                      Indirect, Init))
5089     return true;
5090 
5091   if (!Init)
5092     return false;
5093 
5094   return Info.addFieldInitializer(Init);
5095 }
5096 
5097 bool
5098 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5099                                CXXCtorInitializer *Initializer) {
5100   assert(Initializer->isDelegatingInitializer());
5101   Constructor->setNumCtorInitializers(1);
5102   CXXCtorInitializer **initializer =
5103     new (Context) CXXCtorInitializer*[1];
5104   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5105   Constructor->setCtorInitializers(initializer);
5106 
5107   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5108     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5109     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5110   }
5111 
5112   DelegatingCtorDecls.push_back(Constructor);
5113 
5114   DiagnoseUninitializedFields(*this, Constructor);
5115 
5116   return false;
5117 }
5118 
5119 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5120                                ArrayRef<CXXCtorInitializer *> Initializers) {
5121   if (Constructor->isDependentContext()) {
5122     // Just store the initializers as written, they will be checked during
5123     // instantiation.
5124     if (!Initializers.empty()) {
5125       Constructor->setNumCtorInitializers(Initializers.size());
5126       CXXCtorInitializer **baseOrMemberInitializers =
5127         new (Context) CXXCtorInitializer*[Initializers.size()];
5128       memcpy(baseOrMemberInitializers, Initializers.data(),
5129              Initializers.size() * sizeof(CXXCtorInitializer*));
5130       Constructor->setCtorInitializers(baseOrMemberInitializers);
5131     }
5132 
5133     // Let template instantiation know whether we had errors.
5134     if (AnyErrors)
5135       Constructor->setInvalidDecl();
5136 
5137     return false;
5138   }
5139 
5140   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5141 
5142   // We need to build the initializer AST according to order of construction
5143   // and not what user specified in the Initializers list.
5144   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5145   if (!ClassDecl)
5146     return true;
5147 
5148   bool HadError = false;
5149 
5150   for (unsigned i = 0; i < Initializers.size(); i++) {
5151     CXXCtorInitializer *Member = Initializers[i];
5152 
5153     if (Member->isBaseInitializer())
5154       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5155     else {
5156       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5157 
5158       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5159         for (auto *C : F->chain()) {
5160           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5161           if (FD && FD->getParent()->isUnion())
5162             Info.ActiveUnionMember.insert(std::make_pair(
5163                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5164         }
5165       } else if (FieldDecl *FD = Member->getMember()) {
5166         if (FD->getParent()->isUnion())
5167           Info.ActiveUnionMember.insert(std::make_pair(
5168               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5169       }
5170     }
5171   }
5172 
5173   // Keep track of the direct virtual bases.
5174   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5175   for (auto &I : ClassDecl->bases()) {
5176     if (I.isVirtual())
5177       DirectVBases.insert(&I);
5178   }
5179 
5180   // Push virtual bases before others.
5181   for (auto &VBase : ClassDecl->vbases()) {
5182     if (CXXCtorInitializer *Value
5183         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5184       // [class.base.init]p7, per DR257:
5185       //   A mem-initializer where the mem-initializer-id names a virtual base
5186       //   class is ignored during execution of a constructor of any class that
5187       //   is not the most derived class.
5188       if (ClassDecl->isAbstract()) {
5189         // FIXME: Provide a fixit to remove the base specifier. This requires
5190         // tracking the location of the associated comma for a base specifier.
5191         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5192           << VBase.getType() << ClassDecl;
5193         DiagnoseAbstractType(ClassDecl);
5194       }
5195 
5196       Info.AllToInit.push_back(Value);
5197     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5198       // [class.base.init]p8, per DR257:
5199       //   If a given [...] base class is not named by a mem-initializer-id
5200       //   [...] and the entity is not a virtual base class of an abstract
5201       //   class, then [...] the entity is default-initialized.
5202       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5203       CXXCtorInitializer *CXXBaseInit;
5204       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5205                                        &VBase, IsInheritedVirtualBase,
5206                                        CXXBaseInit)) {
5207         HadError = true;
5208         continue;
5209       }
5210 
5211       Info.AllToInit.push_back(CXXBaseInit);
5212     }
5213   }
5214 
5215   // Non-virtual bases.
5216   for (auto &Base : ClassDecl->bases()) {
5217     // Virtuals are in the virtual base list and already constructed.
5218     if (Base.isVirtual())
5219       continue;
5220 
5221     if (CXXCtorInitializer *Value
5222           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5223       Info.AllToInit.push_back(Value);
5224     } else if (!AnyErrors) {
5225       CXXCtorInitializer *CXXBaseInit;
5226       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5227                                        &Base, /*IsInheritedVirtualBase=*/false,
5228                                        CXXBaseInit)) {
5229         HadError = true;
5230         continue;
5231       }
5232 
5233       Info.AllToInit.push_back(CXXBaseInit);
5234     }
5235   }
5236 
5237   // Fields.
5238   for (auto *Mem : ClassDecl->decls()) {
5239     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5240       // C++ [class.bit]p2:
5241       //   A declaration for a bit-field that omits the identifier declares an
5242       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5243       //   initialized.
5244       if (F->isUnnamedBitfield())
5245         continue;
5246 
5247       // If we're not generating the implicit copy/move constructor, then we'll
5248       // handle anonymous struct/union fields based on their individual
5249       // indirect fields.
5250       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5251         continue;
5252 
5253       if (CollectFieldInitializer(*this, Info, F))
5254         HadError = true;
5255       continue;
5256     }
5257 
5258     // Beyond this point, we only consider default initialization.
5259     if (Info.isImplicitCopyOrMove())
5260       continue;
5261 
5262     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5263       if (F->getType()->isIncompleteArrayType()) {
5264         assert(ClassDecl->hasFlexibleArrayMember() &&
5265                "Incomplete array type is not valid");
5266         continue;
5267       }
5268 
5269       // Initialize each field of an anonymous struct individually.
5270       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5271         HadError = true;
5272 
5273       continue;
5274     }
5275   }
5276 
5277   unsigned NumInitializers = Info.AllToInit.size();
5278   if (NumInitializers > 0) {
5279     Constructor->setNumCtorInitializers(NumInitializers);
5280     CXXCtorInitializer **baseOrMemberInitializers =
5281       new (Context) CXXCtorInitializer*[NumInitializers];
5282     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5283            NumInitializers * sizeof(CXXCtorInitializer*));
5284     Constructor->setCtorInitializers(baseOrMemberInitializers);
5285 
5286     // Constructors implicitly reference the base and member
5287     // destructors.
5288     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5289                                            Constructor->getParent());
5290   }
5291 
5292   return HadError;
5293 }
5294 
5295 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5296   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5297     const RecordDecl *RD = RT->getDecl();
5298     if (RD->isAnonymousStructOrUnion()) {
5299       for (auto *Field : RD->fields())
5300         PopulateKeysForFields(Field, IdealInits);
5301       return;
5302     }
5303   }
5304   IdealInits.push_back(Field->getCanonicalDecl());
5305 }
5306 
5307 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5308   return Context.getCanonicalType(BaseType).getTypePtr();
5309 }
5310 
5311 static const void *GetKeyForMember(ASTContext &Context,
5312                                    CXXCtorInitializer *Member) {
5313   if (!Member->isAnyMemberInitializer())
5314     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5315 
5316   return Member->getAnyMember()->getCanonicalDecl();
5317 }
5318 
5319 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5320                                  const CXXCtorInitializer *Previous,
5321                                  const CXXCtorInitializer *Current) {
5322   if (Previous->isAnyMemberInitializer())
5323     Diag << 0 << Previous->getAnyMember();
5324   else
5325     Diag << 1 << Previous->getTypeSourceInfo()->getType();
5326 
5327   if (Current->isAnyMemberInitializer())
5328     Diag << 0 << Current->getAnyMember();
5329   else
5330     Diag << 1 << Current->getTypeSourceInfo()->getType();
5331 }
5332 
5333 static void DiagnoseBaseOrMemInitializerOrder(
5334     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5335     ArrayRef<CXXCtorInitializer *> Inits) {
5336   if (Constructor->getDeclContext()->isDependentContext())
5337     return;
5338 
5339   // Don't check initializers order unless the warning is enabled at the
5340   // location of at least one initializer.
5341   bool ShouldCheckOrder = false;
5342   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5343     CXXCtorInitializer *Init = Inits[InitIndex];
5344     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5345                                  Init->getSourceLocation())) {
5346       ShouldCheckOrder = true;
5347       break;
5348     }
5349   }
5350   if (!ShouldCheckOrder)
5351     return;
5352 
5353   // Build the list of bases and members in the order that they'll
5354   // actually be initialized.  The explicit initializers should be in
5355   // this same order but may be missing things.
5356   SmallVector<const void*, 32> IdealInitKeys;
5357 
5358   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5359 
5360   // 1. Virtual bases.
5361   for (const auto &VBase : ClassDecl->vbases())
5362     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5363 
5364   // 2. Non-virtual bases.
5365   for (const auto &Base : ClassDecl->bases()) {
5366     if (Base.isVirtual())
5367       continue;
5368     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5369   }
5370 
5371   // 3. Direct fields.
5372   for (auto *Field : ClassDecl->fields()) {
5373     if (Field->isUnnamedBitfield())
5374       continue;
5375 
5376     PopulateKeysForFields(Field, IdealInitKeys);
5377   }
5378 
5379   unsigned NumIdealInits = IdealInitKeys.size();
5380   unsigned IdealIndex = 0;
5381 
5382   // Track initializers that are in an incorrect order for either a warning or
5383   // note if multiple ones occur.
5384   SmallVector<unsigned> WarnIndexes;
5385   // Correlates the index of an initializer in the init-list to the index of
5386   // the field/base in the class.
5387   SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5388 
5389   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5390     const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5391 
5392     // Scan forward to try to find this initializer in the idealized
5393     // initializers list.
5394     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5395       if (InitKey == IdealInitKeys[IdealIndex])
5396         break;
5397 
5398     // If we didn't find this initializer, it must be because we
5399     // scanned past it on a previous iteration.  That can only
5400     // happen if we're out of order;  emit a warning.
5401     if (IdealIndex == NumIdealInits && InitIndex) {
5402       WarnIndexes.push_back(InitIndex);
5403 
5404       // Move back to the initializer's location in the ideal list.
5405       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5406         if (InitKey == IdealInitKeys[IdealIndex])
5407           break;
5408 
5409       assert(IdealIndex < NumIdealInits &&
5410              "initializer not found in initializer list");
5411     }
5412     CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5413   }
5414 
5415   if (WarnIndexes.empty())
5416     return;
5417 
5418   // Sort based on the ideal order, first in the pair.
5419   llvm::sort(CorrelatedInitOrder,
5420              [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; });
5421 
5422   // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5423   // emit the diagnostic before we can try adding notes.
5424   {
5425     Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5426         Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5427         WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5428                                 : diag::warn_some_initializers_out_of_order);
5429 
5430     for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5431       if (CorrelatedInitOrder[I].second == I)
5432         continue;
5433       // Ideally we would be using InsertFromRange here, but clang doesn't
5434       // appear to handle InsertFromRange correctly when the source range is
5435       // modified by another fix-it.
5436       D << FixItHint::CreateReplacement(
5437           Inits[I]->getSourceRange(),
5438           Lexer::getSourceText(
5439               CharSourceRange::getTokenRange(
5440                   Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5441               SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5442     }
5443 
5444     // If there is only 1 item out of order, the warning expects the name and
5445     // type of each being added to it.
5446     if (WarnIndexes.size() == 1) {
5447       AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5448                            Inits[WarnIndexes.front()]);
5449       return;
5450     }
5451   }
5452   // More than 1 item to warn, create notes letting the user know which ones
5453   // are bad.
5454   for (unsigned WarnIndex : WarnIndexes) {
5455     const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5456     auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5457                           diag::note_initializer_out_of_order);
5458     AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5459     D << PrevInit->getSourceRange();
5460   }
5461 }
5462 
5463 namespace {
5464 bool CheckRedundantInit(Sema &S,
5465                         CXXCtorInitializer *Init,
5466                         CXXCtorInitializer *&PrevInit) {
5467   if (!PrevInit) {
5468     PrevInit = Init;
5469     return false;
5470   }
5471 
5472   if (FieldDecl *Field = Init->getAnyMember())
5473     S.Diag(Init->getSourceLocation(),
5474            diag::err_multiple_mem_initialization)
5475       << Field->getDeclName()
5476       << Init->getSourceRange();
5477   else {
5478     const Type *BaseClass = Init->getBaseClass();
5479     assert(BaseClass && "neither field nor base");
5480     S.Diag(Init->getSourceLocation(),
5481            diag::err_multiple_base_initialization)
5482       << QualType(BaseClass, 0)
5483       << Init->getSourceRange();
5484   }
5485   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5486     << 0 << PrevInit->getSourceRange();
5487 
5488   return true;
5489 }
5490 
5491 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5492 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5493 
5494 bool CheckRedundantUnionInit(Sema &S,
5495                              CXXCtorInitializer *Init,
5496                              RedundantUnionMap &Unions) {
5497   FieldDecl *Field = Init->getAnyMember();
5498   RecordDecl *Parent = Field->getParent();
5499   NamedDecl *Child = Field;
5500 
5501   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5502     if (Parent->isUnion()) {
5503       UnionEntry &En = Unions[Parent];
5504       if (En.first && En.first != Child) {
5505         S.Diag(Init->getSourceLocation(),
5506                diag::err_multiple_mem_union_initialization)
5507           << Field->getDeclName()
5508           << Init->getSourceRange();
5509         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5510           << 0 << En.second->getSourceRange();
5511         return true;
5512       }
5513       if (!En.first) {
5514         En.first = Child;
5515         En.second = Init;
5516       }
5517       if (!Parent->isAnonymousStructOrUnion())
5518         return false;
5519     }
5520 
5521     Child = Parent;
5522     Parent = cast<RecordDecl>(Parent->getDeclContext());
5523   }
5524 
5525   return false;
5526 }
5527 } // namespace
5528 
5529 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5530 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5531                                 SourceLocation ColonLoc,
5532                                 ArrayRef<CXXCtorInitializer*> MemInits,
5533                                 bool AnyErrors) {
5534   if (!ConstructorDecl)
5535     return;
5536 
5537   AdjustDeclIfTemplate(ConstructorDecl);
5538 
5539   CXXConstructorDecl *Constructor
5540     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5541 
5542   if (!Constructor) {
5543     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5544     return;
5545   }
5546 
5547   // Mapping for the duplicate initializers check.
5548   // For member initializers, this is keyed with a FieldDecl*.
5549   // For base initializers, this is keyed with a Type*.
5550   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5551 
5552   // Mapping for the inconsistent anonymous-union initializers check.
5553   RedundantUnionMap MemberUnions;
5554 
5555   bool HadError = false;
5556   for (unsigned i = 0; i < MemInits.size(); i++) {
5557     CXXCtorInitializer *Init = MemInits[i];
5558 
5559     // Set the source order index.
5560     Init->setSourceOrder(i);
5561 
5562     if (Init->isAnyMemberInitializer()) {
5563       const void *Key = GetKeyForMember(Context, Init);
5564       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5565           CheckRedundantUnionInit(*this, Init, MemberUnions))
5566         HadError = true;
5567     } else if (Init->isBaseInitializer()) {
5568       const void *Key = GetKeyForMember(Context, Init);
5569       if (CheckRedundantInit(*this, Init, Members[Key]))
5570         HadError = true;
5571     } else {
5572       assert(Init->isDelegatingInitializer());
5573       // This must be the only initializer
5574       if (MemInits.size() != 1) {
5575         Diag(Init->getSourceLocation(),
5576              diag::err_delegating_initializer_alone)
5577           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5578         // We will treat this as being the only initializer.
5579       }
5580       SetDelegatingInitializer(Constructor, MemInits[i]);
5581       // Return immediately as the initializer is set.
5582       return;
5583     }
5584   }
5585 
5586   if (HadError)
5587     return;
5588 
5589   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5590 
5591   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5592 
5593   DiagnoseUninitializedFields(*this, Constructor);
5594 }
5595 
5596 void
5597 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5598                                              CXXRecordDecl *ClassDecl) {
5599   // Ignore dependent contexts. Also ignore unions, since their members never
5600   // have destructors implicitly called.
5601   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5602     return;
5603 
5604   // FIXME: all the access-control diagnostics are positioned on the
5605   // field/base declaration.  That's probably good; that said, the
5606   // user might reasonably want to know why the destructor is being
5607   // emitted, and we currently don't say.
5608 
5609   // Non-static data members.
5610   for (auto *Field : ClassDecl->fields()) {
5611     if (Field->isInvalidDecl())
5612       continue;
5613 
5614     // Don't destroy incomplete or zero-length arrays.
5615     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5616       continue;
5617 
5618     QualType FieldType = Context.getBaseElementType(Field->getType());
5619 
5620     const RecordType* RT = FieldType->getAs<RecordType>();
5621     if (!RT)
5622       continue;
5623 
5624     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5625     if (FieldClassDecl->isInvalidDecl())
5626       continue;
5627     if (FieldClassDecl->hasIrrelevantDestructor())
5628       continue;
5629     // The destructor for an implicit anonymous union member is never invoked.
5630     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5631       continue;
5632 
5633     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5634     assert(Dtor && "No dtor found for FieldClassDecl!");
5635     CheckDestructorAccess(Field->getLocation(), Dtor,
5636                           PDiag(diag::err_access_dtor_field)
5637                             << Field->getDeclName()
5638                             << FieldType);
5639 
5640     MarkFunctionReferenced(Location, Dtor);
5641     DiagnoseUseOfDecl(Dtor, Location);
5642   }
5643 
5644   // We only potentially invoke the destructors of potentially constructed
5645   // subobjects.
5646   bool VisitVirtualBases = !ClassDecl->isAbstract();
5647 
5648   // If the destructor exists and has already been marked used in the MS ABI,
5649   // then virtual base destructors have already been checked and marked used.
5650   // Skip checking them again to avoid duplicate diagnostics.
5651   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5652     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5653     if (Dtor && Dtor->isUsed())
5654       VisitVirtualBases = false;
5655   }
5656 
5657   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5658 
5659   // Bases.
5660   for (const auto &Base : ClassDecl->bases()) {
5661     const RecordType *RT = Base.getType()->getAs<RecordType>();
5662     if (!RT)
5663       continue;
5664 
5665     // Remember direct virtual bases.
5666     if (Base.isVirtual()) {
5667       if (!VisitVirtualBases)
5668         continue;
5669       DirectVirtualBases.insert(RT);
5670     }
5671 
5672     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5673     // If our base class is invalid, we probably can't get its dtor anyway.
5674     if (BaseClassDecl->isInvalidDecl())
5675       continue;
5676     if (BaseClassDecl->hasIrrelevantDestructor())
5677       continue;
5678 
5679     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5680     assert(Dtor && "No dtor found for BaseClassDecl!");
5681 
5682     // FIXME: caret should be on the start of the class name
5683     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5684                           PDiag(diag::err_access_dtor_base)
5685                               << Base.getType() << Base.getSourceRange(),
5686                           Context.getTypeDeclType(ClassDecl));
5687 
5688     MarkFunctionReferenced(Location, Dtor);
5689     DiagnoseUseOfDecl(Dtor, Location);
5690   }
5691 
5692   if (VisitVirtualBases)
5693     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5694                                          &DirectVirtualBases);
5695 }
5696 
5697 void Sema::MarkVirtualBaseDestructorsReferenced(
5698     SourceLocation Location, CXXRecordDecl *ClassDecl,
5699     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5700   // Virtual bases.
5701   for (const auto &VBase : ClassDecl->vbases()) {
5702     // Bases are always records in a well-formed non-dependent class.
5703     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5704 
5705     // Ignore already visited direct virtual bases.
5706     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5707       continue;
5708 
5709     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5710     // If our base class is invalid, we probably can't get its dtor anyway.
5711     if (BaseClassDecl->isInvalidDecl())
5712       continue;
5713     if (BaseClassDecl->hasIrrelevantDestructor())
5714       continue;
5715 
5716     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5717     assert(Dtor && "No dtor found for BaseClassDecl!");
5718     if (CheckDestructorAccess(
5719             ClassDecl->getLocation(), Dtor,
5720             PDiag(diag::err_access_dtor_vbase)
5721                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5722             Context.getTypeDeclType(ClassDecl)) ==
5723         AR_accessible) {
5724       CheckDerivedToBaseConversion(
5725           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5726           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5727           SourceRange(), DeclarationName(), nullptr);
5728     }
5729 
5730     MarkFunctionReferenced(Location, Dtor);
5731     DiagnoseUseOfDecl(Dtor, Location);
5732   }
5733 }
5734 
5735 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5736   if (!CDtorDecl)
5737     return;
5738 
5739   if (CXXConstructorDecl *Constructor
5740       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5741     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5742     DiagnoseUninitializedFields(*this, Constructor);
5743   }
5744 }
5745 
5746 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5747   if (!getLangOpts().CPlusPlus)
5748     return false;
5749 
5750   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5751   if (!RD)
5752     return false;
5753 
5754   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5755   // class template specialization here, but doing so breaks a lot of code.
5756 
5757   // We can't answer whether something is abstract until it has a
5758   // definition. If it's currently being defined, we'll walk back
5759   // over all the declarations when we have a full definition.
5760   const CXXRecordDecl *Def = RD->getDefinition();
5761   if (!Def || Def->isBeingDefined())
5762     return false;
5763 
5764   return RD->isAbstract();
5765 }
5766 
5767 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5768                                   TypeDiagnoser &Diagnoser) {
5769   if (!isAbstractType(Loc, T))
5770     return false;
5771 
5772   T = Context.getBaseElementType(T);
5773   Diagnoser.diagnose(*this, Loc, T);
5774   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5775   return true;
5776 }
5777 
5778 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5779   // Check if we've already emitted the list of pure virtual functions
5780   // for this class.
5781   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5782     return;
5783 
5784   // If the diagnostic is suppressed, don't emit the notes. We're only
5785   // going to emit them once, so try to attach them to a diagnostic we're
5786   // actually going to show.
5787   if (Diags.isLastDiagnosticIgnored())
5788     return;
5789 
5790   CXXFinalOverriderMap FinalOverriders;
5791   RD->getFinalOverriders(FinalOverriders);
5792 
5793   // Keep a set of seen pure methods so we won't diagnose the same method
5794   // more than once.
5795   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5796 
5797   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5798                                    MEnd = FinalOverriders.end();
5799        M != MEnd;
5800        ++M) {
5801     for (OverridingMethods::iterator SO = M->second.begin(),
5802                                   SOEnd = M->second.end();
5803          SO != SOEnd; ++SO) {
5804       // C++ [class.abstract]p4:
5805       //   A class is abstract if it contains or inherits at least one
5806       //   pure virtual function for which the final overrider is pure
5807       //   virtual.
5808 
5809       //
5810       if (SO->second.size() != 1)
5811         continue;
5812 
5813       if (!SO->second.front().Method->isPure())
5814         continue;
5815 
5816       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5817         continue;
5818 
5819       Diag(SO->second.front().Method->getLocation(),
5820            diag::note_pure_virtual_function)
5821         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5822     }
5823   }
5824 
5825   if (!PureVirtualClassDiagSet)
5826     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5827   PureVirtualClassDiagSet->insert(RD);
5828 }
5829 
5830 namespace {
5831 struct AbstractUsageInfo {
5832   Sema &S;
5833   CXXRecordDecl *Record;
5834   CanQualType AbstractType;
5835   bool Invalid;
5836 
5837   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5838     : S(S), Record(Record),
5839       AbstractType(S.Context.getCanonicalType(
5840                    S.Context.getTypeDeclType(Record))),
5841       Invalid(false) {}
5842 
5843   void DiagnoseAbstractType() {
5844     if (Invalid) return;
5845     S.DiagnoseAbstractType(Record);
5846     Invalid = true;
5847   }
5848 
5849   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5850 };
5851 
5852 struct CheckAbstractUsage {
5853   AbstractUsageInfo &Info;
5854   const NamedDecl *Ctx;
5855 
5856   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5857     : Info(Info), Ctx(Ctx) {}
5858 
5859   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5860     switch (TL.getTypeLocClass()) {
5861 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5862 #define TYPELOC(CLASS, PARENT) \
5863     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5864 #include "clang/AST/TypeLocNodes.def"
5865     }
5866   }
5867 
5868   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5869     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5870     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5871       if (!TL.getParam(I))
5872         continue;
5873 
5874       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5875       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5876     }
5877   }
5878 
5879   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5880     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5881   }
5882 
5883   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5884     // Visit the type parameters from a permissive context.
5885     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5886       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5887       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5888         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5889           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5890       // TODO: other template argument types?
5891     }
5892   }
5893 
5894   // Visit pointee types from a permissive context.
5895 #define CheckPolymorphic(Type) \
5896   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5897     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5898   }
5899   CheckPolymorphic(PointerTypeLoc)
5900   CheckPolymorphic(ReferenceTypeLoc)
5901   CheckPolymorphic(MemberPointerTypeLoc)
5902   CheckPolymorphic(BlockPointerTypeLoc)
5903   CheckPolymorphic(AtomicTypeLoc)
5904 
5905   /// Handle all the types we haven't given a more specific
5906   /// implementation for above.
5907   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5908     // Every other kind of type that we haven't called out already
5909     // that has an inner type is either (1) sugar or (2) contains that
5910     // inner type in some way as a subobject.
5911     if (TypeLoc Next = TL.getNextTypeLoc())
5912       return Visit(Next, Sel);
5913 
5914     // If there's no inner type and we're in a permissive context,
5915     // don't diagnose.
5916     if (Sel == Sema::AbstractNone) return;
5917 
5918     // Check whether the type matches the abstract type.
5919     QualType T = TL.getType();
5920     if (T->isArrayType()) {
5921       Sel = Sema::AbstractArrayType;
5922       T = Info.S.Context.getBaseElementType(T);
5923     }
5924     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5925     if (CT != Info.AbstractType) return;
5926 
5927     // It matched; do some magic.
5928     // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
5929     if (Sel == Sema::AbstractArrayType) {
5930       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5931         << T << TL.getSourceRange();
5932     } else {
5933       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5934         << Sel << T << TL.getSourceRange();
5935     }
5936     Info.DiagnoseAbstractType();
5937   }
5938 };
5939 
5940 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5941                                   Sema::AbstractDiagSelID Sel) {
5942   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5943 }
5944 
5945 }
5946 
5947 /// Check for invalid uses of an abstract type in a function declaration.
5948 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5949                                     FunctionDecl *FD) {
5950   // No need to do the check on definitions, which require that
5951   // the return/param types be complete.
5952   if (FD->doesThisDeclarationHaveABody())
5953     return;
5954 
5955   // For safety's sake, just ignore it if we don't have type source
5956   // information.  This should never happen for non-implicit methods,
5957   // but...
5958   if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5959     Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
5960 }
5961 
5962 /// Check for invalid uses of an abstract type in a variable0 declaration.
5963 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5964                                     VarDecl *VD) {
5965   // No need to do the check on definitions, which require that
5966   // the type is complete.
5967   if (VD->isThisDeclarationADefinition())
5968     return;
5969 
5970   Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
5971                  Sema::AbstractVariableType);
5972 }
5973 
5974 /// Check for invalid uses of an abstract type within a class definition.
5975 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5976                                     CXXRecordDecl *RD) {
5977   for (auto *D : RD->decls()) {
5978     if (D->isImplicit()) continue;
5979 
5980     // Step through friends to the befriended declaration.
5981     if (auto *FD = dyn_cast<FriendDecl>(D)) {
5982       D = FD->getFriendDecl();
5983       if (!D) continue;
5984     }
5985 
5986     // Functions and function templates.
5987     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5988       CheckAbstractClassUsage(Info, FD);
5989     } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
5990       CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
5991 
5992     // Fields and static variables.
5993     } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
5994       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5995         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5996     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
5997       CheckAbstractClassUsage(Info, VD);
5998     } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
5999       CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6000 
6001     // Nested classes and class templates.
6002     } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6003       CheckAbstractClassUsage(Info, RD);
6004     } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6005       CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6006     }
6007   }
6008 }
6009 
6010 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6011   Attr *ClassAttr = getDLLAttr(Class);
6012   if (!ClassAttr)
6013     return;
6014 
6015   assert(ClassAttr->getKind() == attr::DLLExport);
6016 
6017   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6018 
6019   if (TSK == TSK_ExplicitInstantiationDeclaration)
6020     // Don't go any further if this is just an explicit instantiation
6021     // declaration.
6022     return;
6023 
6024   // Add a context note to explain how we got to any diagnostics produced below.
6025   struct MarkingClassDllexported {
6026     Sema &S;
6027     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6028                             SourceLocation AttrLoc)
6029         : S(S) {
6030       Sema::CodeSynthesisContext Ctx;
6031       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6032       Ctx.PointOfInstantiation = AttrLoc;
6033       Ctx.Entity = Class;
6034       S.pushCodeSynthesisContext(Ctx);
6035     }
6036     ~MarkingClassDllexported() {
6037       S.popCodeSynthesisContext();
6038     }
6039   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6040 
6041   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6042     S.MarkVTableUsed(Class->getLocation(), Class, true);
6043 
6044   for (Decl *Member : Class->decls()) {
6045     // Skip members that were not marked exported.
6046     if (!Member->hasAttr<DLLExportAttr>())
6047       continue;
6048 
6049     // Defined static variables that are members of an exported base
6050     // class must be marked export too.
6051     auto *VD = dyn_cast<VarDecl>(Member);
6052     if (VD && VD->getStorageClass() == SC_Static &&
6053         TSK == TSK_ImplicitInstantiation)
6054       S.MarkVariableReferenced(VD->getLocation(), VD);
6055 
6056     auto *MD = dyn_cast<CXXMethodDecl>(Member);
6057     if (!MD)
6058       continue;
6059 
6060     if (MD->isUserProvided()) {
6061       // Instantiate non-default class member functions ...
6062 
6063       // .. except for certain kinds of template specializations.
6064       if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6065         continue;
6066 
6067       // If this is an MS ABI dllexport default constructor, instantiate any
6068       // default arguments.
6069       if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6070         auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6071         if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6072           S.InstantiateDefaultCtorDefaultArgs(CD);
6073         }
6074       }
6075 
6076       S.MarkFunctionReferenced(Class->getLocation(), MD);
6077 
6078       // The function will be passed to the consumer when its definition is
6079       // encountered.
6080     } else if (MD->isExplicitlyDefaulted()) {
6081       // Synthesize and instantiate explicitly defaulted methods.
6082       S.MarkFunctionReferenced(Class->getLocation(), MD);
6083 
6084       if (TSK != TSK_ExplicitInstantiationDefinition) {
6085         // Except for explicit instantiation defs, we will not see the
6086         // definition again later, so pass it to the consumer now.
6087         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6088       }
6089     } else if (!MD->isTrivial() ||
6090                MD->isCopyAssignmentOperator() ||
6091                MD->isMoveAssignmentOperator()) {
6092       // Synthesize and instantiate non-trivial implicit methods, and the copy
6093       // and move assignment operators. The latter are exported even if they
6094       // are trivial, because the address of an operator can be taken and
6095       // should compare equal across libraries.
6096       S.MarkFunctionReferenced(Class->getLocation(), MD);
6097 
6098       // There is no later point when we will see the definition of this
6099       // function, so pass it to the consumer now.
6100       S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6101     }
6102   }
6103 }
6104 
6105 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6106                                                         CXXRecordDecl *Class) {
6107   // Only the MS ABI has default constructor closures, so we don't need to do
6108   // this semantic checking anywhere else.
6109   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6110     return;
6111 
6112   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6113   for (Decl *Member : Class->decls()) {
6114     // Look for exported default constructors.
6115     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6116     if (!CD || !CD->isDefaultConstructor())
6117       continue;
6118     auto *Attr = CD->getAttr<DLLExportAttr>();
6119     if (!Attr)
6120       continue;
6121 
6122     // If the class is non-dependent, mark the default arguments as ODR-used so
6123     // that we can properly codegen the constructor closure.
6124     if (!Class->isDependentContext()) {
6125       for (ParmVarDecl *PD : CD->parameters()) {
6126         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6127         S.DiscardCleanupsInEvaluationContext();
6128       }
6129     }
6130 
6131     if (LastExportedDefaultCtor) {
6132       S.Diag(LastExportedDefaultCtor->getLocation(),
6133              diag::err_attribute_dll_ambiguous_default_ctor)
6134           << Class;
6135       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6136           << CD->getDeclName();
6137       return;
6138     }
6139     LastExportedDefaultCtor = CD;
6140   }
6141 }
6142 
6143 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6144                                                        CXXRecordDecl *Class) {
6145   bool ErrorReported = false;
6146   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6147                                                      ClassTemplateDecl *TD) {
6148     if (ErrorReported)
6149       return;
6150     S.Diag(TD->getLocation(),
6151            diag::err_cuda_device_builtin_surftex_cls_template)
6152         << /*surface*/ 0 << TD;
6153     ErrorReported = true;
6154   };
6155 
6156   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6157   if (!TD) {
6158     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6159     if (!SD) {
6160       S.Diag(Class->getLocation(),
6161              diag::err_cuda_device_builtin_surftex_ref_decl)
6162           << /*surface*/ 0 << Class;
6163       S.Diag(Class->getLocation(),
6164              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6165           << Class;
6166       return;
6167     }
6168     TD = SD->getSpecializedTemplate();
6169   }
6170 
6171   TemplateParameterList *Params = TD->getTemplateParameters();
6172   unsigned N = Params->size();
6173 
6174   if (N != 2) {
6175     reportIllegalClassTemplate(S, TD);
6176     S.Diag(TD->getLocation(),
6177            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6178         << TD << 2;
6179   }
6180   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6181     reportIllegalClassTemplate(S, TD);
6182     S.Diag(TD->getLocation(),
6183            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6184         << TD << /*1st*/ 0 << /*type*/ 0;
6185   }
6186   if (N > 1) {
6187     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6188     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6189       reportIllegalClassTemplate(S, TD);
6190       S.Diag(TD->getLocation(),
6191              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6192           << TD << /*2nd*/ 1 << /*integer*/ 1;
6193     }
6194   }
6195 }
6196 
6197 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6198                                                        CXXRecordDecl *Class) {
6199   bool ErrorReported = false;
6200   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6201                                                      ClassTemplateDecl *TD) {
6202     if (ErrorReported)
6203       return;
6204     S.Diag(TD->getLocation(),
6205            diag::err_cuda_device_builtin_surftex_cls_template)
6206         << /*texture*/ 1 << TD;
6207     ErrorReported = true;
6208   };
6209 
6210   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6211   if (!TD) {
6212     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6213     if (!SD) {
6214       S.Diag(Class->getLocation(),
6215              diag::err_cuda_device_builtin_surftex_ref_decl)
6216           << /*texture*/ 1 << Class;
6217       S.Diag(Class->getLocation(),
6218              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6219           << Class;
6220       return;
6221     }
6222     TD = SD->getSpecializedTemplate();
6223   }
6224 
6225   TemplateParameterList *Params = TD->getTemplateParameters();
6226   unsigned N = Params->size();
6227 
6228   if (N != 3) {
6229     reportIllegalClassTemplate(S, TD);
6230     S.Diag(TD->getLocation(),
6231            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6232         << TD << 3;
6233   }
6234   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6235     reportIllegalClassTemplate(S, TD);
6236     S.Diag(TD->getLocation(),
6237            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6238         << TD << /*1st*/ 0 << /*type*/ 0;
6239   }
6240   if (N > 1) {
6241     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6242     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6243       reportIllegalClassTemplate(S, TD);
6244       S.Diag(TD->getLocation(),
6245              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6246           << TD << /*2nd*/ 1 << /*integer*/ 1;
6247     }
6248   }
6249   if (N > 2) {
6250     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6251     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6252       reportIllegalClassTemplate(S, TD);
6253       S.Diag(TD->getLocation(),
6254              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6255           << TD << /*3rd*/ 2 << /*integer*/ 1;
6256     }
6257   }
6258 }
6259 
6260 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6261   // Mark any compiler-generated routines with the implicit code_seg attribute.
6262   for (auto *Method : Class->methods()) {
6263     if (Method->isUserProvided())
6264       continue;
6265     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6266       Method->addAttr(A);
6267   }
6268 }
6269 
6270 /// Check class-level dllimport/dllexport attribute.
6271 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6272   Attr *ClassAttr = getDLLAttr(Class);
6273 
6274   // MSVC inherits DLL attributes to partial class template specializations.
6275   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6276     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6277       if (Attr *TemplateAttr =
6278               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6279         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6280         A->setInherited(true);
6281         ClassAttr = A;
6282       }
6283     }
6284   }
6285 
6286   if (!ClassAttr)
6287     return;
6288 
6289   if (!Class->isExternallyVisible()) {
6290     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6291         << Class << ClassAttr;
6292     return;
6293   }
6294 
6295   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6296       !ClassAttr->isInherited()) {
6297     // Diagnose dll attributes on members of class with dll attribute.
6298     for (Decl *Member : Class->decls()) {
6299       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6300         continue;
6301       InheritableAttr *MemberAttr = getDLLAttr(Member);
6302       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6303         continue;
6304 
6305       Diag(MemberAttr->getLocation(),
6306              diag::err_attribute_dll_member_of_dll_class)
6307           << MemberAttr << ClassAttr;
6308       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6309       Member->setInvalidDecl();
6310     }
6311   }
6312 
6313   if (Class->getDescribedClassTemplate())
6314     // Don't inherit dll attribute until the template is instantiated.
6315     return;
6316 
6317   // The class is either imported or exported.
6318   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6319 
6320   // Check if this was a dllimport attribute propagated from a derived class to
6321   // a base class template specialization. We don't apply these attributes to
6322   // static data members.
6323   const bool PropagatedImport =
6324       !ClassExported &&
6325       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6326 
6327   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6328 
6329   // Ignore explicit dllexport on explicit class template instantiation
6330   // declarations, except in MinGW mode.
6331   if (ClassExported && !ClassAttr->isInherited() &&
6332       TSK == TSK_ExplicitInstantiationDeclaration &&
6333       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6334     Class->dropAttr<DLLExportAttr>();
6335     return;
6336   }
6337 
6338   // Force declaration of implicit members so they can inherit the attribute.
6339   ForceDeclarationOfImplicitMembers(Class);
6340 
6341   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6342   // seem to be true in practice?
6343 
6344   for (Decl *Member : Class->decls()) {
6345     VarDecl *VD = dyn_cast<VarDecl>(Member);
6346     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6347 
6348     // Only methods and static fields inherit the attributes.
6349     if (!VD && !MD)
6350       continue;
6351 
6352     if (MD) {
6353       // Don't process deleted methods.
6354       if (MD->isDeleted())
6355         continue;
6356 
6357       if (MD->isInlined()) {
6358         // MinGW does not import or export inline methods. But do it for
6359         // template instantiations.
6360         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6361             TSK != TSK_ExplicitInstantiationDeclaration &&
6362             TSK != TSK_ExplicitInstantiationDefinition)
6363           continue;
6364 
6365         // MSVC versions before 2015 don't export the move assignment operators
6366         // and move constructor, so don't attempt to import/export them if
6367         // we have a definition.
6368         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6369         if ((MD->isMoveAssignmentOperator() ||
6370              (Ctor && Ctor->isMoveConstructor())) &&
6371             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6372           continue;
6373 
6374         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6375         // operator is exported anyway.
6376         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6377             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6378           continue;
6379       }
6380     }
6381 
6382     // Don't apply dllimport attributes to static data members of class template
6383     // instantiations when the attribute is propagated from a derived class.
6384     if (VD && PropagatedImport)
6385       continue;
6386 
6387     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6388       continue;
6389 
6390     if (!getDLLAttr(Member)) {
6391       InheritableAttr *NewAttr = nullptr;
6392 
6393       // Do not export/import inline function when -fno-dllexport-inlines is
6394       // passed. But add attribute for later local static var check.
6395       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6396           TSK != TSK_ExplicitInstantiationDeclaration &&
6397           TSK != TSK_ExplicitInstantiationDefinition) {
6398         if (ClassExported) {
6399           NewAttr = ::new (getASTContext())
6400               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6401         } else {
6402           NewAttr = ::new (getASTContext())
6403               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6404         }
6405       } else {
6406         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6407       }
6408 
6409       NewAttr->setInherited(true);
6410       Member->addAttr(NewAttr);
6411 
6412       if (MD) {
6413         // Propagate DLLAttr to friend re-declarations of MD that have already
6414         // been constructed.
6415         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6416              FD = FD->getPreviousDecl()) {
6417           if (FD->getFriendObjectKind() == Decl::FOK_None)
6418             continue;
6419           assert(!getDLLAttr(FD) &&
6420                  "friend re-decl should not already have a DLLAttr");
6421           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6422           NewAttr->setInherited(true);
6423           FD->addAttr(NewAttr);
6424         }
6425       }
6426     }
6427   }
6428 
6429   if (ClassExported)
6430     DelayedDllExportClasses.push_back(Class);
6431 }
6432 
6433 /// Perform propagation of DLL attributes from a derived class to a
6434 /// templated base class for MS compatibility.
6435 void Sema::propagateDLLAttrToBaseClassTemplate(
6436     CXXRecordDecl *Class, Attr *ClassAttr,
6437     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6438   if (getDLLAttr(
6439           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6440     // If the base class template has a DLL attribute, don't try to change it.
6441     return;
6442   }
6443 
6444   auto TSK = BaseTemplateSpec->getSpecializationKind();
6445   if (!getDLLAttr(BaseTemplateSpec) &&
6446       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6447        TSK == TSK_ImplicitInstantiation)) {
6448     // The template hasn't been instantiated yet (or it has, but only as an
6449     // explicit instantiation declaration or implicit instantiation, which means
6450     // we haven't codegenned any members yet), so propagate the attribute.
6451     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6452     NewAttr->setInherited(true);
6453     BaseTemplateSpec->addAttr(NewAttr);
6454 
6455     // If this was an import, mark that we propagated it from a derived class to
6456     // a base class template specialization.
6457     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6458       ImportAttr->setPropagatedToBaseTemplate();
6459 
6460     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6461     // needs to be run again to work see the new attribute. Otherwise this will
6462     // get run whenever the template is instantiated.
6463     if (TSK != TSK_Undeclared)
6464       checkClassLevelDLLAttribute(BaseTemplateSpec);
6465 
6466     return;
6467   }
6468 
6469   if (getDLLAttr(BaseTemplateSpec)) {
6470     // The template has already been specialized or instantiated with an
6471     // attribute, explicitly or through propagation. We should not try to change
6472     // it.
6473     return;
6474   }
6475 
6476   // The template was previously instantiated or explicitly specialized without
6477   // a dll attribute, It's too late for us to add an attribute, so warn that
6478   // this is unsupported.
6479   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6480       << BaseTemplateSpec->isExplicitSpecialization();
6481   Diag(ClassAttr->getLocation(), diag::note_attribute);
6482   if (BaseTemplateSpec->isExplicitSpecialization()) {
6483     Diag(BaseTemplateSpec->getLocation(),
6484            diag::note_template_class_explicit_specialization_was_here)
6485         << BaseTemplateSpec;
6486   } else {
6487     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6488            diag::note_template_class_instantiation_was_here)
6489         << BaseTemplateSpec;
6490   }
6491 }
6492 
6493 /// Determine the kind of defaulting that would be done for a given function.
6494 ///
6495 /// If the function is both a default constructor and a copy / move constructor
6496 /// (due to having a default argument for the first parameter), this picks
6497 /// CXXDefaultConstructor.
6498 ///
6499 /// FIXME: Check that case is properly handled by all callers.
6500 Sema::DefaultedFunctionKind
6501 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6502   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6503     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6504       if (Ctor->isDefaultConstructor())
6505         return Sema::CXXDefaultConstructor;
6506 
6507       if (Ctor->isCopyConstructor())
6508         return Sema::CXXCopyConstructor;
6509 
6510       if (Ctor->isMoveConstructor())
6511         return Sema::CXXMoveConstructor;
6512     }
6513 
6514     if (MD->isCopyAssignmentOperator())
6515       return Sema::CXXCopyAssignment;
6516 
6517     if (MD->isMoveAssignmentOperator())
6518       return Sema::CXXMoveAssignment;
6519 
6520     if (isa<CXXDestructorDecl>(FD))
6521       return Sema::CXXDestructor;
6522   }
6523 
6524   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6525   case OO_EqualEqual:
6526     return DefaultedComparisonKind::Equal;
6527 
6528   case OO_ExclaimEqual:
6529     return DefaultedComparisonKind::NotEqual;
6530 
6531   case OO_Spaceship:
6532     // No point allowing this if <=> doesn't exist in the current language mode.
6533     if (!getLangOpts().CPlusPlus20)
6534       break;
6535     return DefaultedComparisonKind::ThreeWay;
6536 
6537   case OO_Less:
6538   case OO_LessEqual:
6539   case OO_Greater:
6540   case OO_GreaterEqual:
6541     // No point allowing this if <=> doesn't exist in the current language mode.
6542     if (!getLangOpts().CPlusPlus20)
6543       break;
6544     return DefaultedComparisonKind::Relational;
6545 
6546   default:
6547     break;
6548   }
6549 
6550   // Not defaultable.
6551   return DefaultedFunctionKind();
6552 }
6553 
6554 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6555                                     SourceLocation DefaultLoc) {
6556   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6557   if (DFK.isComparison())
6558     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6559 
6560   switch (DFK.asSpecialMember()) {
6561   case Sema::CXXDefaultConstructor:
6562     S.DefineImplicitDefaultConstructor(DefaultLoc,
6563                                        cast<CXXConstructorDecl>(FD));
6564     break;
6565   case Sema::CXXCopyConstructor:
6566     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6567     break;
6568   case Sema::CXXCopyAssignment:
6569     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6570     break;
6571   case Sema::CXXDestructor:
6572     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6573     break;
6574   case Sema::CXXMoveConstructor:
6575     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6576     break;
6577   case Sema::CXXMoveAssignment:
6578     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6579     break;
6580   case Sema::CXXInvalid:
6581     llvm_unreachable("Invalid special member.");
6582   }
6583 }
6584 
6585 /// Determine whether a type is permitted to be passed or returned in
6586 /// registers, per C++ [class.temporary]p3.
6587 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6588                                TargetInfo::CallingConvKind CCK) {
6589   if (D->isDependentType() || D->isInvalidDecl())
6590     return false;
6591 
6592   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6593   // The PS4 platform ABI follows the behavior of Clang 3.2.
6594   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6595     return !D->hasNonTrivialDestructorForCall() &&
6596            !D->hasNonTrivialCopyConstructorForCall();
6597 
6598   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6599     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6600     bool DtorIsTrivialForCall = false;
6601 
6602     // If a class has at least one non-deleted, trivial copy constructor, it
6603     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6604     //
6605     // Note: This permits classes with non-trivial copy or move ctors to be
6606     // passed in registers, so long as they *also* have a trivial copy ctor,
6607     // which is non-conforming.
6608     if (D->needsImplicitCopyConstructor()) {
6609       if (!D->defaultedCopyConstructorIsDeleted()) {
6610         if (D->hasTrivialCopyConstructor())
6611           CopyCtorIsTrivial = true;
6612         if (D->hasTrivialCopyConstructorForCall())
6613           CopyCtorIsTrivialForCall = true;
6614       }
6615     } else {
6616       for (const CXXConstructorDecl *CD : D->ctors()) {
6617         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6618           if (CD->isTrivial())
6619             CopyCtorIsTrivial = true;
6620           if (CD->isTrivialForCall())
6621             CopyCtorIsTrivialForCall = true;
6622         }
6623       }
6624     }
6625 
6626     if (D->needsImplicitDestructor()) {
6627       if (!D->defaultedDestructorIsDeleted() &&
6628           D->hasTrivialDestructorForCall())
6629         DtorIsTrivialForCall = true;
6630     } else if (const auto *DD = D->getDestructor()) {
6631       if (!DD->isDeleted() && DD->isTrivialForCall())
6632         DtorIsTrivialForCall = true;
6633     }
6634 
6635     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6636     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6637       return true;
6638 
6639     // If a class has a destructor, we'd really like to pass it indirectly
6640     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6641     // impossible for small types, which it will pass in a single register or
6642     // stack slot. Most objects with dtors are large-ish, so handle that early.
6643     // We can't call out all large objects as being indirect because there are
6644     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6645     // how we pass large POD types.
6646 
6647     // Note: This permits small classes with nontrivial destructors to be
6648     // passed in registers, which is non-conforming.
6649     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6650     uint64_t TypeSize = isAArch64 ? 128 : 64;
6651 
6652     if (CopyCtorIsTrivial &&
6653         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6654       return true;
6655     return false;
6656   }
6657 
6658   // Per C++ [class.temporary]p3, the relevant condition is:
6659   //   each copy constructor, move constructor, and destructor of X is
6660   //   either trivial or deleted, and X has at least one non-deleted copy
6661   //   or move constructor
6662   bool HasNonDeletedCopyOrMove = false;
6663 
6664   if (D->needsImplicitCopyConstructor() &&
6665       !D->defaultedCopyConstructorIsDeleted()) {
6666     if (!D->hasTrivialCopyConstructorForCall())
6667       return false;
6668     HasNonDeletedCopyOrMove = true;
6669   }
6670 
6671   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6672       !D->defaultedMoveConstructorIsDeleted()) {
6673     if (!D->hasTrivialMoveConstructorForCall())
6674       return false;
6675     HasNonDeletedCopyOrMove = true;
6676   }
6677 
6678   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6679       !D->hasTrivialDestructorForCall())
6680     return false;
6681 
6682   for (const CXXMethodDecl *MD : D->methods()) {
6683     if (MD->isDeleted())
6684       continue;
6685 
6686     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6687     if (CD && CD->isCopyOrMoveConstructor())
6688       HasNonDeletedCopyOrMove = true;
6689     else if (!isa<CXXDestructorDecl>(MD))
6690       continue;
6691 
6692     if (!MD->isTrivialForCall())
6693       return false;
6694   }
6695 
6696   return HasNonDeletedCopyOrMove;
6697 }
6698 
6699 /// Report an error regarding overriding, along with any relevant
6700 /// overridden methods.
6701 ///
6702 /// \param DiagID the primary error to report.
6703 /// \param MD the overriding method.
6704 static bool
6705 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6706                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6707   bool IssuedDiagnostic = false;
6708   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6709     if (Report(O)) {
6710       if (!IssuedDiagnostic) {
6711         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6712         IssuedDiagnostic = true;
6713       }
6714       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6715     }
6716   }
6717   return IssuedDiagnostic;
6718 }
6719 
6720 /// Perform semantic checks on a class definition that has been
6721 /// completing, introducing implicitly-declared members, checking for
6722 /// abstract types, etc.
6723 ///
6724 /// \param S The scope in which the class was parsed. Null if we didn't just
6725 ///        parse a class definition.
6726 /// \param Record The completed class.
6727 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6728   if (!Record)
6729     return;
6730 
6731   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6732     AbstractUsageInfo Info(*this, Record);
6733     CheckAbstractClassUsage(Info, Record);
6734   }
6735 
6736   // If this is not an aggregate type and has no user-declared constructor,
6737   // complain about any non-static data members of reference or const scalar
6738   // type, since they will never get initializers.
6739   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6740       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6741       !Record->isLambda()) {
6742     bool Complained = false;
6743     for (const auto *F : Record->fields()) {
6744       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6745         continue;
6746 
6747       if (F->getType()->isReferenceType() ||
6748           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6749         if (!Complained) {
6750           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6751             << Record->getTagKind() << Record;
6752           Complained = true;
6753         }
6754 
6755         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6756           << F->getType()->isReferenceType()
6757           << F->getDeclName();
6758       }
6759     }
6760   }
6761 
6762   if (Record->getIdentifier()) {
6763     // C++ [class.mem]p13:
6764     //   If T is the name of a class, then each of the following shall have a
6765     //   name different from T:
6766     //     - every member of every anonymous union that is a member of class T.
6767     //
6768     // C++ [class.mem]p14:
6769     //   In addition, if class T has a user-declared constructor (12.1), every
6770     //   non-static data member of class T shall have a name different from T.
6771     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6772     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6773          ++I) {
6774       NamedDecl *D = (*I)->getUnderlyingDecl();
6775       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6776            Record->hasUserDeclaredConstructor()) ||
6777           isa<IndirectFieldDecl>(D)) {
6778         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6779           << D->getDeclName();
6780         break;
6781       }
6782     }
6783   }
6784 
6785   // Warn if the class has virtual methods but non-virtual public destructor.
6786   if (Record->isPolymorphic() && !Record->isDependentType()) {
6787     CXXDestructorDecl *dtor = Record->getDestructor();
6788     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6789         !Record->hasAttr<FinalAttr>())
6790       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6791            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6792   }
6793 
6794   if (Record->isAbstract()) {
6795     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6796       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6797         << FA->isSpelledAsSealed();
6798       DiagnoseAbstractType(Record);
6799     }
6800   }
6801 
6802   // Warn if the class has a final destructor but is not itself marked final.
6803   if (!Record->hasAttr<FinalAttr>()) {
6804     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6805       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6806         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6807             << FA->isSpelledAsSealed()
6808             << FixItHint::CreateInsertion(
6809                    getLocForEndOfToken(Record->getLocation()),
6810                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6811         Diag(Record->getLocation(),
6812              diag::note_final_dtor_non_final_class_silence)
6813             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6814       }
6815     }
6816   }
6817 
6818   // See if trivial_abi has to be dropped.
6819   if (Record->hasAttr<TrivialABIAttr>())
6820     checkIllFormedTrivialABIStruct(*Record);
6821 
6822   // Set HasTrivialSpecialMemberForCall if the record has attribute
6823   // "trivial_abi".
6824   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6825 
6826   if (HasTrivialABI)
6827     Record->setHasTrivialSpecialMemberForCall();
6828 
6829   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6830   // We check these last because they can depend on the properties of the
6831   // primary comparison functions (==, <=>).
6832   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6833 
6834   // Perform checks that can't be done until we know all the properties of a
6835   // member function (whether it's defaulted, deleted, virtual, overriding,
6836   // ...).
6837   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6838     // A static function cannot override anything.
6839     if (MD->getStorageClass() == SC_Static) {
6840       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6841                           [](const CXXMethodDecl *) { return true; }))
6842         return;
6843     }
6844 
6845     // A deleted function cannot override a non-deleted function and vice
6846     // versa.
6847     if (ReportOverrides(*this,
6848                         MD->isDeleted() ? diag::err_deleted_override
6849                                         : diag::err_non_deleted_override,
6850                         MD, [&](const CXXMethodDecl *V) {
6851                           return MD->isDeleted() != V->isDeleted();
6852                         })) {
6853       if (MD->isDefaulted() && MD->isDeleted())
6854         // Explain why this defaulted function was deleted.
6855         DiagnoseDeletedDefaultedFunction(MD);
6856       return;
6857     }
6858 
6859     // A consteval function cannot override a non-consteval function and vice
6860     // versa.
6861     if (ReportOverrides(*this,
6862                         MD->isConsteval() ? diag::err_consteval_override
6863                                           : diag::err_non_consteval_override,
6864                         MD, [&](const CXXMethodDecl *V) {
6865                           return MD->isConsteval() != V->isConsteval();
6866                         })) {
6867       if (MD->isDefaulted() && MD->isDeleted())
6868         // Explain why this defaulted function was deleted.
6869         DiagnoseDeletedDefaultedFunction(MD);
6870       return;
6871     }
6872   };
6873 
6874   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6875     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6876       return false;
6877 
6878     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6879     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6880         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6881       DefaultedSecondaryComparisons.push_back(FD);
6882       return true;
6883     }
6884 
6885     CheckExplicitlyDefaultedFunction(S, FD);
6886     return false;
6887   };
6888 
6889   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6890     // Check whether the explicitly-defaulted members are valid.
6891     bool Incomplete = CheckForDefaultedFunction(M);
6892 
6893     // Skip the rest of the checks for a member of a dependent class.
6894     if (Record->isDependentType())
6895       return;
6896 
6897     // For an explicitly defaulted or deleted special member, we defer
6898     // determining triviality until the class is complete. That time is now!
6899     CXXSpecialMember CSM = getSpecialMember(M);
6900     if (!M->isImplicit() && !M->isUserProvided()) {
6901       if (CSM != CXXInvalid) {
6902         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6903         // Inform the class that we've finished declaring this member.
6904         Record->finishedDefaultedOrDeletedMember(M);
6905         M->setTrivialForCall(
6906             HasTrivialABI ||
6907             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6908         Record->setTrivialForCallFlags(M);
6909       }
6910     }
6911 
6912     // Set triviality for the purpose of calls if this is a user-provided
6913     // copy/move constructor or destructor.
6914     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6915          CSM == CXXDestructor) && M->isUserProvided()) {
6916       M->setTrivialForCall(HasTrivialABI);
6917       Record->setTrivialForCallFlags(M);
6918     }
6919 
6920     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6921         M->hasAttr<DLLExportAttr>()) {
6922       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6923           M->isTrivial() &&
6924           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6925            CSM == CXXDestructor))
6926         M->dropAttr<DLLExportAttr>();
6927 
6928       if (M->hasAttr<DLLExportAttr>()) {
6929         // Define after any fields with in-class initializers have been parsed.
6930         DelayedDllExportMemberFunctions.push_back(M);
6931       }
6932     }
6933 
6934     // Define defaulted constexpr virtual functions that override a base class
6935     // function right away.
6936     // FIXME: We can defer doing this until the vtable is marked as used.
6937     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6938       DefineDefaultedFunction(*this, M, M->getLocation());
6939 
6940     if (!Incomplete)
6941       CheckCompletedMemberFunction(M);
6942   };
6943 
6944   // Check the destructor before any other member function. We need to
6945   // determine whether it's trivial in order to determine whether the claas
6946   // type is a literal type, which is a prerequisite for determining whether
6947   // other special member functions are valid and whether they're implicitly
6948   // 'constexpr'.
6949   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6950     CompleteMemberFunction(Dtor);
6951 
6952   bool HasMethodWithOverrideControl = false,
6953        HasOverridingMethodWithoutOverrideControl = false;
6954   for (auto *D : Record->decls()) {
6955     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6956       // FIXME: We could do this check for dependent types with non-dependent
6957       // bases.
6958       if (!Record->isDependentType()) {
6959         // See if a method overloads virtual methods in a base
6960         // class without overriding any.
6961         if (!M->isStatic())
6962           DiagnoseHiddenVirtualMethods(M);
6963         if (M->hasAttr<OverrideAttr>())
6964           HasMethodWithOverrideControl = true;
6965         else if (M->size_overridden_methods() > 0)
6966           HasOverridingMethodWithoutOverrideControl = true;
6967       }
6968 
6969       if (!isa<CXXDestructorDecl>(M))
6970         CompleteMemberFunction(M);
6971     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6972       CheckForDefaultedFunction(
6973           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6974     }
6975   }
6976 
6977   if (HasOverridingMethodWithoutOverrideControl) {
6978     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6979     for (auto *M : Record->methods())
6980       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6981   }
6982 
6983   // Check the defaulted secondary comparisons after any other member functions.
6984   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6985     CheckExplicitlyDefaultedFunction(S, FD);
6986 
6987     // If this is a member function, we deferred checking it until now.
6988     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6989       CheckCompletedMemberFunction(MD);
6990   }
6991 
6992   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6993   // whether this class uses any C++ features that are implemented
6994   // completely differently in MSVC, and if so, emit a diagnostic.
6995   // That diagnostic defaults to an error, but we allow projects to
6996   // map it down to a warning (or ignore it).  It's a fairly common
6997   // practice among users of the ms_struct pragma to mass-annotate
6998   // headers, sweeping up a bunch of types that the project doesn't
6999   // really rely on MSVC-compatible layout for.  We must therefore
7000   // support "ms_struct except for C++ stuff" as a secondary ABI.
7001   // Don't emit this diagnostic if the feature was enabled as a
7002   // language option (as opposed to via a pragma or attribute), as
7003   // the option -mms-bitfields otherwise essentially makes it impossible
7004   // to build C++ code, unless this diagnostic is turned off.
7005   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7006       (Record->isPolymorphic() || Record->getNumBases())) {
7007     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7008   }
7009 
7010   checkClassLevelDLLAttribute(Record);
7011   checkClassLevelCodeSegAttribute(Record);
7012 
7013   bool ClangABICompat4 =
7014       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7015   TargetInfo::CallingConvKind CCK =
7016       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7017   bool CanPass = canPassInRegisters(*this, Record, CCK);
7018 
7019   // Do not change ArgPassingRestrictions if it has already been set to
7020   // APK_CanNeverPassInRegs.
7021   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
7022     Record->setArgPassingRestrictions(CanPass
7023                                           ? RecordDecl::APK_CanPassInRegs
7024                                           : RecordDecl::APK_CannotPassInRegs);
7025 
7026   // If canPassInRegisters returns true despite the record having a non-trivial
7027   // destructor, the record is destructed in the callee. This happens only when
7028   // the record or one of its subobjects has a field annotated with trivial_abi
7029   // or a field qualified with ObjC __strong/__weak.
7030   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7031     Record->setParamDestroyedInCallee(true);
7032   else if (Record->hasNonTrivialDestructor())
7033     Record->setParamDestroyedInCallee(CanPass);
7034 
7035   if (getLangOpts().ForceEmitVTables) {
7036     // If we want to emit all the vtables, we need to mark it as used.  This
7037     // is especially required for cases like vtable assumption loads.
7038     MarkVTableUsed(Record->getInnerLocStart(), Record);
7039   }
7040 
7041   if (getLangOpts().CUDA) {
7042     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7043       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7044     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7045       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7046   }
7047 }
7048 
7049 /// Look up the special member function that would be called by a special
7050 /// member function for a subobject of class type.
7051 ///
7052 /// \param Class The class type of the subobject.
7053 /// \param CSM The kind of special member function.
7054 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7055 /// \param ConstRHS True if this is a copy operation with a const object
7056 ///        on its RHS, that is, if the argument to the outer special member
7057 ///        function is 'const' and this is not a field marked 'mutable'.
7058 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7059     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7060     unsigned FieldQuals, bool ConstRHS) {
7061   unsigned LHSQuals = 0;
7062   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7063     LHSQuals = FieldQuals;
7064 
7065   unsigned RHSQuals = FieldQuals;
7066   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7067     RHSQuals = 0;
7068   else if (ConstRHS)
7069     RHSQuals |= Qualifiers::Const;
7070 
7071   return S.LookupSpecialMember(Class, CSM,
7072                                RHSQuals & Qualifiers::Const,
7073                                RHSQuals & Qualifiers::Volatile,
7074                                false,
7075                                LHSQuals & Qualifiers::Const,
7076                                LHSQuals & Qualifiers::Volatile);
7077 }
7078 
7079 class Sema::InheritedConstructorInfo {
7080   Sema &S;
7081   SourceLocation UseLoc;
7082 
7083   /// A mapping from the base classes through which the constructor was
7084   /// inherited to the using shadow declaration in that base class (or a null
7085   /// pointer if the constructor was declared in that base class).
7086   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7087       InheritedFromBases;
7088 
7089 public:
7090   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7091                            ConstructorUsingShadowDecl *Shadow)
7092       : S(S), UseLoc(UseLoc) {
7093     bool DiagnosedMultipleConstructedBases = false;
7094     CXXRecordDecl *ConstructedBase = nullptr;
7095     BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7096 
7097     // Find the set of such base class subobjects and check that there's a
7098     // unique constructed subobject.
7099     for (auto *D : Shadow->redecls()) {
7100       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7101       auto *DNominatedBase = DShadow->getNominatedBaseClass();
7102       auto *DConstructedBase = DShadow->getConstructedBaseClass();
7103 
7104       InheritedFromBases.insert(
7105           std::make_pair(DNominatedBase->getCanonicalDecl(),
7106                          DShadow->getNominatedBaseClassShadowDecl()));
7107       if (DShadow->constructsVirtualBase())
7108         InheritedFromBases.insert(
7109             std::make_pair(DConstructedBase->getCanonicalDecl(),
7110                            DShadow->getConstructedBaseClassShadowDecl()));
7111       else
7112         assert(DNominatedBase == DConstructedBase);
7113 
7114       // [class.inhctor.init]p2:
7115       //   If the constructor was inherited from multiple base class subobjects
7116       //   of type B, the program is ill-formed.
7117       if (!ConstructedBase) {
7118         ConstructedBase = DConstructedBase;
7119         ConstructedBaseIntroducer = D->getIntroducer();
7120       } else if (ConstructedBase != DConstructedBase &&
7121                  !Shadow->isInvalidDecl()) {
7122         if (!DiagnosedMultipleConstructedBases) {
7123           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7124               << Shadow->getTargetDecl();
7125           S.Diag(ConstructedBaseIntroducer->getLocation(),
7126                  diag::note_ambiguous_inherited_constructor_using)
7127               << ConstructedBase;
7128           DiagnosedMultipleConstructedBases = true;
7129         }
7130         S.Diag(D->getIntroducer()->getLocation(),
7131                diag::note_ambiguous_inherited_constructor_using)
7132             << DConstructedBase;
7133       }
7134     }
7135 
7136     if (DiagnosedMultipleConstructedBases)
7137       Shadow->setInvalidDecl();
7138   }
7139 
7140   /// Find the constructor to use for inherited construction of a base class,
7141   /// and whether that base class constructor inherits the constructor from a
7142   /// virtual base class (in which case it won't actually invoke it).
7143   std::pair<CXXConstructorDecl *, bool>
7144   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7145     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7146     if (It == InheritedFromBases.end())
7147       return std::make_pair(nullptr, false);
7148 
7149     // This is an intermediary class.
7150     if (It->second)
7151       return std::make_pair(
7152           S.findInheritingConstructor(UseLoc, Ctor, It->second),
7153           It->second->constructsVirtualBase());
7154 
7155     // This is the base class from which the constructor was inherited.
7156     return std::make_pair(Ctor, false);
7157   }
7158 };
7159 
7160 /// Is the special member function which would be selected to perform the
7161 /// specified operation on the specified class type a constexpr constructor?
7162 static bool
7163 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7164                          Sema::CXXSpecialMember CSM, unsigned Quals,
7165                          bool ConstRHS,
7166                          CXXConstructorDecl *InheritedCtor = nullptr,
7167                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7168   // If we're inheriting a constructor, see if we need to call it for this base
7169   // class.
7170   if (InheritedCtor) {
7171     assert(CSM == Sema::CXXDefaultConstructor);
7172     auto BaseCtor =
7173         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7174     if (BaseCtor)
7175       return BaseCtor->isConstexpr();
7176   }
7177 
7178   if (CSM == Sema::CXXDefaultConstructor)
7179     return ClassDecl->hasConstexprDefaultConstructor();
7180   if (CSM == Sema::CXXDestructor)
7181     return ClassDecl->hasConstexprDestructor();
7182 
7183   Sema::SpecialMemberOverloadResult SMOR =
7184       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7185   if (!SMOR.getMethod())
7186     // A constructor we wouldn't select can't be "involved in initializing"
7187     // anything.
7188     return true;
7189   return SMOR.getMethod()->isConstexpr();
7190 }
7191 
7192 /// Determine whether the specified special member function would be constexpr
7193 /// if it were implicitly defined.
7194 static bool defaultedSpecialMemberIsConstexpr(
7195     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7196     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7197     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7198   if (!S.getLangOpts().CPlusPlus11)
7199     return false;
7200 
7201   // C++11 [dcl.constexpr]p4:
7202   // In the definition of a constexpr constructor [...]
7203   bool Ctor = true;
7204   switch (CSM) {
7205   case Sema::CXXDefaultConstructor:
7206     if (Inherited)
7207       break;
7208     // Since default constructor lookup is essentially trivial (and cannot
7209     // involve, for instance, template instantiation), we compute whether a
7210     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7211     //
7212     // This is important for performance; we need to know whether the default
7213     // constructor is constexpr to determine whether the type is a literal type.
7214     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7215 
7216   case Sema::CXXCopyConstructor:
7217   case Sema::CXXMoveConstructor:
7218     // For copy or move constructors, we need to perform overload resolution.
7219     break;
7220 
7221   case Sema::CXXCopyAssignment:
7222   case Sema::CXXMoveAssignment:
7223     if (!S.getLangOpts().CPlusPlus14)
7224       return false;
7225     // In C++1y, we need to perform overload resolution.
7226     Ctor = false;
7227     break;
7228 
7229   case Sema::CXXDestructor:
7230     return ClassDecl->defaultedDestructorIsConstexpr();
7231 
7232   case Sema::CXXInvalid:
7233     return false;
7234   }
7235 
7236   //   -- if the class is a non-empty union, or for each non-empty anonymous
7237   //      union member of a non-union class, exactly one non-static data member
7238   //      shall be initialized; [DR1359]
7239   //
7240   // If we squint, this is guaranteed, since exactly one non-static data member
7241   // will be initialized (if the constructor isn't deleted), we just don't know
7242   // which one.
7243   if (Ctor && ClassDecl->isUnion())
7244     return CSM == Sema::CXXDefaultConstructor
7245                ? ClassDecl->hasInClassInitializer() ||
7246                      !ClassDecl->hasVariantMembers()
7247                : true;
7248 
7249   //   -- the class shall not have any virtual base classes;
7250   if (Ctor && ClassDecl->getNumVBases())
7251     return false;
7252 
7253   // C++1y [class.copy]p26:
7254   //   -- [the class] is a literal type, and
7255   if (!Ctor && !ClassDecl->isLiteral())
7256     return false;
7257 
7258   //   -- every constructor involved in initializing [...] base class
7259   //      sub-objects shall be a constexpr constructor;
7260   //   -- the assignment operator selected to copy/move each direct base
7261   //      class is a constexpr function, and
7262   for (const auto &B : ClassDecl->bases()) {
7263     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7264     if (!BaseType) continue;
7265 
7266     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7267     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7268                                   InheritedCtor, Inherited))
7269       return false;
7270   }
7271 
7272   //   -- every constructor involved in initializing non-static data members
7273   //      [...] shall be a constexpr constructor;
7274   //   -- every non-static data member and base class sub-object shall be
7275   //      initialized
7276   //   -- for each non-static data member of X that is of class type (or array
7277   //      thereof), the assignment operator selected to copy/move that member is
7278   //      a constexpr function
7279   for (const auto *F : ClassDecl->fields()) {
7280     if (F->isInvalidDecl())
7281       continue;
7282     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7283       continue;
7284     QualType BaseType = S.Context.getBaseElementType(F->getType());
7285     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7286       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7287       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7288                                     BaseType.getCVRQualifiers(),
7289                                     ConstArg && !F->isMutable()))
7290         return false;
7291     } else if (CSM == Sema::CXXDefaultConstructor) {
7292       return false;
7293     }
7294   }
7295 
7296   // All OK, it's constexpr!
7297   return true;
7298 }
7299 
7300 namespace {
7301 /// RAII object to register a defaulted function as having its exception
7302 /// specification computed.
7303 struct ComputingExceptionSpec {
7304   Sema &S;
7305 
7306   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7307       : S(S) {
7308     Sema::CodeSynthesisContext Ctx;
7309     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7310     Ctx.PointOfInstantiation = Loc;
7311     Ctx.Entity = FD;
7312     S.pushCodeSynthesisContext(Ctx);
7313   }
7314   ~ComputingExceptionSpec() {
7315     S.popCodeSynthesisContext();
7316   }
7317 };
7318 }
7319 
7320 static Sema::ImplicitExceptionSpecification
7321 ComputeDefaultedSpecialMemberExceptionSpec(
7322     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7323     Sema::InheritedConstructorInfo *ICI);
7324 
7325 static Sema::ImplicitExceptionSpecification
7326 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7327                                         FunctionDecl *FD,
7328                                         Sema::DefaultedComparisonKind DCK);
7329 
7330 static Sema::ImplicitExceptionSpecification
7331 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7332   auto DFK = S.getDefaultedFunctionKind(FD);
7333   if (DFK.isSpecialMember())
7334     return ComputeDefaultedSpecialMemberExceptionSpec(
7335         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7336   if (DFK.isComparison())
7337     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7338                                                    DFK.asComparison());
7339 
7340   auto *CD = cast<CXXConstructorDecl>(FD);
7341   assert(CD->getInheritedConstructor() &&
7342          "only defaulted functions and inherited constructors have implicit "
7343          "exception specs");
7344   Sema::InheritedConstructorInfo ICI(
7345       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7346   return ComputeDefaultedSpecialMemberExceptionSpec(
7347       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7348 }
7349 
7350 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7351                                                             CXXMethodDecl *MD) {
7352   FunctionProtoType::ExtProtoInfo EPI;
7353 
7354   // Build an exception specification pointing back at this member.
7355   EPI.ExceptionSpec.Type = EST_Unevaluated;
7356   EPI.ExceptionSpec.SourceDecl = MD;
7357 
7358   // Set the calling convention to the default for C++ instance methods.
7359   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7360       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7361                                             /*IsCXXMethod=*/true));
7362   return EPI;
7363 }
7364 
7365 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7366   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7367   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7368     return;
7369 
7370   // Evaluate the exception specification.
7371   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7372   auto ESI = IES.getExceptionSpec();
7373 
7374   // Update the type of the special member to use it.
7375   UpdateExceptionSpec(FD, ESI);
7376 }
7377 
7378 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7379   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7380 
7381   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7382   if (!DefKind) {
7383     assert(FD->getDeclContext()->isDependentContext());
7384     return;
7385   }
7386 
7387   if (DefKind.isComparison())
7388     UnusedPrivateFields.clear();
7389 
7390   if (DefKind.isSpecialMember()
7391           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7392                                                   DefKind.asSpecialMember())
7393           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7394     FD->setInvalidDecl();
7395 }
7396 
7397 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7398                                                  CXXSpecialMember CSM) {
7399   CXXRecordDecl *RD = MD->getParent();
7400 
7401   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7402          "not an explicitly-defaulted special member");
7403 
7404   // Defer all checking for special members of a dependent type.
7405   if (RD->isDependentType())
7406     return false;
7407 
7408   // Whether this was the first-declared instance of the constructor.
7409   // This affects whether we implicitly add an exception spec and constexpr.
7410   bool First = MD == MD->getCanonicalDecl();
7411 
7412   bool HadError = false;
7413 
7414   // C++11 [dcl.fct.def.default]p1:
7415   //   A function that is explicitly defaulted shall
7416   //     -- be a special member function [...] (checked elsewhere),
7417   //     -- have the same type (except for ref-qualifiers, and except that a
7418   //        copy operation can take a non-const reference) as an implicit
7419   //        declaration, and
7420   //     -- not have default arguments.
7421   // C++2a changes the second bullet to instead delete the function if it's
7422   // defaulted on its first declaration, unless it's "an assignment operator,
7423   // and its return type differs or its parameter type is not a reference".
7424   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7425   bool ShouldDeleteForTypeMismatch = false;
7426   unsigned ExpectedParams = 1;
7427   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7428     ExpectedParams = 0;
7429   if (MD->getNumParams() != ExpectedParams) {
7430     // This checks for default arguments: a copy or move constructor with a
7431     // default argument is classified as a default constructor, and assignment
7432     // operations and destructors can't have default arguments.
7433     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7434       << CSM << MD->getSourceRange();
7435     HadError = true;
7436   } else if (MD->isVariadic()) {
7437     if (DeleteOnTypeMismatch)
7438       ShouldDeleteForTypeMismatch = true;
7439     else {
7440       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7441         << CSM << MD->getSourceRange();
7442       HadError = true;
7443     }
7444   }
7445 
7446   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7447 
7448   bool CanHaveConstParam = false;
7449   if (CSM == CXXCopyConstructor)
7450     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7451   else if (CSM == CXXCopyAssignment)
7452     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7453 
7454   QualType ReturnType = Context.VoidTy;
7455   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7456     // Check for return type matching.
7457     ReturnType = Type->getReturnType();
7458 
7459     QualType DeclType = Context.getTypeDeclType(RD);
7460     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7461     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7462 
7463     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7464       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7465         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7466       HadError = true;
7467     }
7468 
7469     // A defaulted special member cannot have cv-qualifiers.
7470     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7471       if (DeleteOnTypeMismatch)
7472         ShouldDeleteForTypeMismatch = true;
7473       else {
7474         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7475           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7476         HadError = true;
7477       }
7478     }
7479   }
7480 
7481   // Check for parameter type matching.
7482   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7483   bool HasConstParam = false;
7484   if (ExpectedParams && ArgType->isReferenceType()) {
7485     // Argument must be reference to possibly-const T.
7486     QualType ReferentType = ArgType->getPointeeType();
7487     HasConstParam = ReferentType.isConstQualified();
7488 
7489     if (ReferentType.isVolatileQualified()) {
7490       if (DeleteOnTypeMismatch)
7491         ShouldDeleteForTypeMismatch = true;
7492       else {
7493         Diag(MD->getLocation(),
7494              diag::err_defaulted_special_member_volatile_param) << CSM;
7495         HadError = true;
7496       }
7497     }
7498 
7499     if (HasConstParam && !CanHaveConstParam) {
7500       if (DeleteOnTypeMismatch)
7501         ShouldDeleteForTypeMismatch = true;
7502       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7503         Diag(MD->getLocation(),
7504              diag::err_defaulted_special_member_copy_const_param)
7505           << (CSM == CXXCopyAssignment);
7506         // FIXME: Explain why this special member can't be const.
7507         HadError = true;
7508       } else {
7509         Diag(MD->getLocation(),
7510              diag::err_defaulted_special_member_move_const_param)
7511           << (CSM == CXXMoveAssignment);
7512         HadError = true;
7513       }
7514     }
7515   } else if (ExpectedParams) {
7516     // A copy assignment operator can take its argument by value, but a
7517     // defaulted one cannot.
7518     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7519     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7520     HadError = true;
7521   }
7522 
7523   // C++11 [dcl.fct.def.default]p2:
7524   //   An explicitly-defaulted function may be declared constexpr only if it
7525   //   would have been implicitly declared as constexpr,
7526   // Do not apply this rule to members of class templates, since core issue 1358
7527   // makes such functions always instantiate to constexpr functions. For
7528   // functions which cannot be constexpr (for non-constructors in C++11 and for
7529   // destructors in C++14 and C++17), this is checked elsewhere.
7530   //
7531   // FIXME: This should not apply if the member is deleted.
7532   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7533                                                      HasConstParam);
7534   if ((getLangOpts().CPlusPlus20 ||
7535        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7536                                   : isa<CXXConstructorDecl>(MD))) &&
7537       MD->isConstexpr() && !Constexpr &&
7538       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7539     Diag(MD->getBeginLoc(), MD->isConsteval()
7540                                 ? diag::err_incorrect_defaulted_consteval
7541                                 : diag::err_incorrect_defaulted_constexpr)
7542         << CSM;
7543     // FIXME: Explain why the special member can't be constexpr.
7544     HadError = true;
7545   }
7546 
7547   if (First) {
7548     // C++2a [dcl.fct.def.default]p3:
7549     //   If a function is explicitly defaulted on its first declaration, it is
7550     //   implicitly considered to be constexpr if the implicit declaration
7551     //   would be.
7552     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7553                                           ? ConstexprSpecKind::Consteval
7554                                           : ConstexprSpecKind::Constexpr)
7555                                    : ConstexprSpecKind::Unspecified);
7556 
7557     if (!Type->hasExceptionSpec()) {
7558       // C++2a [except.spec]p3:
7559       //   If a declaration of a function does not have a noexcept-specifier
7560       //   [and] is defaulted on its first declaration, [...] the exception
7561       //   specification is as specified below
7562       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7563       EPI.ExceptionSpec.Type = EST_Unevaluated;
7564       EPI.ExceptionSpec.SourceDecl = MD;
7565       MD->setType(Context.getFunctionType(ReturnType,
7566                                           llvm::makeArrayRef(&ArgType,
7567                                                              ExpectedParams),
7568                                           EPI));
7569     }
7570   }
7571 
7572   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7573     if (First) {
7574       SetDeclDeleted(MD, MD->getLocation());
7575       if (!inTemplateInstantiation() && !HadError) {
7576         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7577         if (ShouldDeleteForTypeMismatch) {
7578           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7579         } else {
7580           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7581         }
7582       }
7583       if (ShouldDeleteForTypeMismatch && !HadError) {
7584         Diag(MD->getLocation(),
7585              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7586       }
7587     } else {
7588       // C++11 [dcl.fct.def.default]p4:
7589       //   [For a] user-provided explicitly-defaulted function [...] if such a
7590       //   function is implicitly defined as deleted, the program is ill-formed.
7591       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7592       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7593       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7594       HadError = true;
7595     }
7596   }
7597 
7598   return HadError;
7599 }
7600 
7601 namespace {
7602 /// Helper class for building and checking a defaulted comparison.
7603 ///
7604 /// Defaulted functions are built in two phases:
7605 ///
7606 ///  * First, the set of operations that the function will perform are
7607 ///    identified, and some of them are checked. If any of the checked
7608 ///    operations is invalid in certain ways, the comparison function is
7609 ///    defined as deleted and no body is built.
7610 ///  * Then, if the function is not defined as deleted, the body is built.
7611 ///
7612 /// This is accomplished by performing two visitation steps over the eventual
7613 /// body of the function.
7614 template<typename Derived, typename ResultList, typename Result,
7615          typename Subobject>
7616 class DefaultedComparisonVisitor {
7617 public:
7618   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7619 
7620   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7621                              DefaultedComparisonKind DCK)
7622       : S(S), RD(RD), FD(FD), DCK(DCK) {
7623     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7624       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7625       // UnresolvedSet to avoid this copy.
7626       Fns.assign(Info->getUnqualifiedLookups().begin(),
7627                  Info->getUnqualifiedLookups().end());
7628     }
7629   }
7630 
7631   ResultList visit() {
7632     // The type of an lvalue naming a parameter of this function.
7633     QualType ParamLvalType =
7634         FD->getParamDecl(0)->getType().getNonReferenceType();
7635 
7636     ResultList Results;
7637 
7638     switch (DCK) {
7639     case DefaultedComparisonKind::None:
7640       llvm_unreachable("not a defaulted comparison");
7641 
7642     case DefaultedComparisonKind::Equal:
7643     case DefaultedComparisonKind::ThreeWay:
7644       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7645       return Results;
7646 
7647     case DefaultedComparisonKind::NotEqual:
7648     case DefaultedComparisonKind::Relational:
7649       Results.add(getDerived().visitExpandedSubobject(
7650           ParamLvalType, getDerived().getCompleteObject()));
7651       return Results;
7652     }
7653     llvm_unreachable("");
7654   }
7655 
7656 protected:
7657   Derived &getDerived() { return static_cast<Derived&>(*this); }
7658 
7659   /// Visit the expanded list of subobjects of the given type, as specified in
7660   /// C++2a [class.compare.default].
7661   ///
7662   /// \return \c true if the ResultList object said we're done, \c false if not.
7663   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7664                        Qualifiers Quals) {
7665     // C++2a [class.compare.default]p4:
7666     //   The direct base class subobjects of C
7667     for (CXXBaseSpecifier &Base : Record->bases())
7668       if (Results.add(getDerived().visitSubobject(
7669               S.Context.getQualifiedType(Base.getType(), Quals),
7670               getDerived().getBase(&Base))))
7671         return true;
7672 
7673     //   followed by the non-static data members of C
7674     for (FieldDecl *Field : Record->fields()) {
7675       // Recursively expand anonymous structs.
7676       if (Field->isAnonymousStructOrUnion()) {
7677         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7678                             Quals))
7679           return true;
7680         continue;
7681       }
7682 
7683       // Figure out the type of an lvalue denoting this field.
7684       Qualifiers FieldQuals = Quals;
7685       if (Field->isMutable())
7686         FieldQuals.removeConst();
7687       QualType FieldType =
7688           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7689 
7690       if (Results.add(getDerived().visitSubobject(
7691               FieldType, getDerived().getField(Field))))
7692         return true;
7693     }
7694 
7695     //   form a list of subobjects.
7696     return false;
7697   }
7698 
7699   Result visitSubobject(QualType Type, Subobject Subobj) {
7700     //   In that list, any subobject of array type is recursively expanded
7701     const ArrayType *AT = S.Context.getAsArrayType(Type);
7702     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7703       return getDerived().visitSubobjectArray(CAT->getElementType(),
7704                                               CAT->getSize(), Subobj);
7705     return getDerived().visitExpandedSubobject(Type, Subobj);
7706   }
7707 
7708   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7709                              Subobject Subobj) {
7710     return getDerived().visitSubobject(Type, Subobj);
7711   }
7712 
7713 protected:
7714   Sema &S;
7715   CXXRecordDecl *RD;
7716   FunctionDecl *FD;
7717   DefaultedComparisonKind DCK;
7718   UnresolvedSet<16> Fns;
7719 };
7720 
7721 /// Information about a defaulted comparison, as determined by
7722 /// DefaultedComparisonAnalyzer.
7723 struct DefaultedComparisonInfo {
7724   bool Deleted = false;
7725   bool Constexpr = true;
7726   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7727 
7728   static DefaultedComparisonInfo deleted() {
7729     DefaultedComparisonInfo Deleted;
7730     Deleted.Deleted = true;
7731     return Deleted;
7732   }
7733 
7734   bool add(const DefaultedComparisonInfo &R) {
7735     Deleted |= R.Deleted;
7736     Constexpr &= R.Constexpr;
7737     Category = commonComparisonType(Category, R.Category);
7738     return Deleted;
7739   }
7740 };
7741 
7742 /// An element in the expanded list of subobjects of a defaulted comparison, as
7743 /// specified in C++2a [class.compare.default]p4.
7744 struct DefaultedComparisonSubobject {
7745   enum { CompleteObject, Member, Base } Kind;
7746   NamedDecl *Decl;
7747   SourceLocation Loc;
7748 };
7749 
7750 /// A visitor over the notional body of a defaulted comparison that determines
7751 /// whether that body would be deleted or constexpr.
7752 class DefaultedComparisonAnalyzer
7753     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7754                                         DefaultedComparisonInfo,
7755                                         DefaultedComparisonInfo,
7756                                         DefaultedComparisonSubobject> {
7757 public:
7758   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7759 
7760 private:
7761   DiagnosticKind Diagnose;
7762 
7763 public:
7764   using Base = DefaultedComparisonVisitor;
7765   using Result = DefaultedComparisonInfo;
7766   using Subobject = DefaultedComparisonSubobject;
7767 
7768   friend Base;
7769 
7770   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7771                               DefaultedComparisonKind DCK,
7772                               DiagnosticKind Diagnose = NoDiagnostics)
7773       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7774 
7775   Result visit() {
7776     if ((DCK == DefaultedComparisonKind::Equal ||
7777          DCK == DefaultedComparisonKind::ThreeWay) &&
7778         RD->hasVariantMembers()) {
7779       // C++2a [class.compare.default]p2 [P2002R0]:
7780       //   A defaulted comparison operator function for class C is defined as
7781       //   deleted if [...] C has variant members.
7782       if (Diagnose == ExplainDeleted) {
7783         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7784           << FD << RD->isUnion() << RD;
7785       }
7786       return Result::deleted();
7787     }
7788 
7789     return Base::visit();
7790   }
7791 
7792 private:
7793   Subobject getCompleteObject() {
7794     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7795   }
7796 
7797   Subobject getBase(CXXBaseSpecifier *Base) {
7798     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7799                      Base->getBaseTypeLoc()};
7800   }
7801 
7802   Subobject getField(FieldDecl *Field) {
7803     return Subobject{Subobject::Member, Field, Field->getLocation()};
7804   }
7805 
7806   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7807     // C++2a [class.compare.default]p2 [P2002R0]:
7808     //   A defaulted <=> or == operator function for class C is defined as
7809     //   deleted if any non-static data member of C is of reference type
7810     if (Type->isReferenceType()) {
7811       if (Diagnose == ExplainDeleted) {
7812         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7813             << FD << RD;
7814       }
7815       return Result::deleted();
7816     }
7817 
7818     // [...] Let xi be an lvalue denoting the ith element [...]
7819     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7820     Expr *Args[] = {&Xi, &Xi};
7821 
7822     // All operators start by trying to apply that same operator recursively.
7823     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7824     assert(OO != OO_None && "not an overloaded operator!");
7825     return visitBinaryOperator(OO, Args, Subobj);
7826   }
7827 
7828   Result
7829   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7830                       Subobject Subobj,
7831                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7832     // Note that there is no need to consider rewritten candidates here if
7833     // we've already found there is no viable 'operator<=>' candidate (and are
7834     // considering synthesizing a '<=>' from '==' and '<').
7835     OverloadCandidateSet CandidateSet(
7836         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7837         OverloadCandidateSet::OperatorRewriteInfo(
7838             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7839 
7840     /// C++2a [class.compare.default]p1 [P2002R0]:
7841     ///   [...] the defaulted function itself is never a candidate for overload
7842     ///   resolution [...]
7843     CandidateSet.exclude(FD);
7844 
7845     if (Args[0]->getType()->isOverloadableType())
7846       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7847     else
7848       // FIXME: We determine whether this is a valid expression by checking to
7849       // see if there's a viable builtin operator candidate for it. That isn't
7850       // really what the rules ask us to do, but should give the right results.
7851       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7852 
7853     Result R;
7854 
7855     OverloadCandidateSet::iterator Best;
7856     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7857     case OR_Success: {
7858       // C++2a [class.compare.secondary]p2 [P2002R0]:
7859       //   The operator function [...] is defined as deleted if [...] the
7860       //   candidate selected by overload resolution is not a rewritten
7861       //   candidate.
7862       if ((DCK == DefaultedComparisonKind::NotEqual ||
7863            DCK == DefaultedComparisonKind::Relational) &&
7864           !Best->RewriteKind) {
7865         if (Diagnose == ExplainDeleted) {
7866           if (Best->Function) {
7867             S.Diag(Best->Function->getLocation(),
7868                    diag::note_defaulted_comparison_not_rewritten_callee)
7869                 << FD;
7870           } else {
7871             assert(Best->Conversions.size() == 2 &&
7872                    Best->Conversions[0].isUserDefined() &&
7873                    "non-user-defined conversion from class to built-in "
7874                    "comparison");
7875             S.Diag(Best->Conversions[0]
7876                        .UserDefined.FoundConversionFunction.getDecl()
7877                        ->getLocation(),
7878                    diag::note_defaulted_comparison_not_rewritten_conversion)
7879                 << FD;
7880           }
7881         }
7882         return Result::deleted();
7883       }
7884 
7885       // Throughout C++2a [class.compare]: if overload resolution does not
7886       // result in a usable function, the candidate function is defined as
7887       // deleted. This requires that we selected an accessible function.
7888       //
7889       // Note that this only considers the access of the function when named
7890       // within the type of the subobject, and not the access path for any
7891       // derived-to-base conversion.
7892       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7893       if (ArgClass && Best->FoundDecl.getDecl() &&
7894           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7895         QualType ObjectType = Subobj.Kind == Subobject::Member
7896                                   ? Args[0]->getType()
7897                                   : S.Context.getRecordType(RD);
7898         if (!S.isMemberAccessibleForDeletion(
7899                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7900                 Diagnose == ExplainDeleted
7901                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7902                           << FD << Subobj.Kind << Subobj.Decl
7903                     : S.PDiag()))
7904           return Result::deleted();
7905       }
7906 
7907       bool NeedsDeducing =
7908           OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7909 
7910       if (FunctionDecl *BestFD = Best->Function) {
7911         // C++2a [class.compare.default]p3 [P2002R0]:
7912         //   A defaulted comparison function is constexpr-compatible if
7913         //   [...] no overlod resolution performed [...] results in a
7914         //   non-constexpr function.
7915         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7916         // If it's not constexpr, explain why not.
7917         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7918           if (Subobj.Kind != Subobject::CompleteObject)
7919             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7920               << Subobj.Kind << Subobj.Decl;
7921           S.Diag(BestFD->getLocation(),
7922                  diag::note_defaulted_comparison_not_constexpr_here);
7923           // Bail out after explaining; we don't want any more notes.
7924           return Result::deleted();
7925         }
7926         R.Constexpr &= BestFD->isConstexpr();
7927 
7928         if (NeedsDeducing) {
7929           // If any callee has an undeduced return type, deduce it now.
7930           // FIXME: It's not clear how a failure here should be handled. For
7931           // now, we produce an eager diagnostic, because that is forward
7932           // compatible with most (all?) other reasonable options.
7933           if (BestFD->getReturnType()->isUndeducedType() &&
7934               S.DeduceReturnType(BestFD, FD->getLocation(),
7935                                  /*Diagnose=*/false)) {
7936             // Don't produce a duplicate error when asked to explain why the
7937             // comparison is deleted: we diagnosed that when initially checking
7938             // the defaulted operator.
7939             if (Diagnose == NoDiagnostics) {
7940               S.Diag(
7941                   FD->getLocation(),
7942                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7943                   << Subobj.Kind << Subobj.Decl;
7944               S.Diag(
7945                   Subobj.Loc,
7946                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7947                   << Subobj.Kind << Subobj.Decl;
7948               S.Diag(BestFD->getLocation(),
7949                      diag::note_defaulted_comparison_cannot_deduce_callee)
7950                   << Subobj.Kind << Subobj.Decl;
7951             }
7952             return Result::deleted();
7953           }
7954           auto *Info = S.Context.CompCategories.lookupInfoForType(
7955               BestFD->getCallResultType());
7956           if (!Info) {
7957             if (Diagnose == ExplainDeleted) {
7958               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7959                   << Subobj.Kind << Subobj.Decl
7960                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7961               S.Diag(BestFD->getLocation(),
7962                      diag::note_defaulted_comparison_cannot_deduce_callee)
7963                   << Subobj.Kind << Subobj.Decl;
7964             }
7965             return Result::deleted();
7966           }
7967           R.Category = Info->Kind;
7968         }
7969       } else {
7970         QualType T = Best->BuiltinParamTypes[0];
7971         assert(T == Best->BuiltinParamTypes[1] &&
7972                "builtin comparison for different types?");
7973         assert(Best->BuiltinParamTypes[2].isNull() &&
7974                "invalid builtin comparison");
7975 
7976         if (NeedsDeducing) {
7977           Optional<ComparisonCategoryType> Cat =
7978               getComparisonCategoryForBuiltinCmp(T);
7979           assert(Cat && "no category for builtin comparison?");
7980           R.Category = *Cat;
7981         }
7982       }
7983 
7984       // Note that we might be rewriting to a different operator. That call is
7985       // not considered until we come to actually build the comparison function.
7986       break;
7987     }
7988 
7989     case OR_Ambiguous:
7990       if (Diagnose == ExplainDeleted) {
7991         unsigned Kind = 0;
7992         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7993           Kind = OO == OO_EqualEqual ? 1 : 2;
7994         CandidateSet.NoteCandidates(
7995             PartialDiagnosticAt(
7996                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7997                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7998             S, OCD_AmbiguousCandidates, Args);
7999       }
8000       R = Result::deleted();
8001       break;
8002 
8003     case OR_Deleted:
8004       if (Diagnose == ExplainDeleted) {
8005         if ((DCK == DefaultedComparisonKind::NotEqual ||
8006              DCK == DefaultedComparisonKind::Relational) &&
8007             !Best->RewriteKind) {
8008           S.Diag(Best->Function->getLocation(),
8009                  diag::note_defaulted_comparison_not_rewritten_callee)
8010               << FD;
8011         } else {
8012           S.Diag(Subobj.Loc,
8013                  diag::note_defaulted_comparison_calls_deleted)
8014               << FD << Subobj.Kind << Subobj.Decl;
8015           S.NoteDeletedFunction(Best->Function);
8016         }
8017       }
8018       R = Result::deleted();
8019       break;
8020 
8021     case OR_No_Viable_Function:
8022       // If there's no usable candidate, we're done unless we can rewrite a
8023       // '<=>' in terms of '==' and '<'.
8024       if (OO == OO_Spaceship &&
8025           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8026         // For any kind of comparison category return type, we need a usable
8027         // '==' and a usable '<'.
8028         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8029                                        &CandidateSet)))
8030           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8031         break;
8032       }
8033 
8034       if (Diagnose == ExplainDeleted) {
8035         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8036             << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
8037 
8038         // For a three-way comparison, list both the candidates for the
8039         // original operator and the candidates for the synthesized operator.
8040         if (SpaceshipCandidates) {
8041           SpaceshipCandidates->NoteCandidates(
8042               S, Args,
8043               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8044                                                       Args, FD->getLocation()));
8045           S.Diag(Subobj.Loc,
8046                  diag::note_defaulted_comparison_no_viable_function_synthesized)
8047               << (OO == OO_EqualEqual ? 0 : 1);
8048         }
8049 
8050         CandidateSet.NoteCandidates(
8051             S, Args,
8052             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8053                                             FD->getLocation()));
8054       }
8055       R = Result::deleted();
8056       break;
8057     }
8058 
8059     return R;
8060   }
8061 };
8062 
8063 /// A list of statements.
8064 struct StmtListResult {
8065   bool IsInvalid = false;
8066   llvm::SmallVector<Stmt*, 16> Stmts;
8067 
8068   bool add(const StmtResult &S) {
8069     IsInvalid |= S.isInvalid();
8070     if (IsInvalid)
8071       return true;
8072     Stmts.push_back(S.get());
8073     return false;
8074   }
8075 };
8076 
8077 /// A visitor over the notional body of a defaulted comparison that synthesizes
8078 /// the actual body.
8079 class DefaultedComparisonSynthesizer
8080     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8081                                         StmtListResult, StmtResult,
8082                                         std::pair<ExprResult, ExprResult>> {
8083   SourceLocation Loc;
8084   unsigned ArrayDepth = 0;
8085 
8086 public:
8087   using Base = DefaultedComparisonVisitor;
8088   using ExprPair = std::pair<ExprResult, ExprResult>;
8089 
8090   friend Base;
8091 
8092   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8093                                  DefaultedComparisonKind DCK,
8094                                  SourceLocation BodyLoc)
8095       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8096 
8097   /// Build a suitable function body for this defaulted comparison operator.
8098   StmtResult build() {
8099     Sema::CompoundScopeRAII CompoundScope(S);
8100 
8101     StmtListResult Stmts = visit();
8102     if (Stmts.IsInvalid)
8103       return StmtError();
8104 
8105     ExprResult RetVal;
8106     switch (DCK) {
8107     case DefaultedComparisonKind::None:
8108       llvm_unreachable("not a defaulted comparison");
8109 
8110     case DefaultedComparisonKind::Equal: {
8111       // C++2a [class.eq]p3:
8112       //   [...] compar[e] the corresponding elements [...] until the first
8113       //   index i where xi == yi yields [...] false. If no such index exists,
8114       //   V is true. Otherwise, V is false.
8115       //
8116       // Join the comparisons with '&&'s and return the result. Use a right
8117       // fold (traversing the conditions right-to-left), because that
8118       // short-circuits more naturally.
8119       auto OldStmts = std::move(Stmts.Stmts);
8120       Stmts.Stmts.clear();
8121       ExprResult CmpSoFar;
8122       // Finish a particular comparison chain.
8123       auto FinishCmp = [&] {
8124         if (Expr *Prior = CmpSoFar.get()) {
8125           // Convert the last expression to 'return ...;'
8126           if (RetVal.isUnset() && Stmts.Stmts.empty())
8127             RetVal = CmpSoFar;
8128           // Convert any prior comparison to 'if (!(...)) return false;'
8129           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8130             return true;
8131           CmpSoFar = ExprResult();
8132         }
8133         return false;
8134       };
8135       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8136         Expr *E = dyn_cast<Expr>(EAsStmt);
8137         if (!E) {
8138           // Found an array comparison.
8139           if (FinishCmp() || Stmts.add(EAsStmt))
8140             return StmtError();
8141           continue;
8142         }
8143 
8144         if (CmpSoFar.isUnset()) {
8145           CmpSoFar = E;
8146           continue;
8147         }
8148         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8149         if (CmpSoFar.isInvalid())
8150           return StmtError();
8151       }
8152       if (FinishCmp())
8153         return StmtError();
8154       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8155       //   If no such index exists, V is true.
8156       if (RetVal.isUnset())
8157         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8158       break;
8159     }
8160 
8161     case DefaultedComparisonKind::ThreeWay: {
8162       // Per C++2a [class.spaceship]p3, as a fallback add:
8163       // return static_cast<R>(std::strong_ordering::equal);
8164       QualType StrongOrdering = S.CheckComparisonCategoryType(
8165           ComparisonCategoryType::StrongOrdering, Loc,
8166           Sema::ComparisonCategoryUsage::DefaultedOperator);
8167       if (StrongOrdering.isNull())
8168         return StmtError();
8169       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8170                              .getValueInfo(ComparisonCategoryResult::Equal)
8171                              ->VD;
8172       RetVal = getDecl(EqualVD);
8173       if (RetVal.isInvalid())
8174         return StmtError();
8175       RetVal = buildStaticCastToR(RetVal.get());
8176       break;
8177     }
8178 
8179     case DefaultedComparisonKind::NotEqual:
8180     case DefaultedComparisonKind::Relational:
8181       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8182       break;
8183     }
8184 
8185     // Build the final return statement.
8186     if (RetVal.isInvalid())
8187       return StmtError();
8188     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8189     if (ReturnStmt.isInvalid())
8190       return StmtError();
8191     Stmts.Stmts.push_back(ReturnStmt.get());
8192 
8193     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8194   }
8195 
8196 private:
8197   ExprResult getDecl(ValueDecl *VD) {
8198     return S.BuildDeclarationNameExpr(
8199         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8200   }
8201 
8202   ExprResult getParam(unsigned I) {
8203     ParmVarDecl *PD = FD->getParamDecl(I);
8204     return getDecl(PD);
8205   }
8206 
8207   ExprPair getCompleteObject() {
8208     unsigned Param = 0;
8209     ExprResult LHS;
8210     if (isa<CXXMethodDecl>(FD)) {
8211       // LHS is '*this'.
8212       LHS = S.ActOnCXXThis(Loc);
8213       if (!LHS.isInvalid())
8214         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8215     } else {
8216       LHS = getParam(Param++);
8217     }
8218     ExprResult RHS = getParam(Param++);
8219     assert(Param == FD->getNumParams());
8220     return {LHS, RHS};
8221   }
8222 
8223   ExprPair getBase(CXXBaseSpecifier *Base) {
8224     ExprPair Obj = getCompleteObject();
8225     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8226       return {ExprError(), ExprError()};
8227     CXXCastPath Path = {Base};
8228     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8229                                 CK_DerivedToBase, VK_LValue, &Path),
8230             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8231                                 CK_DerivedToBase, VK_LValue, &Path)};
8232   }
8233 
8234   ExprPair getField(FieldDecl *Field) {
8235     ExprPair Obj = getCompleteObject();
8236     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8237       return {ExprError(), ExprError()};
8238 
8239     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8240     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8241     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8242                                       CXXScopeSpec(), Field, Found, NameInfo),
8243             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8244                                       CXXScopeSpec(), Field, Found, NameInfo)};
8245   }
8246 
8247   // FIXME: When expanding a subobject, register a note in the code synthesis
8248   // stack to say which subobject we're comparing.
8249 
8250   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8251     if (Cond.isInvalid())
8252       return StmtError();
8253 
8254     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8255     if (NotCond.isInvalid())
8256       return StmtError();
8257 
8258     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8259     assert(!False.isInvalid() && "should never fail");
8260     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8261     if (ReturnFalse.isInvalid())
8262       return StmtError();
8263 
8264     return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8265                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8266                                           Sema::ConditionKind::Boolean),
8267                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8268   }
8269 
8270   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8271                                  ExprPair Subobj) {
8272     QualType SizeType = S.Context.getSizeType();
8273     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8274 
8275     // Build 'size_t i$n = 0'.
8276     IdentifierInfo *IterationVarName = nullptr;
8277     {
8278       SmallString<8> Str;
8279       llvm::raw_svector_ostream OS(Str);
8280       OS << "i" << ArrayDepth;
8281       IterationVarName = &S.Context.Idents.get(OS.str());
8282     }
8283     VarDecl *IterationVar = VarDecl::Create(
8284         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8285         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8286     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8287     IterationVar->setInit(
8288         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8289     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8290 
8291     auto IterRef = [&] {
8292       ExprResult Ref = S.BuildDeclarationNameExpr(
8293           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8294           IterationVar);
8295       assert(!Ref.isInvalid() && "can't reference our own variable?");
8296       return Ref.get();
8297     };
8298 
8299     // Build 'i$n != Size'.
8300     ExprResult Cond = S.CreateBuiltinBinOp(
8301         Loc, BO_NE, IterRef(),
8302         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8303     assert(!Cond.isInvalid() && "should never fail");
8304 
8305     // Build '++i$n'.
8306     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8307     assert(!Inc.isInvalid() && "should never fail");
8308 
8309     // Build 'a[i$n]' and 'b[i$n]'.
8310     auto Index = [&](ExprResult E) {
8311       if (E.isInvalid())
8312         return ExprError();
8313       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8314     };
8315     Subobj.first = Index(Subobj.first);
8316     Subobj.second = Index(Subobj.second);
8317 
8318     // Compare the array elements.
8319     ++ArrayDepth;
8320     StmtResult Substmt = visitSubobject(Type, Subobj);
8321     --ArrayDepth;
8322 
8323     if (Substmt.isInvalid())
8324       return StmtError();
8325 
8326     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8327     // For outer levels or for an 'operator<=>' we already have a suitable
8328     // statement that returns as necessary.
8329     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8330       assert(DCK == DefaultedComparisonKind::Equal &&
8331              "should have non-expression statement");
8332       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8333       if (Substmt.isInvalid())
8334         return StmtError();
8335     }
8336 
8337     // Build 'for (...) ...'
8338     return S.ActOnForStmt(Loc, Loc, Init,
8339                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8340                                            Sema::ConditionKind::Boolean),
8341                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8342                           Substmt.get());
8343   }
8344 
8345   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8346     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8347       return StmtError();
8348 
8349     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8350     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8351     ExprResult Op;
8352     if (Type->isOverloadableType())
8353       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8354                                    Obj.second.get(), /*PerformADL=*/true,
8355                                    /*AllowRewrittenCandidates=*/true, FD);
8356     else
8357       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8358     if (Op.isInvalid())
8359       return StmtError();
8360 
8361     switch (DCK) {
8362     case DefaultedComparisonKind::None:
8363       llvm_unreachable("not a defaulted comparison");
8364 
8365     case DefaultedComparisonKind::Equal:
8366       // Per C++2a [class.eq]p2, each comparison is individually contextually
8367       // converted to bool.
8368       Op = S.PerformContextuallyConvertToBool(Op.get());
8369       if (Op.isInvalid())
8370         return StmtError();
8371       return Op.get();
8372 
8373     case DefaultedComparisonKind::ThreeWay: {
8374       // Per C++2a [class.spaceship]p3, form:
8375       //   if (R cmp = static_cast<R>(op); cmp != 0)
8376       //     return cmp;
8377       QualType R = FD->getReturnType();
8378       Op = buildStaticCastToR(Op.get());
8379       if (Op.isInvalid())
8380         return StmtError();
8381 
8382       // R cmp = ...;
8383       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8384       VarDecl *VD =
8385           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8386                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8387       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8388       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8389 
8390       // cmp != 0
8391       ExprResult VDRef = getDecl(VD);
8392       if (VDRef.isInvalid())
8393         return StmtError();
8394       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8395       Expr *Zero =
8396           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8397       ExprResult Comp;
8398       if (VDRef.get()->getType()->isOverloadableType())
8399         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8400                                        true, FD);
8401       else
8402         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8403       if (Comp.isInvalid())
8404         return StmtError();
8405       Sema::ConditionResult Cond = S.ActOnCondition(
8406           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8407       if (Cond.isInvalid())
8408         return StmtError();
8409 
8410       // return cmp;
8411       VDRef = getDecl(VD);
8412       if (VDRef.isInvalid())
8413         return StmtError();
8414       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8415       if (ReturnStmt.isInvalid())
8416         return StmtError();
8417 
8418       // if (...)
8419       return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8420                            Loc, ReturnStmt.get(),
8421                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8422     }
8423 
8424     case DefaultedComparisonKind::NotEqual:
8425     case DefaultedComparisonKind::Relational:
8426       // C++2a [class.compare.secondary]p2:
8427       //   Otherwise, the operator function yields x @ y.
8428       return Op.get();
8429     }
8430     llvm_unreachable("");
8431   }
8432 
8433   /// Build "static_cast<R>(E)".
8434   ExprResult buildStaticCastToR(Expr *E) {
8435     QualType R = FD->getReturnType();
8436     assert(!R->isUndeducedType() && "type should have been deduced already");
8437 
8438     // Don't bother forming a no-op cast in the common case.
8439     if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8440       return E;
8441     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8442                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8443                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8444   }
8445 };
8446 }
8447 
8448 /// Perform the unqualified lookups that might be needed to form a defaulted
8449 /// comparison function for the given operator.
8450 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8451                                                   UnresolvedSetImpl &Operators,
8452                                                   OverloadedOperatorKind Op) {
8453   auto Lookup = [&](OverloadedOperatorKind OO) {
8454     Self.LookupOverloadedOperatorName(OO, S, Operators);
8455   };
8456 
8457   // Every defaulted operator looks up itself.
8458   Lookup(Op);
8459   // ... and the rewritten form of itself, if any.
8460   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8461     Lookup(ExtraOp);
8462 
8463   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8464   // synthesize a three-way comparison from '<' and '=='. In a dependent
8465   // context, we also need to look up '==' in case we implicitly declare a
8466   // defaulted 'operator=='.
8467   if (Op == OO_Spaceship) {
8468     Lookup(OO_ExclaimEqual);
8469     Lookup(OO_Less);
8470     Lookup(OO_EqualEqual);
8471   }
8472 }
8473 
8474 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8475                                               DefaultedComparisonKind DCK) {
8476   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8477 
8478   // Perform any unqualified lookups we're going to need to default this
8479   // function.
8480   if (S) {
8481     UnresolvedSet<32> Operators;
8482     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8483                                           FD->getOverloadedOperator());
8484     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8485         Context, Operators.pairs()));
8486   }
8487 
8488   // C++2a [class.compare.default]p1:
8489   //   A defaulted comparison operator function for some class C shall be a
8490   //   non-template function declared in the member-specification of C that is
8491   //    -- a non-static const member of C having one parameter of type
8492   //       const C&, or
8493   //    -- a friend of C having two parameters of type const C& or two
8494   //       parameters of type C.
8495 
8496   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8497   bool IsMethod = isa<CXXMethodDecl>(FD);
8498   if (IsMethod) {
8499     auto *MD = cast<CXXMethodDecl>(FD);
8500     assert(!MD->isStatic() && "comparison function cannot be a static member");
8501 
8502     // If we're out-of-class, this is the class we're comparing.
8503     if (!RD)
8504       RD = MD->getParent();
8505 
8506     if (!MD->isConst()) {
8507       SourceLocation InsertLoc;
8508       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8509         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8510       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8511       // corresponding defaulted 'operator<=>' already.
8512       if (!MD->isImplicit()) {
8513         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8514             << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8515       }
8516 
8517       // Add the 'const' to the type to recover.
8518       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8519       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8520       EPI.TypeQuals.addConst();
8521       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8522                                           FPT->getParamTypes(), EPI));
8523     }
8524   }
8525 
8526   if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8527     // Let's not worry about using a variadic template pack here -- who would do
8528     // such a thing?
8529     Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8530         << int(IsMethod) << int(DCK);
8531     return true;
8532   }
8533 
8534   const ParmVarDecl *KnownParm = nullptr;
8535   for (const ParmVarDecl *Param : FD->parameters()) {
8536     QualType ParmTy = Param->getType();
8537     if (ParmTy->isDependentType())
8538       continue;
8539     if (!KnownParm) {
8540       auto CTy = ParmTy;
8541       // Is it `T const &`?
8542       bool Ok = !IsMethod;
8543       QualType ExpectedTy;
8544       if (RD)
8545         ExpectedTy = Context.getRecordType(RD);
8546       if (auto *Ref = CTy->getAs<ReferenceType>()) {
8547         CTy = Ref->getPointeeType();
8548         if (RD)
8549           ExpectedTy.addConst();
8550         Ok = true;
8551       }
8552 
8553       // Is T a class?
8554       if (!Ok) {
8555       } else if (RD) {
8556         if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8557           Ok = false;
8558       } else if (auto *CRD = CTy->getAsRecordDecl()) {
8559         RD = cast<CXXRecordDecl>(CRD);
8560       } else {
8561         Ok = false;
8562       }
8563 
8564       if (Ok) {
8565         KnownParm = Param;
8566       } else {
8567         // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8568         // corresponding defaulted 'operator<=>' already.
8569         if (!FD->isImplicit()) {
8570           if (RD) {
8571             QualType PlainTy = Context.getRecordType(RD);
8572             QualType RefTy =
8573                 Context.getLValueReferenceType(PlainTy.withConst());
8574             Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8575                 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8576                 << Param->getSourceRange();
8577           } else {
8578             assert(!IsMethod && "should know expected type for method");
8579             Diag(FD->getLocation(),
8580                  diag::err_defaulted_comparison_param_unknown)
8581                 << int(DCK) << ParmTy << Param->getSourceRange();
8582           }
8583         }
8584         return true;
8585       }
8586     } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8587       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8588           << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8589           << ParmTy << Param->getSourceRange();
8590       return true;
8591     }
8592   }
8593 
8594   assert(RD && "must have determined class");
8595   if (IsMethod) {
8596   } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8597     // In-class, must be a friend decl.
8598     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8599   } else {
8600     // Out of class, require the defaulted comparison to be a friend (of a
8601     // complete type).
8602     if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8603                             diag::err_defaulted_comparison_not_friend, int(DCK),
8604                             int(1)))
8605       return true;
8606 
8607     if (llvm::find_if(RD->friends(), [&](const FriendDecl *F) {
8608           return FD->getCanonicalDecl() ==
8609                  F->getFriendDecl()->getCanonicalDecl();
8610         }) == RD->friends().end()) {
8611       Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8612           << int(DCK) << int(0) << RD;
8613       Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8614       return true;
8615     }
8616   }
8617 
8618   // C++2a [class.eq]p1, [class.rel]p1:
8619   //   A [defaulted comparison other than <=>] shall have a declared return
8620   //   type bool.
8621   if (DCK != DefaultedComparisonKind::ThreeWay &&
8622       !FD->getDeclaredReturnType()->isDependentType() &&
8623       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8624     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8625         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8626         << FD->getReturnTypeSourceRange();
8627     return true;
8628   }
8629   // C++2a [class.spaceship]p2 [P2002R0]:
8630   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8631   //   R shall not contain a placeholder type.
8632   if (DCK == DefaultedComparisonKind::ThreeWay &&
8633       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8634       !Context.hasSameType(FD->getDeclaredReturnType(),
8635                            Context.getAutoDeductType())) {
8636     Diag(FD->getLocation(),
8637          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8638         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8639         << FD->getReturnTypeSourceRange();
8640     return true;
8641   }
8642 
8643   // For a defaulted function in a dependent class, defer all remaining checks
8644   // until instantiation.
8645   if (RD->isDependentType())
8646     return false;
8647 
8648   // Determine whether the function should be defined as deleted.
8649   DefaultedComparisonInfo Info =
8650       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8651 
8652   bool First = FD == FD->getCanonicalDecl();
8653 
8654   // If we want to delete the function, then do so; there's nothing else to
8655   // check in that case.
8656   if (Info.Deleted) {
8657     if (!First) {
8658       // C++11 [dcl.fct.def.default]p4:
8659       //   [For a] user-provided explicitly-defaulted function [...] if such a
8660       //   function is implicitly defined as deleted, the program is ill-formed.
8661       //
8662       // This is really just a consequence of the general rule that you can
8663       // only delete a function on its first declaration.
8664       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8665           << FD->isImplicit() << (int)DCK;
8666       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8667                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8668           .visit();
8669       return true;
8670     }
8671 
8672     SetDeclDeleted(FD, FD->getLocation());
8673     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8674       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8675           << (int)DCK;
8676       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8677                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8678           .visit();
8679     }
8680     return false;
8681   }
8682 
8683   // C++2a [class.spaceship]p2:
8684   //   The return type is deduced as the common comparison type of R0, R1, ...
8685   if (DCK == DefaultedComparisonKind::ThreeWay &&
8686       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8687     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8688     if (RetLoc.isInvalid())
8689       RetLoc = FD->getBeginLoc();
8690     // FIXME: Should we really care whether we have the complete type and the
8691     // 'enumerator' constants here? A forward declaration seems sufficient.
8692     QualType Cat = CheckComparisonCategoryType(
8693         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8694     if (Cat.isNull())
8695       return true;
8696     Context.adjustDeducedFunctionResultType(
8697         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8698   }
8699 
8700   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8701   //   An explicitly-defaulted function that is not defined as deleted may be
8702   //   declared constexpr or consteval only if it is constexpr-compatible.
8703   // C++2a [class.compare.default]p3 [P2002R0]:
8704   //   A defaulted comparison function is constexpr-compatible if it satisfies
8705   //   the requirements for a constexpr function [...]
8706   // The only relevant requirements are that the parameter and return types are
8707   // literal types. The remaining conditions are checked by the analyzer.
8708   if (FD->isConstexpr()) {
8709     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8710         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8711         !Info.Constexpr) {
8712       Diag(FD->getBeginLoc(),
8713            diag::err_incorrect_defaulted_comparison_constexpr)
8714           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8715       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8716                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8717           .visit();
8718     }
8719   }
8720 
8721   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8722   //   If a constexpr-compatible function is explicitly defaulted on its first
8723   //   declaration, it is implicitly considered to be constexpr.
8724   // FIXME: Only applying this to the first declaration seems problematic, as
8725   // simple reorderings can affect the meaning of the program.
8726   if (First && !FD->isConstexpr() && Info.Constexpr)
8727     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8728 
8729   // C++2a [except.spec]p3:
8730   //   If a declaration of a function does not have a noexcept-specifier
8731   //   [and] is defaulted on its first declaration, [...] the exception
8732   //   specification is as specified below
8733   if (FD->getExceptionSpecType() == EST_None) {
8734     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8735     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8736     EPI.ExceptionSpec.Type = EST_Unevaluated;
8737     EPI.ExceptionSpec.SourceDecl = FD;
8738     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8739                                         FPT->getParamTypes(), EPI));
8740   }
8741 
8742   return false;
8743 }
8744 
8745 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8746                                              FunctionDecl *Spaceship) {
8747   Sema::CodeSynthesisContext Ctx;
8748   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8749   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8750   Ctx.Entity = Spaceship;
8751   pushCodeSynthesisContext(Ctx);
8752 
8753   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8754     EqualEqual->setImplicit();
8755 
8756   popCodeSynthesisContext();
8757 }
8758 
8759 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8760                                      DefaultedComparisonKind DCK) {
8761   assert(FD->isDefaulted() && !FD->isDeleted() &&
8762          !FD->doesThisDeclarationHaveABody());
8763   if (FD->willHaveBody() || FD->isInvalidDecl())
8764     return;
8765 
8766   SynthesizedFunctionScope Scope(*this, FD);
8767 
8768   // Add a context note for diagnostics produced after this point.
8769   Scope.addContextNote(UseLoc);
8770 
8771   {
8772     // Build and set up the function body.
8773     // The first parameter has type maybe-ref-to maybe-const T, use that to get
8774     // the type of the class being compared.
8775     auto PT = FD->getParamDecl(0)->getType();
8776     CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
8777     SourceLocation BodyLoc =
8778         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8779     StmtResult Body =
8780         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8781     if (Body.isInvalid()) {
8782       FD->setInvalidDecl();
8783       return;
8784     }
8785     FD->setBody(Body.get());
8786     FD->markUsed(Context);
8787   }
8788 
8789   // The exception specification is needed because we are defining the
8790   // function. Note that this will reuse the body we just built.
8791   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8792 
8793   if (ASTMutationListener *L = getASTMutationListener())
8794     L->CompletedImplicitDefinition(FD);
8795 }
8796 
8797 static Sema::ImplicitExceptionSpecification
8798 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8799                                         FunctionDecl *FD,
8800                                         Sema::DefaultedComparisonKind DCK) {
8801   ComputingExceptionSpec CES(S, FD, Loc);
8802   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8803 
8804   if (FD->isInvalidDecl())
8805     return ExceptSpec;
8806 
8807   // The common case is that we just defined the comparison function. In that
8808   // case, just look at whether the body can throw.
8809   if (FD->hasBody()) {
8810     ExceptSpec.CalledStmt(FD->getBody());
8811   } else {
8812     // Otherwise, build a body so we can check it. This should ideally only
8813     // happen when we're not actually marking the function referenced. (This is
8814     // only really important for efficiency: we don't want to build and throw
8815     // away bodies for comparison functions more than we strictly need to.)
8816 
8817     // Pretend to synthesize the function body in an unevaluated context.
8818     // Note that we can't actually just go ahead and define the function here:
8819     // we are not permitted to mark its callees as referenced.
8820     Sema::SynthesizedFunctionScope Scope(S, FD);
8821     EnterExpressionEvaluationContext Context(
8822         S, Sema::ExpressionEvaluationContext::Unevaluated);
8823 
8824     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8825     SourceLocation BodyLoc =
8826         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8827     StmtResult Body =
8828         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8829     if (!Body.isInvalid())
8830       ExceptSpec.CalledStmt(Body.get());
8831 
8832     // FIXME: Can we hold onto this body and just transform it to potentially
8833     // evaluated when we're asked to define the function rather than rebuilding
8834     // it? Either that, or we should only build the bits of the body that we
8835     // need (the expressions, not the statements).
8836   }
8837 
8838   return ExceptSpec;
8839 }
8840 
8841 void Sema::CheckDelayedMemberExceptionSpecs() {
8842   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8843   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8844 
8845   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8846   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8847 
8848   // Perform any deferred checking of exception specifications for virtual
8849   // destructors.
8850   for (auto &Check : Overriding)
8851     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8852 
8853   // Perform any deferred checking of exception specifications for befriended
8854   // special members.
8855   for (auto &Check : Equivalent)
8856     CheckEquivalentExceptionSpec(Check.second, Check.first);
8857 }
8858 
8859 namespace {
8860 /// CRTP base class for visiting operations performed by a special member
8861 /// function (or inherited constructor).
8862 template<typename Derived>
8863 struct SpecialMemberVisitor {
8864   Sema &S;
8865   CXXMethodDecl *MD;
8866   Sema::CXXSpecialMember CSM;
8867   Sema::InheritedConstructorInfo *ICI;
8868 
8869   // Properties of the special member, computed for convenience.
8870   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8871 
8872   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8873                        Sema::InheritedConstructorInfo *ICI)
8874       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8875     switch (CSM) {
8876     case Sema::CXXDefaultConstructor:
8877     case Sema::CXXCopyConstructor:
8878     case Sema::CXXMoveConstructor:
8879       IsConstructor = true;
8880       break;
8881     case Sema::CXXCopyAssignment:
8882     case Sema::CXXMoveAssignment:
8883       IsAssignment = true;
8884       break;
8885     case Sema::CXXDestructor:
8886       break;
8887     case Sema::CXXInvalid:
8888       llvm_unreachable("invalid special member kind");
8889     }
8890 
8891     if (MD->getNumParams()) {
8892       if (const ReferenceType *RT =
8893               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8894         ConstArg = RT->getPointeeType().isConstQualified();
8895     }
8896   }
8897 
8898   Derived &getDerived() { return static_cast<Derived&>(*this); }
8899 
8900   /// Is this a "move" special member?
8901   bool isMove() const {
8902     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8903   }
8904 
8905   /// Look up the corresponding special member in the given class.
8906   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8907                                              unsigned Quals, bool IsMutable) {
8908     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8909                                        ConstArg && !IsMutable);
8910   }
8911 
8912   /// Look up the constructor for the specified base class to see if it's
8913   /// overridden due to this being an inherited constructor.
8914   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8915     if (!ICI)
8916       return {};
8917     assert(CSM == Sema::CXXDefaultConstructor);
8918     auto *BaseCtor =
8919       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8920     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8921       return MD;
8922     return {};
8923   }
8924 
8925   /// A base or member subobject.
8926   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8927 
8928   /// Get the location to use for a subobject in diagnostics.
8929   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8930     // FIXME: For an indirect virtual base, the direct base leading to
8931     // the indirect virtual base would be a more useful choice.
8932     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8933       return B->getBaseTypeLoc();
8934     else
8935       return Subobj.get<FieldDecl*>()->getLocation();
8936   }
8937 
8938   enum BasesToVisit {
8939     /// Visit all non-virtual (direct) bases.
8940     VisitNonVirtualBases,
8941     /// Visit all direct bases, virtual or not.
8942     VisitDirectBases,
8943     /// Visit all non-virtual bases, and all virtual bases if the class
8944     /// is not abstract.
8945     VisitPotentiallyConstructedBases,
8946     /// Visit all direct or virtual bases.
8947     VisitAllBases
8948   };
8949 
8950   // Visit the bases and members of the class.
8951   bool visit(BasesToVisit Bases) {
8952     CXXRecordDecl *RD = MD->getParent();
8953 
8954     if (Bases == VisitPotentiallyConstructedBases)
8955       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8956 
8957     for (auto &B : RD->bases())
8958       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8959           getDerived().visitBase(&B))
8960         return true;
8961 
8962     if (Bases == VisitAllBases)
8963       for (auto &B : RD->vbases())
8964         if (getDerived().visitBase(&B))
8965           return true;
8966 
8967     for (auto *F : RD->fields())
8968       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8969           getDerived().visitField(F))
8970         return true;
8971 
8972     return false;
8973   }
8974 };
8975 }
8976 
8977 namespace {
8978 struct SpecialMemberDeletionInfo
8979     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8980   bool Diagnose;
8981 
8982   SourceLocation Loc;
8983 
8984   bool AllFieldsAreConst;
8985 
8986   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8987                             Sema::CXXSpecialMember CSM,
8988                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8989       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8990         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8991 
8992   bool inUnion() const { return MD->getParent()->isUnion(); }
8993 
8994   Sema::CXXSpecialMember getEffectiveCSM() {
8995     return ICI ? Sema::CXXInvalid : CSM;
8996   }
8997 
8998   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8999 
9000   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9001   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9002 
9003   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9004   bool shouldDeleteForField(FieldDecl *FD);
9005   bool shouldDeleteForAllConstMembers();
9006 
9007   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9008                                      unsigned Quals);
9009   bool shouldDeleteForSubobjectCall(Subobject Subobj,
9010                                     Sema::SpecialMemberOverloadResult SMOR,
9011                                     bool IsDtorCallInCtor);
9012 
9013   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9014 };
9015 }
9016 
9017 /// Is the given special member inaccessible when used on the given
9018 /// sub-object.
9019 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9020                                              CXXMethodDecl *target) {
9021   /// If we're operating on a base class, the object type is the
9022   /// type of this special member.
9023   QualType objectTy;
9024   AccessSpecifier access = target->getAccess();
9025   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9026     objectTy = S.Context.getTypeDeclType(MD->getParent());
9027     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9028 
9029   // If we're operating on a field, the object type is the type of the field.
9030   } else {
9031     objectTy = S.Context.getTypeDeclType(target->getParent());
9032   }
9033 
9034   return S.isMemberAccessibleForDeletion(
9035       target->getParent(), DeclAccessPair::make(target, access), objectTy);
9036 }
9037 
9038 /// Check whether we should delete a special member due to the implicit
9039 /// definition containing a call to a special member of a subobject.
9040 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9041     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9042     bool IsDtorCallInCtor) {
9043   CXXMethodDecl *Decl = SMOR.getMethod();
9044   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9045 
9046   int DiagKind = -1;
9047 
9048   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9049     DiagKind = !Decl ? 0 : 1;
9050   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9051     DiagKind = 2;
9052   else if (!isAccessible(Subobj, Decl))
9053     DiagKind = 3;
9054   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9055            !Decl->isTrivial()) {
9056     // A member of a union must have a trivial corresponding special member.
9057     // As a weird special case, a destructor call from a union's constructor
9058     // must be accessible and non-deleted, but need not be trivial. Such a
9059     // destructor is never actually called, but is semantically checked as
9060     // if it were.
9061     DiagKind = 4;
9062   }
9063 
9064   if (DiagKind == -1)
9065     return false;
9066 
9067   if (Diagnose) {
9068     if (Field) {
9069       S.Diag(Field->getLocation(),
9070              diag::note_deleted_special_member_class_subobject)
9071         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9072         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9073     } else {
9074       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9075       S.Diag(Base->getBeginLoc(),
9076              diag::note_deleted_special_member_class_subobject)
9077           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9078           << Base->getType() << DiagKind << IsDtorCallInCtor
9079           << /*IsObjCPtr*/false;
9080     }
9081 
9082     if (DiagKind == 1)
9083       S.NoteDeletedFunction(Decl);
9084     // FIXME: Explain inaccessibility if DiagKind == 3.
9085   }
9086 
9087   return true;
9088 }
9089 
9090 /// Check whether we should delete a special member function due to having a
9091 /// direct or virtual base class or non-static data member of class type M.
9092 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9093     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9094   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9095   bool IsMutable = Field && Field->isMutable();
9096 
9097   // C++11 [class.ctor]p5:
9098   // -- any direct or virtual base class, or non-static data member with no
9099   //    brace-or-equal-initializer, has class type M (or array thereof) and
9100   //    either M has no default constructor or overload resolution as applied
9101   //    to M's default constructor results in an ambiguity or in a function
9102   //    that is deleted or inaccessible
9103   // C++11 [class.copy]p11, C++11 [class.copy]p23:
9104   // -- a direct or virtual base class B that cannot be copied/moved because
9105   //    overload resolution, as applied to B's corresponding special member,
9106   //    results in an ambiguity or a function that is deleted or inaccessible
9107   //    from the defaulted special member
9108   // C++11 [class.dtor]p5:
9109   // -- any direct or virtual base class [...] has a type with a destructor
9110   //    that is deleted or inaccessible
9111   if (!(CSM == Sema::CXXDefaultConstructor &&
9112         Field && Field->hasInClassInitializer()) &&
9113       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9114                                    false))
9115     return true;
9116 
9117   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9118   // -- any direct or virtual base class or non-static data member has a
9119   //    type with a destructor that is deleted or inaccessible
9120   if (IsConstructor) {
9121     Sema::SpecialMemberOverloadResult SMOR =
9122         S.LookupSpecialMember(Class, Sema::CXXDestructor,
9123                               false, false, false, false, false);
9124     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9125       return true;
9126   }
9127 
9128   return false;
9129 }
9130 
9131 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9132     FieldDecl *FD, QualType FieldType) {
9133   // The defaulted special functions are defined as deleted if this is a variant
9134   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9135   // type under ARC.
9136   if (!FieldType.hasNonTrivialObjCLifetime())
9137     return false;
9138 
9139   // Don't make the defaulted default constructor defined as deleted if the
9140   // member has an in-class initializer.
9141   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9142     return false;
9143 
9144   if (Diagnose) {
9145     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9146     S.Diag(FD->getLocation(),
9147            diag::note_deleted_special_member_class_subobject)
9148         << getEffectiveCSM() << ParentClass << /*IsField*/true
9149         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9150   }
9151 
9152   return true;
9153 }
9154 
9155 /// Check whether we should delete a special member function due to the class
9156 /// having a particular direct or virtual base class.
9157 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9158   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9159   // If program is correct, BaseClass cannot be null, but if it is, the error
9160   // must be reported elsewhere.
9161   if (!BaseClass)
9162     return false;
9163   // If we have an inheriting constructor, check whether we're calling an
9164   // inherited constructor instead of a default constructor.
9165   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9166   if (auto *BaseCtor = SMOR.getMethod()) {
9167     // Note that we do not check access along this path; other than that,
9168     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9169     // FIXME: Check that the base has a usable destructor! Sink this into
9170     // shouldDeleteForClassSubobject.
9171     if (BaseCtor->isDeleted() && Diagnose) {
9172       S.Diag(Base->getBeginLoc(),
9173              diag::note_deleted_special_member_class_subobject)
9174           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9175           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9176           << /*IsObjCPtr*/false;
9177       S.NoteDeletedFunction(BaseCtor);
9178     }
9179     return BaseCtor->isDeleted();
9180   }
9181   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9182 }
9183 
9184 /// Check whether we should delete a special member function due to the class
9185 /// having a particular non-static data member.
9186 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9187   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9188   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9189 
9190   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9191     return true;
9192 
9193   if (CSM == Sema::CXXDefaultConstructor) {
9194     // For a default constructor, all references must be initialized in-class
9195     // and, if a union, it must have a non-const member.
9196     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9197       if (Diagnose)
9198         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9199           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9200       return true;
9201     }
9202     // C++11 [class.ctor]p5: any non-variant non-static data member of
9203     // const-qualified type (or array thereof) with no
9204     // brace-or-equal-initializer does not have a user-provided default
9205     // constructor.
9206     if (!inUnion() && FieldType.isConstQualified() &&
9207         !FD->hasInClassInitializer() &&
9208         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
9209       if (Diagnose)
9210         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9211           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9212       return true;
9213     }
9214 
9215     if (inUnion() && !FieldType.isConstQualified())
9216       AllFieldsAreConst = false;
9217   } else if (CSM == Sema::CXXCopyConstructor) {
9218     // For a copy constructor, data members must not be of rvalue reference
9219     // type.
9220     if (FieldType->isRValueReferenceType()) {
9221       if (Diagnose)
9222         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9223           << MD->getParent() << FD << FieldType;
9224       return true;
9225     }
9226   } else if (IsAssignment) {
9227     // For an assignment operator, data members must not be of reference type.
9228     if (FieldType->isReferenceType()) {
9229       if (Diagnose)
9230         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9231           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9232       return true;
9233     }
9234     if (!FieldRecord && FieldType.isConstQualified()) {
9235       // C++11 [class.copy]p23:
9236       // -- a non-static data member of const non-class type (or array thereof)
9237       if (Diagnose)
9238         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9239           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9240       return true;
9241     }
9242   }
9243 
9244   if (FieldRecord) {
9245     // Some additional restrictions exist on the variant members.
9246     if (!inUnion() && FieldRecord->isUnion() &&
9247         FieldRecord->isAnonymousStructOrUnion()) {
9248       bool AllVariantFieldsAreConst = true;
9249 
9250       // FIXME: Handle anonymous unions declared within anonymous unions.
9251       for (auto *UI : FieldRecord->fields()) {
9252         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9253 
9254         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9255           return true;
9256 
9257         if (!UnionFieldType.isConstQualified())
9258           AllVariantFieldsAreConst = false;
9259 
9260         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9261         if (UnionFieldRecord &&
9262             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9263                                           UnionFieldType.getCVRQualifiers()))
9264           return true;
9265       }
9266 
9267       // At least one member in each anonymous union must be non-const
9268       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9269           !FieldRecord->field_empty()) {
9270         if (Diagnose)
9271           S.Diag(FieldRecord->getLocation(),
9272                  diag::note_deleted_default_ctor_all_const)
9273             << !!ICI << MD->getParent() << /*anonymous union*/1;
9274         return true;
9275       }
9276 
9277       // Don't check the implicit member of the anonymous union type.
9278       // This is technically non-conformant but supported, and we have a
9279       // diagnostic for this elsewhere.
9280       return false;
9281     }
9282 
9283     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9284                                       FieldType.getCVRQualifiers()))
9285       return true;
9286   }
9287 
9288   return false;
9289 }
9290 
9291 /// C++11 [class.ctor] p5:
9292 ///   A defaulted default constructor for a class X is defined as deleted if
9293 /// X is a union and all of its variant members are of const-qualified type.
9294 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9295   // This is a silly definition, because it gives an empty union a deleted
9296   // default constructor. Don't do that.
9297   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9298     bool AnyFields = false;
9299     for (auto *F : MD->getParent()->fields())
9300       if ((AnyFields = !F->isUnnamedBitfield()))
9301         break;
9302     if (!AnyFields)
9303       return false;
9304     if (Diagnose)
9305       S.Diag(MD->getParent()->getLocation(),
9306              diag::note_deleted_default_ctor_all_const)
9307         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9308     return true;
9309   }
9310   return false;
9311 }
9312 
9313 /// Determine whether a defaulted special member function should be defined as
9314 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9315 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9316 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9317                                      InheritedConstructorInfo *ICI,
9318                                      bool Diagnose) {
9319   if (MD->isInvalidDecl())
9320     return false;
9321   CXXRecordDecl *RD = MD->getParent();
9322   assert(!RD->isDependentType() && "do deletion after instantiation");
9323   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9324     return false;
9325 
9326   // C++11 [expr.lambda.prim]p19:
9327   //   The closure type associated with a lambda-expression has a
9328   //   deleted (8.4.3) default constructor and a deleted copy
9329   //   assignment operator.
9330   // C++2a adds back these operators if the lambda has no lambda-capture.
9331   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9332       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9333     if (Diagnose)
9334       Diag(RD->getLocation(), diag::note_lambda_decl);
9335     return true;
9336   }
9337 
9338   // For an anonymous struct or union, the copy and assignment special members
9339   // will never be used, so skip the check. For an anonymous union declared at
9340   // namespace scope, the constructor and destructor are used.
9341   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9342       RD->isAnonymousStructOrUnion())
9343     return false;
9344 
9345   // C++11 [class.copy]p7, p18:
9346   //   If the class definition declares a move constructor or move assignment
9347   //   operator, an implicitly declared copy constructor or copy assignment
9348   //   operator is defined as deleted.
9349   if (MD->isImplicit() &&
9350       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9351     CXXMethodDecl *UserDeclaredMove = nullptr;
9352 
9353     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9354     // deletion of the corresponding copy operation, not both copy operations.
9355     // MSVC 2015 has adopted the standards conforming behavior.
9356     bool DeletesOnlyMatchingCopy =
9357         getLangOpts().MSVCCompat &&
9358         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9359 
9360     if (RD->hasUserDeclaredMoveConstructor() &&
9361         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9362       if (!Diagnose) return true;
9363 
9364       // Find any user-declared move constructor.
9365       for (auto *I : RD->ctors()) {
9366         if (I->isMoveConstructor()) {
9367           UserDeclaredMove = I;
9368           break;
9369         }
9370       }
9371       assert(UserDeclaredMove);
9372     } else if (RD->hasUserDeclaredMoveAssignment() &&
9373                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9374       if (!Diagnose) return true;
9375 
9376       // Find any user-declared move assignment operator.
9377       for (auto *I : RD->methods()) {
9378         if (I->isMoveAssignmentOperator()) {
9379           UserDeclaredMove = I;
9380           break;
9381         }
9382       }
9383       assert(UserDeclaredMove);
9384     }
9385 
9386     if (UserDeclaredMove) {
9387       Diag(UserDeclaredMove->getLocation(),
9388            diag::note_deleted_copy_user_declared_move)
9389         << (CSM == CXXCopyAssignment) << RD
9390         << UserDeclaredMove->isMoveAssignmentOperator();
9391       return true;
9392     }
9393   }
9394 
9395   // Do access control from the special member function
9396   ContextRAII MethodContext(*this, MD);
9397 
9398   // C++11 [class.dtor]p5:
9399   // -- for a virtual destructor, lookup of the non-array deallocation function
9400   //    results in an ambiguity or in a function that is deleted or inaccessible
9401   if (CSM == CXXDestructor && MD->isVirtual()) {
9402     FunctionDecl *OperatorDelete = nullptr;
9403     DeclarationName Name =
9404       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9405     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9406                                  OperatorDelete, /*Diagnose*/false)) {
9407       if (Diagnose)
9408         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9409       return true;
9410     }
9411   }
9412 
9413   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9414 
9415   // Per DR1611, do not consider virtual bases of constructors of abstract
9416   // classes, since we are not going to construct them.
9417   // Per DR1658, do not consider virtual bases of destructors of abstract
9418   // classes either.
9419   // Per DR2180, for assignment operators we only assign (and thus only
9420   // consider) direct bases.
9421   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9422                                  : SMI.VisitPotentiallyConstructedBases))
9423     return true;
9424 
9425   if (SMI.shouldDeleteForAllConstMembers())
9426     return true;
9427 
9428   if (getLangOpts().CUDA) {
9429     // We should delete the special member in CUDA mode if target inference
9430     // failed.
9431     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9432     // is treated as certain special member, which may not reflect what special
9433     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9434     // expects CSM to match MD, therefore recalculate CSM.
9435     assert(ICI || CSM == getSpecialMember(MD));
9436     auto RealCSM = CSM;
9437     if (ICI)
9438       RealCSM = getSpecialMember(MD);
9439 
9440     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9441                                                    SMI.ConstArg, Diagnose);
9442   }
9443 
9444   return false;
9445 }
9446 
9447 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9448   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9449   assert(DFK && "not a defaultable function");
9450   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9451 
9452   if (DFK.isSpecialMember()) {
9453     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9454                               nullptr, /*Diagnose=*/true);
9455   } else {
9456     DefaultedComparisonAnalyzer(
9457         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9458         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9459         .visit();
9460   }
9461 }
9462 
9463 /// Perform lookup for a special member of the specified kind, and determine
9464 /// whether it is trivial. If the triviality can be determined without the
9465 /// lookup, skip it. This is intended for use when determining whether a
9466 /// special member of a containing object is trivial, and thus does not ever
9467 /// perform overload resolution for default constructors.
9468 ///
9469 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9470 /// member that was most likely to be intended to be trivial, if any.
9471 ///
9472 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9473 /// determine whether the special member is trivial.
9474 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9475                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9476                                      bool ConstRHS,
9477                                      Sema::TrivialABIHandling TAH,
9478                                      CXXMethodDecl **Selected) {
9479   if (Selected)
9480     *Selected = nullptr;
9481 
9482   switch (CSM) {
9483   case Sema::CXXInvalid:
9484     llvm_unreachable("not a special member");
9485 
9486   case Sema::CXXDefaultConstructor:
9487     // C++11 [class.ctor]p5:
9488     //   A default constructor is trivial if:
9489     //    - all the [direct subobjects] have trivial default constructors
9490     //
9491     // Note, no overload resolution is performed in this case.
9492     if (RD->hasTrivialDefaultConstructor())
9493       return true;
9494 
9495     if (Selected) {
9496       // If there's a default constructor which could have been trivial, dig it
9497       // out. Otherwise, if there's any user-provided default constructor, point
9498       // to that as an example of why there's not a trivial one.
9499       CXXConstructorDecl *DefCtor = nullptr;
9500       if (RD->needsImplicitDefaultConstructor())
9501         S.DeclareImplicitDefaultConstructor(RD);
9502       for (auto *CI : RD->ctors()) {
9503         if (!CI->isDefaultConstructor())
9504           continue;
9505         DefCtor = CI;
9506         if (!DefCtor->isUserProvided())
9507           break;
9508       }
9509 
9510       *Selected = DefCtor;
9511     }
9512 
9513     return false;
9514 
9515   case Sema::CXXDestructor:
9516     // C++11 [class.dtor]p5:
9517     //   A destructor is trivial if:
9518     //    - all the direct [subobjects] have trivial destructors
9519     if (RD->hasTrivialDestructor() ||
9520         (TAH == Sema::TAH_ConsiderTrivialABI &&
9521          RD->hasTrivialDestructorForCall()))
9522       return true;
9523 
9524     if (Selected) {
9525       if (RD->needsImplicitDestructor())
9526         S.DeclareImplicitDestructor(RD);
9527       *Selected = RD->getDestructor();
9528     }
9529 
9530     return false;
9531 
9532   case Sema::CXXCopyConstructor:
9533     // C++11 [class.copy]p12:
9534     //   A copy constructor is trivial if:
9535     //    - the constructor selected to copy each direct [subobject] is trivial
9536     if (RD->hasTrivialCopyConstructor() ||
9537         (TAH == Sema::TAH_ConsiderTrivialABI &&
9538          RD->hasTrivialCopyConstructorForCall())) {
9539       if (Quals == Qualifiers::Const)
9540         // We must either select the trivial copy constructor or reach an
9541         // ambiguity; no need to actually perform overload resolution.
9542         return true;
9543     } else if (!Selected) {
9544       return false;
9545     }
9546     // In C++98, we are not supposed to perform overload resolution here, but we
9547     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9548     // cases like B as having a non-trivial copy constructor:
9549     //   struct A { template<typename T> A(T&); };
9550     //   struct B { mutable A a; };
9551     goto NeedOverloadResolution;
9552 
9553   case Sema::CXXCopyAssignment:
9554     // C++11 [class.copy]p25:
9555     //   A copy assignment operator is trivial if:
9556     //    - the assignment operator selected to copy each direct [subobject] is
9557     //      trivial
9558     if (RD->hasTrivialCopyAssignment()) {
9559       if (Quals == Qualifiers::Const)
9560         return true;
9561     } else if (!Selected) {
9562       return false;
9563     }
9564     // In C++98, we are not supposed to perform overload resolution here, but we
9565     // treat that as a language defect.
9566     goto NeedOverloadResolution;
9567 
9568   case Sema::CXXMoveConstructor:
9569   case Sema::CXXMoveAssignment:
9570   NeedOverloadResolution:
9571     Sema::SpecialMemberOverloadResult SMOR =
9572         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9573 
9574     // The standard doesn't describe how to behave if the lookup is ambiguous.
9575     // We treat it as not making the member non-trivial, just like the standard
9576     // mandates for the default constructor. This should rarely matter, because
9577     // the member will also be deleted.
9578     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9579       return true;
9580 
9581     if (!SMOR.getMethod()) {
9582       assert(SMOR.getKind() ==
9583              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9584       return false;
9585     }
9586 
9587     // We deliberately don't check if we found a deleted special member. We're
9588     // not supposed to!
9589     if (Selected)
9590       *Selected = SMOR.getMethod();
9591 
9592     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9593         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9594       return SMOR.getMethod()->isTrivialForCall();
9595     return SMOR.getMethod()->isTrivial();
9596   }
9597 
9598   llvm_unreachable("unknown special method kind");
9599 }
9600 
9601 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9602   for (auto *CI : RD->ctors())
9603     if (!CI->isImplicit())
9604       return CI;
9605 
9606   // Look for constructor templates.
9607   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9608   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9609     if (CXXConstructorDecl *CD =
9610           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9611       return CD;
9612   }
9613 
9614   return nullptr;
9615 }
9616 
9617 /// The kind of subobject we are checking for triviality. The values of this
9618 /// enumeration are used in diagnostics.
9619 enum TrivialSubobjectKind {
9620   /// The subobject is a base class.
9621   TSK_BaseClass,
9622   /// The subobject is a non-static data member.
9623   TSK_Field,
9624   /// The object is actually the complete object.
9625   TSK_CompleteObject
9626 };
9627 
9628 /// Check whether the special member selected for a given type would be trivial.
9629 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9630                                       QualType SubType, bool ConstRHS,
9631                                       Sema::CXXSpecialMember CSM,
9632                                       TrivialSubobjectKind Kind,
9633                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9634   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9635   if (!SubRD)
9636     return true;
9637 
9638   CXXMethodDecl *Selected;
9639   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9640                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9641     return true;
9642 
9643   if (Diagnose) {
9644     if (ConstRHS)
9645       SubType.addConst();
9646 
9647     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9648       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9649         << Kind << SubType.getUnqualifiedType();
9650       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9651         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9652     } else if (!Selected)
9653       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9654         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9655     else if (Selected->isUserProvided()) {
9656       if (Kind == TSK_CompleteObject)
9657         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9658           << Kind << SubType.getUnqualifiedType() << CSM;
9659       else {
9660         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9661           << Kind << SubType.getUnqualifiedType() << CSM;
9662         S.Diag(Selected->getLocation(), diag::note_declared_at);
9663       }
9664     } else {
9665       if (Kind != TSK_CompleteObject)
9666         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9667           << Kind << SubType.getUnqualifiedType() << CSM;
9668 
9669       // Explain why the defaulted or deleted special member isn't trivial.
9670       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9671                                Diagnose);
9672     }
9673   }
9674 
9675   return false;
9676 }
9677 
9678 /// Check whether the members of a class type allow a special member to be
9679 /// trivial.
9680 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9681                                      Sema::CXXSpecialMember CSM,
9682                                      bool ConstArg,
9683                                      Sema::TrivialABIHandling TAH,
9684                                      bool Diagnose) {
9685   for (const auto *FI : RD->fields()) {
9686     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9687       continue;
9688 
9689     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9690 
9691     // Pretend anonymous struct or union members are members of this class.
9692     if (FI->isAnonymousStructOrUnion()) {
9693       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9694                                     CSM, ConstArg, TAH, Diagnose))
9695         return false;
9696       continue;
9697     }
9698 
9699     // C++11 [class.ctor]p5:
9700     //   A default constructor is trivial if [...]
9701     //    -- no non-static data member of its class has a
9702     //       brace-or-equal-initializer
9703     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9704       if (Diagnose)
9705         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9706             << FI;
9707       return false;
9708     }
9709 
9710     // Objective C ARC 4.3.5:
9711     //   [...] nontrivally ownership-qualified types are [...] not trivially
9712     //   default constructible, copy constructible, move constructible, copy
9713     //   assignable, move assignable, or destructible [...]
9714     if (FieldType.hasNonTrivialObjCLifetime()) {
9715       if (Diagnose)
9716         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9717           << RD << FieldType.getObjCLifetime();
9718       return false;
9719     }
9720 
9721     bool ConstRHS = ConstArg && !FI->isMutable();
9722     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9723                                    CSM, TSK_Field, TAH, Diagnose))
9724       return false;
9725   }
9726 
9727   return true;
9728 }
9729 
9730 /// Diagnose why the specified class does not have a trivial special member of
9731 /// the given kind.
9732 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9733   QualType Ty = Context.getRecordType(RD);
9734 
9735   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9736   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9737                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9738                             /*Diagnose*/true);
9739 }
9740 
9741 /// Determine whether a defaulted or deleted special member function is trivial,
9742 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9743 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9744 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9745                                   TrivialABIHandling TAH, bool Diagnose) {
9746   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9747 
9748   CXXRecordDecl *RD = MD->getParent();
9749 
9750   bool ConstArg = false;
9751 
9752   // C++11 [class.copy]p12, p25: [DR1593]
9753   //   A [special member] is trivial if [...] its parameter-type-list is
9754   //   equivalent to the parameter-type-list of an implicit declaration [...]
9755   switch (CSM) {
9756   case CXXDefaultConstructor:
9757   case CXXDestructor:
9758     // Trivial default constructors and destructors cannot have parameters.
9759     break;
9760 
9761   case CXXCopyConstructor:
9762   case CXXCopyAssignment: {
9763     // Trivial copy operations always have const, non-volatile parameter types.
9764     ConstArg = true;
9765     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9766     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9767     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9768       if (Diagnose)
9769         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9770           << Param0->getSourceRange() << Param0->getType()
9771           << Context.getLValueReferenceType(
9772                Context.getRecordType(RD).withConst());
9773       return false;
9774     }
9775     break;
9776   }
9777 
9778   case CXXMoveConstructor:
9779   case CXXMoveAssignment: {
9780     // Trivial move operations always have non-cv-qualified parameters.
9781     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9782     const RValueReferenceType *RT =
9783       Param0->getType()->getAs<RValueReferenceType>();
9784     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9785       if (Diagnose)
9786         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9787           << Param0->getSourceRange() << Param0->getType()
9788           << Context.getRValueReferenceType(Context.getRecordType(RD));
9789       return false;
9790     }
9791     break;
9792   }
9793 
9794   case CXXInvalid:
9795     llvm_unreachable("not a special member");
9796   }
9797 
9798   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9799     if (Diagnose)
9800       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9801            diag::note_nontrivial_default_arg)
9802         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9803     return false;
9804   }
9805   if (MD->isVariadic()) {
9806     if (Diagnose)
9807       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9808     return false;
9809   }
9810 
9811   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9812   //   A copy/move [constructor or assignment operator] is trivial if
9813   //    -- the [member] selected to copy/move each direct base class subobject
9814   //       is trivial
9815   //
9816   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9817   //   A [default constructor or destructor] is trivial if
9818   //    -- all the direct base classes have trivial [default constructors or
9819   //       destructors]
9820   for (const auto &BI : RD->bases())
9821     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9822                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9823       return false;
9824 
9825   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9826   //   A copy/move [constructor or assignment operator] for a class X is
9827   //   trivial if
9828   //    -- for each non-static data member of X that is of class type (or array
9829   //       thereof), the constructor selected to copy/move that member is
9830   //       trivial
9831   //
9832   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9833   //   A [default constructor or destructor] is trivial if
9834   //    -- for all of the non-static data members of its class that are of class
9835   //       type (or array thereof), each such class has a trivial [default
9836   //       constructor or destructor]
9837   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9838     return false;
9839 
9840   // C++11 [class.dtor]p5:
9841   //   A destructor is trivial if [...]
9842   //    -- the destructor is not virtual
9843   if (CSM == CXXDestructor && MD->isVirtual()) {
9844     if (Diagnose)
9845       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9846     return false;
9847   }
9848 
9849   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9850   //   A [special member] for class X is trivial if [...]
9851   //    -- class X has no virtual functions and no virtual base classes
9852   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9853     if (!Diagnose)
9854       return false;
9855 
9856     if (RD->getNumVBases()) {
9857       // Check for virtual bases. We already know that the corresponding
9858       // member in all bases is trivial, so vbases must all be direct.
9859       CXXBaseSpecifier &BS = *RD->vbases_begin();
9860       assert(BS.isVirtual());
9861       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9862       return false;
9863     }
9864 
9865     // Must have a virtual method.
9866     for (const auto *MI : RD->methods()) {
9867       if (MI->isVirtual()) {
9868         SourceLocation MLoc = MI->getBeginLoc();
9869         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9870         return false;
9871       }
9872     }
9873 
9874     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9875   }
9876 
9877   // Looks like it's trivial!
9878   return true;
9879 }
9880 
9881 namespace {
9882 struct FindHiddenVirtualMethod {
9883   Sema *S;
9884   CXXMethodDecl *Method;
9885   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9886   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9887 
9888 private:
9889   /// Check whether any most overridden method from MD in Methods
9890   static bool CheckMostOverridenMethods(
9891       const CXXMethodDecl *MD,
9892       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9893     if (MD->size_overridden_methods() == 0)
9894       return Methods.count(MD->getCanonicalDecl());
9895     for (const CXXMethodDecl *O : MD->overridden_methods())
9896       if (CheckMostOverridenMethods(O, Methods))
9897         return true;
9898     return false;
9899   }
9900 
9901 public:
9902   /// Member lookup function that determines whether a given C++
9903   /// method overloads virtual methods in a base class without overriding any,
9904   /// to be used with CXXRecordDecl::lookupInBases().
9905   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9906     RecordDecl *BaseRecord =
9907         Specifier->getType()->castAs<RecordType>()->getDecl();
9908 
9909     DeclarationName Name = Method->getDeclName();
9910     assert(Name.getNameKind() == DeclarationName::Identifier);
9911 
9912     bool foundSameNameMethod = false;
9913     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9914     for (Path.Decls = BaseRecord->lookup(Name).begin();
9915          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9916       NamedDecl *D = *Path.Decls;
9917       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9918         MD = MD->getCanonicalDecl();
9919         foundSameNameMethod = true;
9920         // Interested only in hidden virtual methods.
9921         if (!MD->isVirtual())
9922           continue;
9923         // If the method we are checking overrides a method from its base
9924         // don't warn about the other overloaded methods. Clang deviates from
9925         // GCC by only diagnosing overloads of inherited virtual functions that
9926         // do not override any other virtual functions in the base. GCC's
9927         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9928         // function from a base class. These cases may be better served by a
9929         // warning (not specific to virtual functions) on call sites when the
9930         // call would select a different function from the base class, were it
9931         // visible.
9932         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9933         if (!S->IsOverload(Method, MD, false))
9934           return true;
9935         // Collect the overload only if its hidden.
9936         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9937           overloadedMethods.push_back(MD);
9938       }
9939     }
9940 
9941     if (foundSameNameMethod)
9942       OverloadedMethods.append(overloadedMethods.begin(),
9943                                overloadedMethods.end());
9944     return foundSameNameMethod;
9945   }
9946 };
9947 } // end anonymous namespace
9948 
9949 /// Add the most overridden methods from MD to Methods
9950 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9951                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9952   if (MD->size_overridden_methods() == 0)
9953     Methods.insert(MD->getCanonicalDecl());
9954   else
9955     for (const CXXMethodDecl *O : MD->overridden_methods())
9956       AddMostOverridenMethods(O, Methods);
9957 }
9958 
9959 /// Check if a method overloads virtual methods in a base class without
9960 /// overriding any.
9961 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9962                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9963   if (!MD->getDeclName().isIdentifier())
9964     return;
9965 
9966   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9967                      /*bool RecordPaths=*/false,
9968                      /*bool DetectVirtual=*/false);
9969   FindHiddenVirtualMethod FHVM;
9970   FHVM.Method = MD;
9971   FHVM.S = this;
9972 
9973   // Keep the base methods that were overridden or introduced in the subclass
9974   // by 'using' in a set. A base method not in this set is hidden.
9975   CXXRecordDecl *DC = MD->getParent();
9976   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9977   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9978     NamedDecl *ND = *I;
9979     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9980       ND = shad->getTargetDecl();
9981     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9982       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9983   }
9984 
9985   if (DC->lookupInBases(FHVM, Paths))
9986     OverloadedMethods = FHVM.OverloadedMethods;
9987 }
9988 
9989 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9990                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9991   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9992     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9993     PartialDiagnostic PD = PDiag(
9994          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9995     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9996     Diag(overloadedMD->getLocation(), PD);
9997   }
9998 }
9999 
10000 /// Diagnose methods which overload virtual methods in a base class
10001 /// without overriding any.
10002 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10003   if (MD->isInvalidDecl())
10004     return;
10005 
10006   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10007     return;
10008 
10009   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10010   FindHiddenVirtualMethods(MD, OverloadedMethods);
10011   if (!OverloadedMethods.empty()) {
10012     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10013       << MD << (OverloadedMethods.size() > 1);
10014 
10015     NoteHiddenVirtualMethods(MD, OverloadedMethods);
10016   }
10017 }
10018 
10019 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10020   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10021     // No diagnostics if this is a template instantiation.
10022     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10023       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10024            diag::ext_cannot_use_trivial_abi) << &RD;
10025       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10026            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10027     }
10028     RD.dropAttr<TrivialABIAttr>();
10029   };
10030 
10031   // Ill-formed if the copy and move constructors are deleted.
10032   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10033     // If the type is dependent, then assume it might have
10034     // implicit copy or move ctor because we won't know yet at this point.
10035     if (RD.isDependentType())
10036       return true;
10037     if (RD.needsImplicitCopyConstructor() &&
10038         !RD.defaultedCopyConstructorIsDeleted())
10039       return true;
10040     if (RD.needsImplicitMoveConstructor() &&
10041         !RD.defaultedMoveConstructorIsDeleted())
10042       return true;
10043     for (const CXXConstructorDecl *CD : RD.ctors())
10044       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10045         return true;
10046     return false;
10047   };
10048 
10049   if (!HasNonDeletedCopyOrMoveConstructor()) {
10050     PrintDiagAndRemoveAttr(0);
10051     return;
10052   }
10053 
10054   // Ill-formed if the struct has virtual functions.
10055   if (RD.isPolymorphic()) {
10056     PrintDiagAndRemoveAttr(1);
10057     return;
10058   }
10059 
10060   for (const auto &B : RD.bases()) {
10061     // Ill-formed if the base class is non-trivial for the purpose of calls or a
10062     // virtual base.
10063     if (!B.getType()->isDependentType() &&
10064         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10065       PrintDiagAndRemoveAttr(2);
10066       return;
10067     }
10068 
10069     if (B.isVirtual()) {
10070       PrintDiagAndRemoveAttr(3);
10071       return;
10072     }
10073   }
10074 
10075   for (const auto *FD : RD.fields()) {
10076     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10077     // non-trivial for the purpose of calls.
10078     QualType FT = FD->getType();
10079     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10080       PrintDiagAndRemoveAttr(4);
10081       return;
10082     }
10083 
10084     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10085       if (!RT->isDependentType() &&
10086           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10087         PrintDiagAndRemoveAttr(5);
10088         return;
10089       }
10090   }
10091 }
10092 
10093 void Sema::ActOnFinishCXXMemberSpecification(
10094     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10095     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10096   if (!TagDecl)
10097     return;
10098 
10099   AdjustDeclIfTemplate(TagDecl);
10100 
10101   for (const ParsedAttr &AL : AttrList) {
10102     if (AL.getKind() != ParsedAttr::AT_Visibility)
10103       continue;
10104     AL.setInvalid();
10105     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10106   }
10107 
10108   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
10109               // strict aliasing violation!
10110               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
10111               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
10112 
10113   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10114 }
10115 
10116 /// Find the equality comparison functions that should be implicitly declared
10117 /// in a given class definition, per C++2a [class.compare.default]p3.
10118 static void findImplicitlyDeclaredEqualityComparisons(
10119     ASTContext &Ctx, CXXRecordDecl *RD,
10120     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10121   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10122   if (!RD->lookup(EqEq).empty())
10123     // Member operator== explicitly declared: no implicit operator==s.
10124     return;
10125 
10126   // Traverse friends looking for an '==' or a '<=>'.
10127   for (FriendDecl *Friend : RD->friends()) {
10128     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10129     if (!FD) continue;
10130 
10131     if (FD->getOverloadedOperator() == OO_EqualEqual) {
10132       // Friend operator== explicitly declared: no implicit operator==s.
10133       Spaceships.clear();
10134       return;
10135     }
10136 
10137     if (FD->getOverloadedOperator() == OO_Spaceship &&
10138         FD->isExplicitlyDefaulted())
10139       Spaceships.push_back(FD);
10140   }
10141 
10142   // Look for members named 'operator<=>'.
10143   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10144   for (NamedDecl *ND : RD->lookup(Cmp)) {
10145     // Note that we could find a non-function here (either a function template
10146     // or a using-declaration). Neither case results in an implicit
10147     // 'operator=='.
10148     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10149       if (FD->isExplicitlyDefaulted())
10150         Spaceships.push_back(FD);
10151   }
10152 }
10153 
10154 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10155 /// special functions, such as the default constructor, copy
10156 /// constructor, or destructor, to the given C++ class (C++
10157 /// [special]p1).  This routine can only be executed just before the
10158 /// definition of the class is complete.
10159 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10160   // Don't add implicit special members to templated classes.
10161   // FIXME: This means unqualified lookups for 'operator=' within a class
10162   // template don't work properly.
10163   if (!ClassDecl->isDependentType()) {
10164     if (ClassDecl->needsImplicitDefaultConstructor()) {
10165       ++getASTContext().NumImplicitDefaultConstructors;
10166 
10167       if (ClassDecl->hasInheritedConstructor())
10168         DeclareImplicitDefaultConstructor(ClassDecl);
10169     }
10170 
10171     if (ClassDecl->needsImplicitCopyConstructor()) {
10172       ++getASTContext().NumImplicitCopyConstructors;
10173 
10174       // If the properties or semantics of the copy constructor couldn't be
10175       // determined while the class was being declared, force a declaration
10176       // of it now.
10177       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10178           ClassDecl->hasInheritedConstructor())
10179         DeclareImplicitCopyConstructor(ClassDecl);
10180       // For the MS ABI we need to know whether the copy ctor is deleted. A
10181       // prerequisite for deleting the implicit copy ctor is that the class has
10182       // a move ctor or move assignment that is either user-declared or whose
10183       // semantics are inherited from a subobject. FIXME: We should provide a
10184       // more direct way for CodeGen to ask whether the constructor was deleted.
10185       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10186                (ClassDecl->hasUserDeclaredMoveConstructor() ||
10187                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10188                 ClassDecl->hasUserDeclaredMoveAssignment() ||
10189                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10190         DeclareImplicitCopyConstructor(ClassDecl);
10191     }
10192 
10193     if (getLangOpts().CPlusPlus11 &&
10194         ClassDecl->needsImplicitMoveConstructor()) {
10195       ++getASTContext().NumImplicitMoveConstructors;
10196 
10197       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10198           ClassDecl->hasInheritedConstructor())
10199         DeclareImplicitMoveConstructor(ClassDecl);
10200     }
10201 
10202     if (ClassDecl->needsImplicitCopyAssignment()) {
10203       ++getASTContext().NumImplicitCopyAssignmentOperators;
10204 
10205       // If we have a dynamic class, then the copy assignment operator may be
10206       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10207       // it shows up in the right place in the vtable and that we diagnose
10208       // problems with the implicit exception specification.
10209       if (ClassDecl->isDynamicClass() ||
10210           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10211           ClassDecl->hasInheritedAssignment())
10212         DeclareImplicitCopyAssignment(ClassDecl);
10213     }
10214 
10215     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10216       ++getASTContext().NumImplicitMoveAssignmentOperators;
10217 
10218       // Likewise for the move assignment operator.
10219       if (ClassDecl->isDynamicClass() ||
10220           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10221           ClassDecl->hasInheritedAssignment())
10222         DeclareImplicitMoveAssignment(ClassDecl);
10223     }
10224 
10225     if (ClassDecl->needsImplicitDestructor()) {
10226       ++getASTContext().NumImplicitDestructors;
10227 
10228       // If we have a dynamic class, then the destructor may be virtual, so we
10229       // have to declare the destructor immediately. This ensures that, e.g., it
10230       // shows up in the right place in the vtable and that we diagnose problems
10231       // with the implicit exception specification.
10232       if (ClassDecl->isDynamicClass() ||
10233           ClassDecl->needsOverloadResolutionForDestructor())
10234         DeclareImplicitDestructor(ClassDecl);
10235     }
10236   }
10237 
10238   // C++2a [class.compare.default]p3:
10239   //   If the member-specification does not explicitly declare any member or
10240   //   friend named operator==, an == operator function is declared implicitly
10241   //   for each defaulted three-way comparison operator function defined in
10242   //   the member-specification
10243   // FIXME: Consider doing this lazily.
10244   // We do this during the initial parse for a class template, not during
10245   // instantiation, so that we can handle unqualified lookups for 'operator=='
10246   // when parsing the template.
10247   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10248     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10249     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10250                                               DefaultedSpaceships);
10251     for (auto *FD : DefaultedSpaceships)
10252       DeclareImplicitEqualityComparison(ClassDecl, FD);
10253   }
10254 }
10255 
10256 unsigned
10257 Sema::ActOnReenterTemplateScope(Decl *D,
10258                                 llvm::function_ref<Scope *()> EnterScope) {
10259   if (!D)
10260     return 0;
10261   AdjustDeclIfTemplate(D);
10262 
10263   // In order to get name lookup right, reenter template scopes in order from
10264   // outermost to innermost.
10265   SmallVector<TemplateParameterList *, 4> ParameterLists;
10266   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10267 
10268   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10269     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10270       ParameterLists.push_back(DD->getTemplateParameterList(i));
10271 
10272     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10273       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10274         ParameterLists.push_back(FTD->getTemplateParameters());
10275     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10276       LookupDC = VD->getDeclContext();
10277 
10278       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10279         ParameterLists.push_back(VTD->getTemplateParameters());
10280       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10281         ParameterLists.push_back(PSD->getTemplateParameters());
10282     }
10283   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10284     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10285       ParameterLists.push_back(TD->getTemplateParameterList(i));
10286 
10287     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10288       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10289         ParameterLists.push_back(CTD->getTemplateParameters());
10290       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10291         ParameterLists.push_back(PSD->getTemplateParameters());
10292     }
10293   }
10294   // FIXME: Alias declarations and concepts.
10295 
10296   unsigned Count = 0;
10297   Scope *InnermostTemplateScope = nullptr;
10298   for (TemplateParameterList *Params : ParameterLists) {
10299     // Ignore explicit specializations; they don't contribute to the template
10300     // depth.
10301     if (Params->size() == 0)
10302       continue;
10303 
10304     InnermostTemplateScope = EnterScope();
10305     for (NamedDecl *Param : *Params) {
10306       if (Param->getDeclName()) {
10307         InnermostTemplateScope->AddDecl(Param);
10308         IdResolver.AddDecl(Param);
10309       }
10310     }
10311     ++Count;
10312   }
10313 
10314   // Associate the new template scopes with the corresponding entities.
10315   if (InnermostTemplateScope) {
10316     assert(LookupDC && "no enclosing DeclContext for template lookup");
10317     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10318   }
10319 
10320   return Count;
10321 }
10322 
10323 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10324   if (!RecordD) return;
10325   AdjustDeclIfTemplate(RecordD);
10326   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10327   PushDeclContext(S, Record);
10328 }
10329 
10330 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10331   if (!RecordD) return;
10332   PopDeclContext();
10333 }
10334 
10335 /// This is used to implement the constant expression evaluation part of the
10336 /// attribute enable_if extension. There is nothing in standard C++ which would
10337 /// require reentering parameters.
10338 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10339   if (!Param)
10340     return;
10341 
10342   S->AddDecl(Param);
10343   if (Param->getDeclName())
10344     IdResolver.AddDecl(Param);
10345 }
10346 
10347 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10348 /// parsing a top-level (non-nested) C++ class, and we are now
10349 /// parsing those parts of the given Method declaration that could
10350 /// not be parsed earlier (C++ [class.mem]p2), such as default
10351 /// arguments. This action should enter the scope of the given
10352 /// Method declaration as if we had just parsed the qualified method
10353 /// name. However, it should not bring the parameters into scope;
10354 /// that will be performed by ActOnDelayedCXXMethodParameter.
10355 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10356 }
10357 
10358 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10359 /// C++ method declaration. We're (re-)introducing the given
10360 /// function parameter into scope for use in parsing later parts of
10361 /// the method declaration. For example, we could see an
10362 /// ActOnParamDefaultArgument event for this parameter.
10363 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10364   if (!ParamD)
10365     return;
10366 
10367   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10368 
10369   S->AddDecl(Param);
10370   if (Param->getDeclName())
10371     IdResolver.AddDecl(Param);
10372 }
10373 
10374 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10375 /// processing the delayed method declaration for Method. The method
10376 /// declaration is now considered finished. There may be a separate
10377 /// ActOnStartOfFunctionDef action later (not necessarily
10378 /// immediately!) for this method, if it was also defined inside the
10379 /// class body.
10380 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10381   if (!MethodD)
10382     return;
10383 
10384   AdjustDeclIfTemplate(MethodD);
10385 
10386   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10387 
10388   // Now that we have our default arguments, check the constructor
10389   // again. It could produce additional diagnostics or affect whether
10390   // the class has implicitly-declared destructors, among other
10391   // things.
10392   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10393     CheckConstructor(Constructor);
10394 
10395   // Check the default arguments, which we may have added.
10396   if (!Method->isInvalidDecl())
10397     CheckCXXDefaultArguments(Method);
10398 }
10399 
10400 // Emit the given diagnostic for each non-address-space qualifier.
10401 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10402 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10403   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10404   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10405     bool DiagOccured = false;
10406     FTI.MethodQualifiers->forEachQualifier(
10407         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10408                                    SourceLocation SL) {
10409           // This diagnostic should be emitted on any qualifier except an addr
10410           // space qualifier. However, forEachQualifier currently doesn't visit
10411           // addr space qualifiers, so there's no way to write this condition
10412           // right now; we just diagnose on everything.
10413           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10414           DiagOccured = true;
10415         });
10416     if (DiagOccured)
10417       D.setInvalidType();
10418   }
10419 }
10420 
10421 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10422 /// the well-formedness of the constructor declarator @p D with type @p
10423 /// R. If there are any errors in the declarator, this routine will
10424 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10425 /// will be updated to reflect a well-formed type for the constructor and
10426 /// returned.
10427 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10428                                           StorageClass &SC) {
10429   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10430 
10431   // C++ [class.ctor]p3:
10432   //   A constructor shall not be virtual (10.3) or static (9.4). A
10433   //   constructor can be invoked for a const, volatile or const
10434   //   volatile object. A constructor shall not be declared const,
10435   //   volatile, or const volatile (9.3.2).
10436   if (isVirtual) {
10437     if (!D.isInvalidType())
10438       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10439         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10440         << SourceRange(D.getIdentifierLoc());
10441     D.setInvalidType();
10442   }
10443   if (SC == SC_Static) {
10444     if (!D.isInvalidType())
10445       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10446         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10447         << SourceRange(D.getIdentifierLoc());
10448     D.setInvalidType();
10449     SC = SC_None;
10450   }
10451 
10452   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10453     diagnoseIgnoredQualifiers(
10454         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10455         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10456         D.getDeclSpec().getRestrictSpecLoc(),
10457         D.getDeclSpec().getAtomicSpecLoc());
10458     D.setInvalidType();
10459   }
10460 
10461   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10462 
10463   // C++0x [class.ctor]p4:
10464   //   A constructor shall not be declared with a ref-qualifier.
10465   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10466   if (FTI.hasRefQualifier()) {
10467     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10468       << FTI.RefQualifierIsLValueRef
10469       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10470     D.setInvalidType();
10471   }
10472 
10473   // Rebuild the function type "R" without any type qualifiers (in
10474   // case any of the errors above fired) and with "void" as the
10475   // return type, since constructors don't have return types.
10476   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10477   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10478     return R;
10479 
10480   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10481   EPI.TypeQuals = Qualifiers();
10482   EPI.RefQualifier = RQ_None;
10483 
10484   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10485 }
10486 
10487 /// CheckConstructor - Checks a fully-formed constructor for
10488 /// well-formedness, issuing any diagnostics required. Returns true if
10489 /// the constructor declarator is invalid.
10490 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10491   CXXRecordDecl *ClassDecl
10492     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10493   if (!ClassDecl)
10494     return Constructor->setInvalidDecl();
10495 
10496   // C++ [class.copy]p3:
10497   //   A declaration of a constructor for a class X is ill-formed if
10498   //   its first parameter is of type (optionally cv-qualified) X and
10499   //   either there are no other parameters or else all other
10500   //   parameters have default arguments.
10501   if (!Constructor->isInvalidDecl() &&
10502       Constructor->hasOneParamOrDefaultArgs() &&
10503       Constructor->getTemplateSpecializationKind() !=
10504           TSK_ImplicitInstantiation) {
10505     QualType ParamType = Constructor->getParamDecl(0)->getType();
10506     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10507     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10508       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10509       const char *ConstRef
10510         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10511                                                         : " const &";
10512       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10513         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10514 
10515       // FIXME: Rather that making the constructor invalid, we should endeavor
10516       // to fix the type.
10517       Constructor->setInvalidDecl();
10518     }
10519   }
10520 }
10521 
10522 /// CheckDestructor - Checks a fully-formed destructor definition for
10523 /// well-formedness, issuing any diagnostics required.  Returns true
10524 /// on error.
10525 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10526   CXXRecordDecl *RD = Destructor->getParent();
10527 
10528   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10529     SourceLocation Loc;
10530 
10531     if (!Destructor->isImplicit())
10532       Loc = Destructor->getLocation();
10533     else
10534       Loc = RD->getLocation();
10535 
10536     // If we have a virtual destructor, look up the deallocation function
10537     if (FunctionDecl *OperatorDelete =
10538             FindDeallocationFunctionForDestructor(Loc, RD)) {
10539       Expr *ThisArg = nullptr;
10540 
10541       // If the notional 'delete this' expression requires a non-trivial
10542       // conversion from 'this' to the type of a destroying operator delete's
10543       // first parameter, perform that conversion now.
10544       if (OperatorDelete->isDestroyingOperatorDelete()) {
10545         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10546         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10547           // C++ [class.dtor]p13:
10548           //   ... as if for the expression 'delete this' appearing in a
10549           //   non-virtual destructor of the destructor's class.
10550           ContextRAII SwitchContext(*this, Destructor);
10551           ExprResult This =
10552               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10553           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10554           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10555           if (This.isInvalid()) {
10556             // FIXME: Register this as a context note so that it comes out
10557             // in the right order.
10558             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10559             return true;
10560           }
10561           ThisArg = This.get();
10562         }
10563       }
10564 
10565       DiagnoseUseOfDecl(OperatorDelete, Loc);
10566       MarkFunctionReferenced(Loc, OperatorDelete);
10567       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10568     }
10569   }
10570 
10571   return false;
10572 }
10573 
10574 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10575 /// the well-formednes of the destructor declarator @p D with type @p
10576 /// R. If there are any errors in the declarator, this routine will
10577 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10578 /// will be updated to reflect a well-formed type for the destructor and
10579 /// returned.
10580 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10581                                          StorageClass& SC) {
10582   // C++ [class.dtor]p1:
10583   //   [...] A typedef-name that names a class is a class-name
10584   //   (7.1.3); however, a typedef-name that names a class shall not
10585   //   be used as the identifier in the declarator for a destructor
10586   //   declaration.
10587   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10588   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10589     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10590       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10591   else if (const TemplateSpecializationType *TST =
10592              DeclaratorType->getAs<TemplateSpecializationType>())
10593     if (TST->isTypeAlias())
10594       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10595         << DeclaratorType << 1;
10596 
10597   // C++ [class.dtor]p2:
10598   //   A destructor is used to destroy objects of its class type. A
10599   //   destructor takes no parameters, and no return type can be
10600   //   specified for it (not even void). The address of a destructor
10601   //   shall not be taken. A destructor shall not be static. A
10602   //   destructor can be invoked for a const, volatile or const
10603   //   volatile object. A destructor shall not be declared const,
10604   //   volatile or const volatile (9.3.2).
10605   if (SC == SC_Static) {
10606     if (!D.isInvalidType())
10607       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10608         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10609         << SourceRange(D.getIdentifierLoc())
10610         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10611 
10612     SC = SC_None;
10613   }
10614   if (!D.isInvalidType()) {
10615     // Destructors don't have return types, but the parser will
10616     // happily parse something like:
10617     //
10618     //   class X {
10619     //     float ~X();
10620     //   };
10621     //
10622     // The return type will be eliminated later.
10623     if (D.getDeclSpec().hasTypeSpecifier())
10624       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10625         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10626         << SourceRange(D.getIdentifierLoc());
10627     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10628       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10629                                 SourceLocation(),
10630                                 D.getDeclSpec().getConstSpecLoc(),
10631                                 D.getDeclSpec().getVolatileSpecLoc(),
10632                                 D.getDeclSpec().getRestrictSpecLoc(),
10633                                 D.getDeclSpec().getAtomicSpecLoc());
10634       D.setInvalidType();
10635     }
10636   }
10637 
10638   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10639 
10640   // C++0x [class.dtor]p2:
10641   //   A destructor shall not be declared with a ref-qualifier.
10642   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10643   if (FTI.hasRefQualifier()) {
10644     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10645       << FTI.RefQualifierIsLValueRef
10646       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10647     D.setInvalidType();
10648   }
10649 
10650   // Make sure we don't have any parameters.
10651   if (FTIHasNonVoidParameters(FTI)) {
10652     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10653 
10654     // Delete the parameters.
10655     FTI.freeParams();
10656     D.setInvalidType();
10657   }
10658 
10659   // Make sure the destructor isn't variadic.
10660   if (FTI.isVariadic) {
10661     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10662     D.setInvalidType();
10663   }
10664 
10665   // Rebuild the function type "R" without any type qualifiers or
10666   // parameters (in case any of the errors above fired) and with
10667   // "void" as the return type, since destructors don't have return
10668   // types.
10669   if (!D.isInvalidType())
10670     return R;
10671 
10672   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10673   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10674   EPI.Variadic = false;
10675   EPI.TypeQuals = Qualifiers();
10676   EPI.RefQualifier = RQ_None;
10677   return Context.getFunctionType(Context.VoidTy, None, EPI);
10678 }
10679 
10680 static void extendLeft(SourceRange &R, SourceRange Before) {
10681   if (Before.isInvalid())
10682     return;
10683   R.setBegin(Before.getBegin());
10684   if (R.getEnd().isInvalid())
10685     R.setEnd(Before.getEnd());
10686 }
10687 
10688 static void extendRight(SourceRange &R, SourceRange After) {
10689   if (After.isInvalid())
10690     return;
10691   if (R.getBegin().isInvalid())
10692     R.setBegin(After.getBegin());
10693   R.setEnd(After.getEnd());
10694 }
10695 
10696 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10697 /// well-formednes of the conversion function declarator @p D with
10698 /// type @p R. If there are any errors in the declarator, this routine
10699 /// will emit diagnostics and return true. Otherwise, it will return
10700 /// false. Either way, the type @p R will be updated to reflect a
10701 /// well-formed type for the conversion operator.
10702 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10703                                      StorageClass& SC) {
10704   // C++ [class.conv.fct]p1:
10705   //   Neither parameter types nor return type can be specified. The
10706   //   type of a conversion function (8.3.5) is "function taking no
10707   //   parameter returning conversion-type-id."
10708   if (SC == SC_Static) {
10709     if (!D.isInvalidType())
10710       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10711         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10712         << D.getName().getSourceRange();
10713     D.setInvalidType();
10714     SC = SC_None;
10715   }
10716 
10717   TypeSourceInfo *ConvTSI = nullptr;
10718   QualType ConvType =
10719       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10720 
10721   const DeclSpec &DS = D.getDeclSpec();
10722   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10723     // Conversion functions don't have return types, but the parser will
10724     // happily parse something like:
10725     //
10726     //   class X {
10727     //     float operator bool();
10728     //   };
10729     //
10730     // The return type will be changed later anyway.
10731     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10732       << SourceRange(DS.getTypeSpecTypeLoc())
10733       << SourceRange(D.getIdentifierLoc());
10734     D.setInvalidType();
10735   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10736     // It's also plausible that the user writes type qualifiers in the wrong
10737     // place, such as:
10738     //   struct S { const operator int(); };
10739     // FIXME: we could provide a fixit to move the qualifiers onto the
10740     // conversion type.
10741     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10742         << SourceRange(D.getIdentifierLoc()) << 0;
10743     D.setInvalidType();
10744   }
10745 
10746   const auto *Proto = R->castAs<FunctionProtoType>();
10747 
10748   // Make sure we don't have any parameters.
10749   if (Proto->getNumParams() > 0) {
10750     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10751 
10752     // Delete the parameters.
10753     D.getFunctionTypeInfo().freeParams();
10754     D.setInvalidType();
10755   } else if (Proto->isVariadic()) {
10756     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10757     D.setInvalidType();
10758   }
10759 
10760   // Diagnose "&operator bool()" and other such nonsense.  This
10761   // is actually a gcc extension which we don't support.
10762   if (Proto->getReturnType() != ConvType) {
10763     bool NeedsTypedef = false;
10764     SourceRange Before, After;
10765 
10766     // Walk the chunks and extract information on them for our diagnostic.
10767     bool PastFunctionChunk = false;
10768     for (auto &Chunk : D.type_objects()) {
10769       switch (Chunk.Kind) {
10770       case DeclaratorChunk::Function:
10771         if (!PastFunctionChunk) {
10772           if (Chunk.Fun.HasTrailingReturnType) {
10773             TypeSourceInfo *TRT = nullptr;
10774             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10775             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10776           }
10777           PastFunctionChunk = true;
10778           break;
10779         }
10780         LLVM_FALLTHROUGH;
10781       case DeclaratorChunk::Array:
10782         NeedsTypedef = true;
10783         extendRight(After, Chunk.getSourceRange());
10784         break;
10785 
10786       case DeclaratorChunk::Pointer:
10787       case DeclaratorChunk::BlockPointer:
10788       case DeclaratorChunk::Reference:
10789       case DeclaratorChunk::MemberPointer:
10790       case DeclaratorChunk::Pipe:
10791         extendLeft(Before, Chunk.getSourceRange());
10792         break;
10793 
10794       case DeclaratorChunk::Paren:
10795         extendLeft(Before, Chunk.Loc);
10796         extendRight(After, Chunk.EndLoc);
10797         break;
10798       }
10799     }
10800 
10801     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10802                          After.isValid()  ? After.getBegin() :
10803                                             D.getIdentifierLoc();
10804     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10805     DB << Before << After;
10806 
10807     if (!NeedsTypedef) {
10808       DB << /*don't need a typedef*/0;
10809 
10810       // If we can provide a correct fix-it hint, do so.
10811       if (After.isInvalid() && ConvTSI) {
10812         SourceLocation InsertLoc =
10813             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10814         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10815            << FixItHint::CreateInsertionFromRange(
10816                   InsertLoc, CharSourceRange::getTokenRange(Before))
10817            << FixItHint::CreateRemoval(Before);
10818       }
10819     } else if (!Proto->getReturnType()->isDependentType()) {
10820       DB << /*typedef*/1 << Proto->getReturnType();
10821     } else if (getLangOpts().CPlusPlus11) {
10822       DB << /*alias template*/2 << Proto->getReturnType();
10823     } else {
10824       DB << /*might not be fixable*/3;
10825     }
10826 
10827     // Recover by incorporating the other type chunks into the result type.
10828     // Note, this does *not* change the name of the function. This is compatible
10829     // with the GCC extension:
10830     //   struct S { &operator int(); } s;
10831     //   int &r = s.operator int(); // ok in GCC
10832     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10833     ConvType = Proto->getReturnType();
10834   }
10835 
10836   // C++ [class.conv.fct]p4:
10837   //   The conversion-type-id shall not represent a function type nor
10838   //   an array type.
10839   if (ConvType->isArrayType()) {
10840     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10841     ConvType = Context.getPointerType(ConvType);
10842     D.setInvalidType();
10843   } else if (ConvType->isFunctionType()) {
10844     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10845     ConvType = Context.getPointerType(ConvType);
10846     D.setInvalidType();
10847   }
10848 
10849   // Rebuild the function type "R" without any parameters (in case any
10850   // of the errors above fired) and with the conversion type as the
10851   // return type.
10852   if (D.isInvalidType())
10853     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10854 
10855   // C++0x explicit conversion operators.
10856   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10857     Diag(DS.getExplicitSpecLoc(),
10858          getLangOpts().CPlusPlus11
10859              ? diag::warn_cxx98_compat_explicit_conversion_functions
10860              : diag::ext_explicit_conversion_functions)
10861         << SourceRange(DS.getExplicitSpecRange());
10862 }
10863 
10864 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10865 /// the declaration of the given C++ conversion function. This routine
10866 /// is responsible for recording the conversion function in the C++
10867 /// class, if possible.
10868 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10869   assert(Conversion && "Expected to receive a conversion function declaration");
10870 
10871   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10872 
10873   // Make sure we aren't redeclaring the conversion function.
10874   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10875   // C++ [class.conv.fct]p1:
10876   //   [...] A conversion function is never used to convert a
10877   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10878   //   same object type (or a reference to it), to a (possibly
10879   //   cv-qualified) base class of that type (or a reference to it),
10880   //   or to (possibly cv-qualified) void.
10881   QualType ClassType
10882     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10883   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10884     ConvType = ConvTypeRef->getPointeeType();
10885   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10886       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10887     /* Suppress diagnostics for instantiations. */;
10888   else if (Conversion->size_overridden_methods() != 0)
10889     /* Suppress diagnostics for overriding virtual function in a base class. */;
10890   else if (ConvType->isRecordType()) {
10891     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10892     if (ConvType == ClassType)
10893       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10894         << ClassType;
10895     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10896       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10897         <<  ClassType << ConvType;
10898   } else if (ConvType->isVoidType()) {
10899     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10900       << ClassType << ConvType;
10901   }
10902 
10903   if (FunctionTemplateDecl *ConversionTemplate
10904                                 = Conversion->getDescribedFunctionTemplate())
10905     return ConversionTemplate;
10906 
10907   return Conversion;
10908 }
10909 
10910 namespace {
10911 /// Utility class to accumulate and print a diagnostic listing the invalid
10912 /// specifier(s) on a declaration.
10913 struct BadSpecifierDiagnoser {
10914   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10915       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10916   ~BadSpecifierDiagnoser() {
10917     Diagnostic << Specifiers;
10918   }
10919 
10920   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10921     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10922   }
10923   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10924     return check(SpecLoc,
10925                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10926   }
10927   void check(SourceLocation SpecLoc, const char *Spec) {
10928     if (SpecLoc.isInvalid()) return;
10929     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10930     if (!Specifiers.empty()) Specifiers += " ";
10931     Specifiers += Spec;
10932   }
10933 
10934   Sema &S;
10935   Sema::SemaDiagnosticBuilder Diagnostic;
10936   std::string Specifiers;
10937 };
10938 }
10939 
10940 /// Check the validity of a declarator that we parsed for a deduction-guide.
10941 /// These aren't actually declarators in the grammar, so we need to check that
10942 /// the user didn't specify any pieces that are not part of the deduction-guide
10943 /// grammar.
10944 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10945                                          StorageClass &SC) {
10946   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10947   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10948   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10949 
10950   // C++ [temp.deduct.guide]p3:
10951   //   A deduction-gide shall be declared in the same scope as the
10952   //   corresponding class template.
10953   if (!CurContext->getRedeclContext()->Equals(
10954           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10955     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10956       << GuidedTemplateDecl;
10957     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10958   }
10959 
10960   auto &DS = D.getMutableDeclSpec();
10961   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10962   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10963       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10964       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10965     BadSpecifierDiagnoser Diagnoser(
10966         *this, D.getIdentifierLoc(),
10967         diag::err_deduction_guide_invalid_specifier);
10968 
10969     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10970     DS.ClearStorageClassSpecs();
10971     SC = SC_None;
10972 
10973     // 'explicit' is permitted.
10974     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10975     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10976     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10977     DS.ClearConstexprSpec();
10978 
10979     Diagnoser.check(DS.getConstSpecLoc(), "const");
10980     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10981     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10982     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10983     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10984     DS.ClearTypeQualifiers();
10985 
10986     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10987     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10988     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10989     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10990     DS.ClearTypeSpecType();
10991   }
10992 
10993   if (D.isInvalidType())
10994     return;
10995 
10996   // Check the declarator is simple enough.
10997   bool FoundFunction = false;
10998   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10999     if (Chunk.Kind == DeclaratorChunk::Paren)
11000       continue;
11001     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11002       Diag(D.getDeclSpec().getBeginLoc(),
11003            diag::err_deduction_guide_with_complex_decl)
11004           << D.getSourceRange();
11005       break;
11006     }
11007     if (!Chunk.Fun.hasTrailingReturnType()) {
11008       Diag(D.getName().getBeginLoc(),
11009            diag::err_deduction_guide_no_trailing_return_type);
11010       break;
11011     }
11012 
11013     // Check that the return type is written as a specialization of
11014     // the template specified as the deduction-guide's name.
11015     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11016     TypeSourceInfo *TSI = nullptr;
11017     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11018     assert(TSI && "deduction guide has valid type but invalid return type?");
11019     bool AcceptableReturnType = false;
11020     bool MightInstantiateToSpecialization = false;
11021     if (auto RetTST =
11022             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
11023       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11024       bool TemplateMatches =
11025           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11026       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
11027         AcceptableReturnType = true;
11028       else {
11029         // This could still instantiate to the right type, unless we know it
11030         // names the wrong class template.
11031         auto *TD = SpecifiedName.getAsTemplateDecl();
11032         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11033                                              !TemplateMatches);
11034       }
11035     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11036       MightInstantiateToSpecialization = true;
11037     }
11038 
11039     if (!AcceptableReturnType) {
11040       Diag(TSI->getTypeLoc().getBeginLoc(),
11041            diag::err_deduction_guide_bad_trailing_return_type)
11042           << GuidedTemplate << TSI->getType()
11043           << MightInstantiateToSpecialization
11044           << TSI->getTypeLoc().getSourceRange();
11045     }
11046 
11047     // Keep going to check that we don't have any inner declarator pieces (we
11048     // could still have a function returning a pointer to a function).
11049     FoundFunction = true;
11050   }
11051 
11052   if (D.isFunctionDefinition())
11053     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11054 }
11055 
11056 //===----------------------------------------------------------------------===//
11057 // Namespace Handling
11058 //===----------------------------------------------------------------------===//
11059 
11060 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11061 /// reopened.
11062 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11063                                             SourceLocation Loc,
11064                                             IdentifierInfo *II, bool *IsInline,
11065                                             NamespaceDecl *PrevNS) {
11066   assert(*IsInline != PrevNS->isInline());
11067 
11068   // 'inline' must appear on the original definition, but not necessarily
11069   // on all extension definitions, so the note should point to the first
11070   // definition to avoid confusion.
11071   PrevNS = PrevNS->getFirstDecl();
11072 
11073   if (PrevNS->isInline())
11074     // The user probably just forgot the 'inline', so suggest that it
11075     // be added back.
11076     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11077       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11078   else
11079     S.Diag(Loc, diag::err_inline_namespace_mismatch);
11080 
11081   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11082   *IsInline = PrevNS->isInline();
11083 }
11084 
11085 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11086 /// definition.
11087 Decl *Sema::ActOnStartNamespaceDef(
11088     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
11089     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
11090     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
11091   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11092   // For anonymous namespace, take the location of the left brace.
11093   SourceLocation Loc = II ? IdentLoc : LBrace;
11094   bool IsInline = InlineLoc.isValid();
11095   bool IsInvalid = false;
11096   bool IsStd = false;
11097   bool AddToKnown = false;
11098   Scope *DeclRegionScope = NamespcScope->getParent();
11099 
11100   NamespaceDecl *PrevNS = nullptr;
11101   if (II) {
11102     // C++ [namespace.def]p2:
11103     //   The identifier in an original-namespace-definition shall not
11104     //   have been previously defined in the declarative region in
11105     //   which the original-namespace-definition appears. The
11106     //   identifier in an original-namespace-definition is the name of
11107     //   the namespace. Subsequently in that declarative region, it is
11108     //   treated as an original-namespace-name.
11109     //
11110     // Since namespace names are unique in their scope, and we don't
11111     // look through using directives, just look for any ordinary names
11112     // as if by qualified name lookup.
11113     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11114                    ForExternalRedeclaration);
11115     LookupQualifiedName(R, CurContext->getRedeclContext());
11116     NamedDecl *PrevDecl =
11117         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11118     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11119 
11120     if (PrevNS) {
11121       // This is an extended namespace definition.
11122       if (IsInline != PrevNS->isInline())
11123         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11124                                         &IsInline, PrevNS);
11125     } else if (PrevDecl) {
11126       // This is an invalid name redefinition.
11127       Diag(Loc, diag::err_redefinition_different_kind)
11128         << II;
11129       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11130       IsInvalid = true;
11131       // Continue on to push Namespc as current DeclContext and return it.
11132     } else if (II->isStr("std") &&
11133                CurContext->getRedeclContext()->isTranslationUnit()) {
11134       // This is the first "real" definition of the namespace "std", so update
11135       // our cache of the "std" namespace to point at this definition.
11136       PrevNS = getStdNamespace();
11137       IsStd = true;
11138       AddToKnown = !IsInline;
11139     } else {
11140       // We've seen this namespace for the first time.
11141       AddToKnown = !IsInline;
11142     }
11143   } else {
11144     // Anonymous namespaces.
11145 
11146     // Determine whether the parent already has an anonymous namespace.
11147     DeclContext *Parent = CurContext->getRedeclContext();
11148     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11149       PrevNS = TU->getAnonymousNamespace();
11150     } else {
11151       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11152       PrevNS = ND->getAnonymousNamespace();
11153     }
11154 
11155     if (PrevNS && IsInline != PrevNS->isInline())
11156       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11157                                       &IsInline, PrevNS);
11158   }
11159 
11160   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
11161                                                  StartLoc, Loc, II, PrevNS);
11162   if (IsInvalid)
11163     Namespc->setInvalidDecl();
11164 
11165   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11166   AddPragmaAttributes(DeclRegionScope, Namespc);
11167 
11168   // FIXME: Should we be merging attributes?
11169   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11170     PushNamespaceVisibilityAttr(Attr, Loc);
11171 
11172   if (IsStd)
11173     StdNamespace = Namespc;
11174   if (AddToKnown)
11175     KnownNamespaces[Namespc] = false;
11176 
11177   if (II) {
11178     PushOnScopeChains(Namespc, DeclRegionScope);
11179   } else {
11180     // Link the anonymous namespace into its parent.
11181     DeclContext *Parent = CurContext->getRedeclContext();
11182     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11183       TU->setAnonymousNamespace(Namespc);
11184     } else {
11185       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11186     }
11187 
11188     CurContext->addDecl(Namespc);
11189 
11190     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11191     //   behaves as if it were replaced by
11192     //     namespace unique { /* empty body */ }
11193     //     using namespace unique;
11194     //     namespace unique { namespace-body }
11195     //   where all occurrences of 'unique' in a translation unit are
11196     //   replaced by the same identifier and this identifier differs
11197     //   from all other identifiers in the entire program.
11198 
11199     // We just create the namespace with an empty name and then add an
11200     // implicit using declaration, just like the standard suggests.
11201     //
11202     // CodeGen enforces the "universally unique" aspect by giving all
11203     // declarations semantically contained within an anonymous
11204     // namespace internal linkage.
11205 
11206     if (!PrevNS) {
11207       UD = UsingDirectiveDecl::Create(Context, Parent,
11208                                       /* 'using' */ LBrace,
11209                                       /* 'namespace' */ SourceLocation(),
11210                                       /* qualifier */ NestedNameSpecifierLoc(),
11211                                       /* identifier */ SourceLocation(),
11212                                       Namespc,
11213                                       /* Ancestor */ Parent);
11214       UD->setImplicit();
11215       Parent->addDecl(UD);
11216     }
11217   }
11218 
11219   ActOnDocumentableDecl(Namespc);
11220 
11221   // Although we could have an invalid decl (i.e. the namespace name is a
11222   // redefinition), push it as current DeclContext and try to continue parsing.
11223   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11224   // for the namespace has the declarations that showed up in that particular
11225   // namespace definition.
11226   PushDeclContext(NamespcScope, Namespc);
11227   return Namespc;
11228 }
11229 
11230 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11231 /// is a namespace alias, returns the namespace it points to.
11232 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11233   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11234     return AD->getNamespace();
11235   return dyn_cast_or_null<NamespaceDecl>(D);
11236 }
11237 
11238 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11239 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11240 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11241   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11242   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11243   Namespc->setRBraceLoc(RBrace);
11244   PopDeclContext();
11245   if (Namespc->hasAttr<VisibilityAttr>())
11246     PopPragmaVisibility(true, RBrace);
11247   // If this namespace contains an export-declaration, export it now.
11248   if (DeferredExportedNamespaces.erase(Namespc))
11249     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11250 }
11251 
11252 CXXRecordDecl *Sema::getStdBadAlloc() const {
11253   return cast_or_null<CXXRecordDecl>(
11254                                   StdBadAlloc.get(Context.getExternalSource()));
11255 }
11256 
11257 EnumDecl *Sema::getStdAlignValT() const {
11258   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11259 }
11260 
11261 NamespaceDecl *Sema::getStdNamespace() const {
11262   return cast_or_null<NamespaceDecl>(
11263                                  StdNamespace.get(Context.getExternalSource()));
11264 }
11265 
11266 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11267   if (!StdExperimentalNamespaceCache) {
11268     if (auto Std = getStdNamespace()) {
11269       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11270                           SourceLocation(), LookupNamespaceName);
11271       if (!LookupQualifiedName(Result, Std) ||
11272           !(StdExperimentalNamespaceCache =
11273                 Result.getAsSingle<NamespaceDecl>()))
11274         Result.suppressDiagnostics();
11275     }
11276   }
11277   return StdExperimentalNamespaceCache;
11278 }
11279 
11280 namespace {
11281 
11282 enum UnsupportedSTLSelect {
11283   USS_InvalidMember,
11284   USS_MissingMember,
11285   USS_NonTrivial,
11286   USS_Other
11287 };
11288 
11289 struct InvalidSTLDiagnoser {
11290   Sema &S;
11291   SourceLocation Loc;
11292   QualType TyForDiags;
11293 
11294   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11295                       const VarDecl *VD = nullptr) {
11296     {
11297       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11298                << TyForDiags << ((int)Sel);
11299       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11300         assert(!Name.empty());
11301         D << Name;
11302       }
11303     }
11304     if (Sel == USS_InvalidMember) {
11305       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11306           << VD << VD->getSourceRange();
11307     }
11308     return QualType();
11309   }
11310 };
11311 } // namespace
11312 
11313 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11314                                            SourceLocation Loc,
11315                                            ComparisonCategoryUsage Usage) {
11316   assert(getLangOpts().CPlusPlus &&
11317          "Looking for comparison category type outside of C++.");
11318 
11319   // Use an elaborated type for diagnostics which has a name containing the
11320   // prepended 'std' namespace but not any inline namespace names.
11321   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11322     auto *NNS =
11323         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11324     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11325   };
11326 
11327   // Check if we've already successfully checked the comparison category type
11328   // before. If so, skip checking it again.
11329   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11330   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11331     // The only thing we need to check is that the type has a reachable
11332     // definition in the current context.
11333     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11334       return QualType();
11335 
11336     return Info->getType();
11337   }
11338 
11339   // If lookup failed
11340   if (!Info) {
11341     std::string NameForDiags = "std::";
11342     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11343     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11344         << NameForDiags << (int)Usage;
11345     return QualType();
11346   }
11347 
11348   assert(Info->Kind == Kind);
11349   assert(Info->Record);
11350 
11351   // Update the Record decl in case we encountered a forward declaration on our
11352   // first pass. FIXME: This is a bit of a hack.
11353   if (Info->Record->hasDefinition())
11354     Info->Record = Info->Record->getDefinition();
11355 
11356   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11357     return QualType();
11358 
11359   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11360 
11361   if (!Info->Record->isTriviallyCopyable())
11362     return UnsupportedSTLError(USS_NonTrivial);
11363 
11364   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11365     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11366     // Tolerate empty base classes.
11367     if (Base->isEmpty())
11368       continue;
11369     // Reject STL implementations which have at least one non-empty base.
11370     return UnsupportedSTLError();
11371   }
11372 
11373   // Check that the STL has implemented the types using a single integer field.
11374   // This expectation allows better codegen for builtin operators. We require:
11375   //   (1) The class has exactly one field.
11376   //   (2) The field is an integral or enumeration type.
11377   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11378   if (std::distance(FIt, FEnd) != 1 ||
11379       !FIt->getType()->isIntegralOrEnumerationType()) {
11380     return UnsupportedSTLError();
11381   }
11382 
11383   // Build each of the require values and store them in Info.
11384   for (ComparisonCategoryResult CCR :
11385        ComparisonCategories::getPossibleResultsForType(Kind)) {
11386     StringRef MemName = ComparisonCategories::getResultString(CCR);
11387     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11388 
11389     if (!ValInfo)
11390       return UnsupportedSTLError(USS_MissingMember, MemName);
11391 
11392     VarDecl *VD = ValInfo->VD;
11393     assert(VD && "should not be null!");
11394 
11395     // Attempt to diagnose reasons why the STL definition of this type
11396     // might be foobar, including it failing to be a constant expression.
11397     // TODO Handle more ways the lookup or result can be invalid.
11398     if (!VD->isStaticDataMember() ||
11399         !VD->isUsableInConstantExpressions(Context))
11400       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11401 
11402     // Attempt to evaluate the var decl as a constant expression and extract
11403     // the value of its first field as a ICE. If this fails, the STL
11404     // implementation is not supported.
11405     if (!ValInfo->hasValidIntValue())
11406       return UnsupportedSTLError();
11407 
11408     MarkVariableReferenced(Loc, VD);
11409   }
11410 
11411   // We've successfully built the required types and expressions. Update
11412   // the cache and return the newly cached value.
11413   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11414   return Info->getType();
11415 }
11416 
11417 /// Retrieve the special "std" namespace, which may require us to
11418 /// implicitly define the namespace.
11419 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11420   if (!StdNamespace) {
11421     // The "std" namespace has not yet been defined, so build one implicitly.
11422     StdNamespace = NamespaceDecl::Create(Context,
11423                                          Context.getTranslationUnitDecl(),
11424                                          /*Inline=*/false,
11425                                          SourceLocation(), SourceLocation(),
11426                                          &PP.getIdentifierTable().get("std"),
11427                                          /*PrevDecl=*/nullptr);
11428     getStdNamespace()->setImplicit(true);
11429   }
11430 
11431   return getStdNamespace();
11432 }
11433 
11434 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11435   assert(getLangOpts().CPlusPlus &&
11436          "Looking for std::initializer_list outside of C++.");
11437 
11438   // We're looking for implicit instantiations of
11439   // template <typename E> class std::initializer_list.
11440 
11441   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11442     return false;
11443 
11444   ClassTemplateDecl *Template = nullptr;
11445   const TemplateArgument *Arguments = nullptr;
11446 
11447   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11448 
11449     ClassTemplateSpecializationDecl *Specialization =
11450         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11451     if (!Specialization)
11452       return false;
11453 
11454     Template = Specialization->getSpecializedTemplate();
11455     Arguments = Specialization->getTemplateArgs().data();
11456   } else if (const TemplateSpecializationType *TST =
11457                  Ty->getAs<TemplateSpecializationType>()) {
11458     Template = dyn_cast_or_null<ClassTemplateDecl>(
11459         TST->getTemplateName().getAsTemplateDecl());
11460     Arguments = TST->getArgs();
11461   }
11462   if (!Template)
11463     return false;
11464 
11465   if (!StdInitializerList) {
11466     // Haven't recognized std::initializer_list yet, maybe this is it.
11467     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11468     if (TemplateClass->getIdentifier() !=
11469             &PP.getIdentifierTable().get("initializer_list") ||
11470         !getStdNamespace()->InEnclosingNamespaceSetOf(
11471             TemplateClass->getDeclContext()))
11472       return false;
11473     // This is a template called std::initializer_list, but is it the right
11474     // template?
11475     TemplateParameterList *Params = Template->getTemplateParameters();
11476     if (Params->getMinRequiredArguments() != 1)
11477       return false;
11478     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11479       return false;
11480 
11481     // It's the right template.
11482     StdInitializerList = Template;
11483   }
11484 
11485   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11486     return false;
11487 
11488   // This is an instance of std::initializer_list. Find the argument type.
11489   if (Element)
11490     *Element = Arguments[0].getAsType();
11491   return true;
11492 }
11493 
11494 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11495   NamespaceDecl *Std = S.getStdNamespace();
11496   if (!Std) {
11497     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11498     return nullptr;
11499   }
11500 
11501   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11502                       Loc, Sema::LookupOrdinaryName);
11503   if (!S.LookupQualifiedName(Result, Std)) {
11504     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11505     return nullptr;
11506   }
11507   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11508   if (!Template) {
11509     Result.suppressDiagnostics();
11510     // We found something weird. Complain about the first thing we found.
11511     NamedDecl *Found = *Result.begin();
11512     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11513     return nullptr;
11514   }
11515 
11516   // We found some template called std::initializer_list. Now verify that it's
11517   // correct.
11518   TemplateParameterList *Params = Template->getTemplateParameters();
11519   if (Params->getMinRequiredArguments() != 1 ||
11520       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11521     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11522     return nullptr;
11523   }
11524 
11525   return Template;
11526 }
11527 
11528 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11529   if (!StdInitializerList) {
11530     StdInitializerList = LookupStdInitializerList(*this, Loc);
11531     if (!StdInitializerList)
11532       return QualType();
11533   }
11534 
11535   TemplateArgumentListInfo Args(Loc, Loc);
11536   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11537                                        Context.getTrivialTypeSourceInfo(Element,
11538                                                                         Loc)));
11539   return Context.getCanonicalType(
11540       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11541 }
11542 
11543 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11544   // C++ [dcl.init.list]p2:
11545   //   A constructor is an initializer-list constructor if its first parameter
11546   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11547   //   std::initializer_list<E> for some type E, and either there are no other
11548   //   parameters or else all other parameters have default arguments.
11549   if (!Ctor->hasOneParamOrDefaultArgs())
11550     return false;
11551 
11552   QualType ArgType = Ctor->getParamDecl(0)->getType();
11553   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11554     ArgType = RT->getPointeeType().getUnqualifiedType();
11555 
11556   return isStdInitializerList(ArgType, nullptr);
11557 }
11558 
11559 /// Determine whether a using statement is in a context where it will be
11560 /// apply in all contexts.
11561 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11562   switch (CurContext->getDeclKind()) {
11563     case Decl::TranslationUnit:
11564       return true;
11565     case Decl::LinkageSpec:
11566       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11567     default:
11568       return false;
11569   }
11570 }
11571 
11572 namespace {
11573 
11574 // Callback to only accept typo corrections that are namespaces.
11575 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11576 public:
11577   bool ValidateCandidate(const TypoCorrection &candidate) override {
11578     if (NamedDecl *ND = candidate.getCorrectionDecl())
11579       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11580     return false;
11581   }
11582 
11583   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11584     return std::make_unique<NamespaceValidatorCCC>(*this);
11585   }
11586 };
11587 
11588 }
11589 
11590 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11591                                        CXXScopeSpec &SS,
11592                                        SourceLocation IdentLoc,
11593                                        IdentifierInfo *Ident) {
11594   R.clear();
11595   NamespaceValidatorCCC CCC{};
11596   if (TypoCorrection Corrected =
11597           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11598                         Sema::CTK_ErrorRecovery)) {
11599     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11600       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11601       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11602                               Ident->getName().equals(CorrectedStr);
11603       S.diagnoseTypo(Corrected,
11604                      S.PDiag(diag::err_using_directive_member_suggest)
11605                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11606                      S.PDiag(diag::note_namespace_defined_here));
11607     } else {
11608       S.diagnoseTypo(Corrected,
11609                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11610                      S.PDiag(diag::note_namespace_defined_here));
11611     }
11612     R.addDecl(Corrected.getFoundDecl());
11613     return true;
11614   }
11615   return false;
11616 }
11617 
11618 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11619                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11620                                 SourceLocation IdentLoc,
11621                                 IdentifierInfo *NamespcName,
11622                                 const ParsedAttributesView &AttrList) {
11623   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11624   assert(NamespcName && "Invalid NamespcName.");
11625   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11626 
11627   // This can only happen along a recovery path.
11628   while (S->isTemplateParamScope())
11629     S = S->getParent();
11630   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11631 
11632   UsingDirectiveDecl *UDir = nullptr;
11633   NestedNameSpecifier *Qualifier = nullptr;
11634   if (SS.isSet())
11635     Qualifier = SS.getScopeRep();
11636 
11637   // Lookup namespace name.
11638   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11639   LookupParsedName(R, S, &SS);
11640   if (R.isAmbiguous())
11641     return nullptr;
11642 
11643   if (R.empty()) {
11644     R.clear();
11645     // Allow "using namespace std;" or "using namespace ::std;" even if
11646     // "std" hasn't been defined yet, for GCC compatibility.
11647     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11648         NamespcName->isStr("std")) {
11649       Diag(IdentLoc, diag::ext_using_undefined_std);
11650       R.addDecl(getOrCreateStdNamespace());
11651       R.resolveKind();
11652     }
11653     // Otherwise, attempt typo correction.
11654     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11655   }
11656 
11657   if (!R.empty()) {
11658     NamedDecl *Named = R.getRepresentativeDecl();
11659     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11660     assert(NS && "expected namespace decl");
11661 
11662     // The use of a nested name specifier may trigger deprecation warnings.
11663     DiagnoseUseOfDecl(Named, IdentLoc);
11664 
11665     // C++ [namespace.udir]p1:
11666     //   A using-directive specifies that the names in the nominated
11667     //   namespace can be used in the scope in which the
11668     //   using-directive appears after the using-directive. During
11669     //   unqualified name lookup (3.4.1), the names appear as if they
11670     //   were declared in the nearest enclosing namespace which
11671     //   contains both the using-directive and the nominated
11672     //   namespace. [Note: in this context, "contains" means "contains
11673     //   directly or indirectly". ]
11674 
11675     // Find enclosing context containing both using-directive and
11676     // nominated namespace.
11677     DeclContext *CommonAncestor = NS;
11678     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11679       CommonAncestor = CommonAncestor->getParent();
11680 
11681     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11682                                       SS.getWithLocInContext(Context),
11683                                       IdentLoc, Named, CommonAncestor);
11684 
11685     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11686         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11687       Diag(IdentLoc, diag::warn_using_directive_in_header);
11688     }
11689 
11690     PushUsingDirective(S, UDir);
11691   } else {
11692     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11693   }
11694 
11695   if (UDir)
11696     ProcessDeclAttributeList(S, UDir, AttrList);
11697 
11698   return UDir;
11699 }
11700 
11701 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11702   // If the scope has an associated entity and the using directive is at
11703   // namespace or translation unit scope, add the UsingDirectiveDecl into
11704   // its lookup structure so qualified name lookup can find it.
11705   DeclContext *Ctx = S->getEntity();
11706   if (Ctx && !Ctx->isFunctionOrMethod())
11707     Ctx->addDecl(UDir);
11708   else
11709     // Otherwise, it is at block scope. The using-directives will affect lookup
11710     // only to the end of the scope.
11711     S->PushUsingDirective(UDir);
11712 }
11713 
11714 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11715                                   SourceLocation UsingLoc,
11716                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11717                                   UnqualifiedId &Name,
11718                                   SourceLocation EllipsisLoc,
11719                                   const ParsedAttributesView &AttrList) {
11720   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11721 
11722   if (SS.isEmpty()) {
11723     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11724     return nullptr;
11725   }
11726 
11727   switch (Name.getKind()) {
11728   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11729   case UnqualifiedIdKind::IK_Identifier:
11730   case UnqualifiedIdKind::IK_OperatorFunctionId:
11731   case UnqualifiedIdKind::IK_LiteralOperatorId:
11732   case UnqualifiedIdKind::IK_ConversionFunctionId:
11733     break;
11734 
11735   case UnqualifiedIdKind::IK_ConstructorName:
11736   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11737     // C++11 inheriting constructors.
11738     Diag(Name.getBeginLoc(),
11739          getLangOpts().CPlusPlus11
11740              ? diag::warn_cxx98_compat_using_decl_constructor
11741              : diag::err_using_decl_constructor)
11742         << SS.getRange();
11743 
11744     if (getLangOpts().CPlusPlus11) break;
11745 
11746     return nullptr;
11747 
11748   case UnqualifiedIdKind::IK_DestructorName:
11749     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11750     return nullptr;
11751 
11752   case UnqualifiedIdKind::IK_TemplateId:
11753     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11754         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11755     return nullptr;
11756 
11757   case UnqualifiedIdKind::IK_DeductionGuideName:
11758     llvm_unreachable("cannot parse qualified deduction guide name");
11759   }
11760 
11761   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11762   DeclarationName TargetName = TargetNameInfo.getName();
11763   if (!TargetName)
11764     return nullptr;
11765 
11766   // Warn about access declarations.
11767   if (UsingLoc.isInvalid()) {
11768     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11769                                  ? diag::err_access_decl
11770                                  : diag::warn_access_decl_deprecated)
11771         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11772   }
11773 
11774   if (EllipsisLoc.isInvalid()) {
11775     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11776         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11777       return nullptr;
11778   } else {
11779     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11780         !TargetNameInfo.containsUnexpandedParameterPack()) {
11781       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11782         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11783       EllipsisLoc = SourceLocation();
11784     }
11785   }
11786 
11787   NamedDecl *UD =
11788       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11789                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11790                             /*IsInstantiation*/ false,
11791                             AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11792   if (UD)
11793     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11794 
11795   return UD;
11796 }
11797 
11798 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
11799                                       SourceLocation UsingLoc,
11800                                       SourceLocation EnumLoc,
11801                                       const DeclSpec &DS) {
11802   switch (DS.getTypeSpecType()) {
11803   case DeclSpec::TST_error:
11804     // This will already have been diagnosed
11805     return nullptr;
11806 
11807   case DeclSpec::TST_enum:
11808     break;
11809 
11810   case DeclSpec::TST_typename:
11811     Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
11812     return nullptr;
11813 
11814   default:
11815     llvm_unreachable("unexpected DeclSpec type");
11816   }
11817 
11818   // As with enum-decls, we ignore attributes for now.
11819   auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
11820   if (auto *Def = Enum->getDefinition())
11821     Enum = Def;
11822 
11823   auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
11824                                        DS.getTypeSpecTypeNameLoc(), Enum);
11825   if (UD)
11826     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11827 
11828   return UD;
11829 }
11830 
11831 /// Determine whether a using declaration considers the given
11832 /// declarations as "equivalent", e.g., if they are redeclarations of
11833 /// the same entity or are both typedefs of the same type.
11834 static bool
11835 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11836   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11837     return true;
11838 
11839   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11840     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11841       return Context.hasSameType(TD1->getUnderlyingType(),
11842                                  TD2->getUnderlyingType());
11843 
11844   // Two using_if_exists using-declarations are equivalent if both are
11845   // unresolved.
11846   if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11847       isa<UnresolvedUsingIfExistsDecl>(D2))
11848     return true;
11849 
11850   return false;
11851 }
11852 
11853 
11854 /// Determines whether to create a using shadow decl for a particular
11855 /// decl, given the set of decls existing prior to this using lookup.
11856 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
11857                                 const LookupResult &Previous,
11858                                 UsingShadowDecl *&PrevShadow) {
11859   // Diagnose finding a decl which is not from a base class of the
11860   // current class.  We do this now because there are cases where this
11861   // function will silently decide not to build a shadow decl, which
11862   // will pre-empt further diagnostics.
11863   //
11864   // We don't need to do this in C++11 because we do the check once on
11865   // the qualifier.
11866   //
11867   // FIXME: diagnose the following if we care enough:
11868   //   struct A { int foo; };
11869   //   struct B : A { using A::foo; };
11870   //   template <class T> struct C : A {};
11871   //   template <class T> struct D : C<T> { using B::foo; } // <---
11872   // This is invalid (during instantiation) in C++03 because B::foo
11873   // resolves to the using decl in B, which is not a base class of D<T>.
11874   // We can't diagnose it immediately because C<T> is an unknown
11875   // specialization. The UsingShadowDecl in D<T> then points directly
11876   // to A::foo, which will look well-formed when we instantiate.
11877   // The right solution is to not collapse the shadow-decl chain.
11878   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
11879     if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
11880       DeclContext *OrigDC = Orig->getDeclContext();
11881 
11882       // Handle enums and anonymous structs.
11883       if (isa<EnumDecl>(OrigDC))
11884         OrigDC = OrigDC->getParent();
11885       CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11886       while (OrigRec->isAnonymousStructOrUnion())
11887         OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11888 
11889       if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11890         if (OrigDC == CurContext) {
11891           Diag(Using->getLocation(),
11892                diag::err_using_decl_nested_name_specifier_is_current_class)
11893               << Using->getQualifierLoc().getSourceRange();
11894           Diag(Orig->getLocation(), diag::note_using_decl_target);
11895           Using->setInvalidDecl();
11896           return true;
11897         }
11898 
11899         Diag(Using->getQualifierLoc().getBeginLoc(),
11900              diag::err_using_decl_nested_name_specifier_is_not_base_class)
11901             << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
11902             << Using->getQualifierLoc().getSourceRange();
11903         Diag(Orig->getLocation(), diag::note_using_decl_target);
11904         Using->setInvalidDecl();
11905         return true;
11906       }
11907     }
11908 
11909   if (Previous.empty()) return false;
11910 
11911   NamedDecl *Target = Orig;
11912   if (isa<UsingShadowDecl>(Target))
11913     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11914 
11915   // If the target happens to be one of the previous declarations, we
11916   // don't have a conflict.
11917   //
11918   // FIXME: but we might be increasing its access, in which case we
11919   // should redeclare it.
11920   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11921   bool FoundEquivalentDecl = false;
11922   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11923          I != E; ++I) {
11924     NamedDecl *D = (*I)->getUnderlyingDecl();
11925     // We can have UsingDecls in our Previous results because we use the same
11926     // LookupResult for checking whether the UsingDecl itself is a valid
11927     // redeclaration.
11928     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
11929       continue;
11930 
11931     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11932       // C++ [class.mem]p19:
11933       //   If T is the name of a class, then [every named member other than
11934       //   a non-static data member] shall have a name different from T
11935       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11936           !isa<IndirectFieldDecl>(Target) &&
11937           !isa<UnresolvedUsingValueDecl>(Target) &&
11938           DiagnoseClassNameShadow(
11939               CurContext,
11940               DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
11941         return true;
11942     }
11943 
11944     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11945       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11946         PrevShadow = Shadow;
11947       FoundEquivalentDecl = true;
11948     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11949       // We don't conflict with an existing using shadow decl of an equivalent
11950       // declaration, but we're not a redeclaration of it.
11951       FoundEquivalentDecl = true;
11952     }
11953 
11954     if (isVisible(D))
11955       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11956   }
11957 
11958   if (FoundEquivalentDecl)
11959     return false;
11960 
11961   // Always emit a diagnostic for a mismatch between an unresolved
11962   // using_if_exists and a resolved using declaration in either direction.
11963   if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
11964       (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
11965     if (!NonTag && !Tag)
11966       return false;
11967     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11968     Diag(Target->getLocation(), diag::note_using_decl_target);
11969     Diag((NonTag ? NonTag : Tag)->getLocation(),
11970          diag::note_using_decl_conflict);
11971     BUD->setInvalidDecl();
11972     return true;
11973   }
11974 
11975   if (FunctionDecl *FD = Target->getAsFunction()) {
11976     NamedDecl *OldDecl = nullptr;
11977     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11978                           /*IsForUsingDecl*/ true)) {
11979     case Ovl_Overload:
11980       return false;
11981 
11982     case Ovl_NonFunction:
11983       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11984       break;
11985 
11986     // We found a decl with the exact signature.
11987     case Ovl_Match:
11988       // If we're in a record, we want to hide the target, so we
11989       // return true (without a diagnostic) to tell the caller not to
11990       // build a shadow decl.
11991       if (CurContext->isRecord())
11992         return true;
11993 
11994       // If we're not in a record, this is an error.
11995       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11996       break;
11997     }
11998 
11999     Diag(Target->getLocation(), diag::note_using_decl_target);
12000     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12001     BUD->setInvalidDecl();
12002     return true;
12003   }
12004 
12005   // Target is not a function.
12006 
12007   if (isa<TagDecl>(Target)) {
12008     // No conflict between a tag and a non-tag.
12009     if (!Tag) return false;
12010 
12011     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12012     Diag(Target->getLocation(), diag::note_using_decl_target);
12013     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12014     BUD->setInvalidDecl();
12015     return true;
12016   }
12017 
12018   // No conflict between a tag and a non-tag.
12019   if (!NonTag) return false;
12020 
12021   Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12022   Diag(Target->getLocation(), diag::note_using_decl_target);
12023   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12024   BUD->setInvalidDecl();
12025   return true;
12026 }
12027 
12028 /// Determine whether a direct base class is a virtual base class.
12029 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12030   if (!Derived->getNumVBases())
12031     return false;
12032   for (auto &B : Derived->bases())
12033     if (B.getType()->getAsCXXRecordDecl() == Base)
12034       return B.isVirtual();
12035   llvm_unreachable("not a direct base class");
12036 }
12037 
12038 /// Builds a shadow declaration corresponding to a 'using' declaration.
12039 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12040                                             NamedDecl *Orig,
12041                                             UsingShadowDecl *PrevDecl) {
12042   // If we resolved to another shadow declaration, just coalesce them.
12043   NamedDecl *Target = Orig;
12044   if (isa<UsingShadowDecl>(Target)) {
12045     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12046     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12047   }
12048 
12049   NamedDecl *NonTemplateTarget = Target;
12050   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12051     NonTemplateTarget = TargetTD->getTemplatedDecl();
12052 
12053   UsingShadowDecl *Shadow;
12054   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12055     UsingDecl *Using = cast<UsingDecl>(BUD);
12056     bool IsVirtualBase =
12057         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12058                             Using->getQualifier()->getAsRecordDecl());
12059     Shadow = ConstructorUsingShadowDecl::Create(
12060         Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12061   } else {
12062     Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12063                                      Target->getDeclName(), BUD, Target);
12064   }
12065   BUD->addShadowDecl(Shadow);
12066 
12067   Shadow->setAccess(BUD->getAccess());
12068   if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12069     Shadow->setInvalidDecl();
12070 
12071   Shadow->setPreviousDecl(PrevDecl);
12072 
12073   if (S)
12074     PushOnScopeChains(Shadow, S);
12075   else
12076     CurContext->addDecl(Shadow);
12077 
12078 
12079   return Shadow;
12080 }
12081 
12082 /// Hides a using shadow declaration.  This is required by the current
12083 /// using-decl implementation when a resolvable using declaration in a
12084 /// class is followed by a declaration which would hide or override
12085 /// one or more of the using decl's targets; for example:
12086 ///
12087 ///   struct Base { void foo(int); };
12088 ///   struct Derived : Base {
12089 ///     using Base::foo;
12090 ///     void foo(int);
12091 ///   };
12092 ///
12093 /// The governing language is C++03 [namespace.udecl]p12:
12094 ///
12095 ///   When a using-declaration brings names from a base class into a
12096 ///   derived class scope, member functions in the derived class
12097 ///   override and/or hide member functions with the same name and
12098 ///   parameter types in a base class (rather than conflicting).
12099 ///
12100 /// There are two ways to implement this:
12101 ///   (1) optimistically create shadow decls when they're not hidden
12102 ///       by existing declarations, or
12103 ///   (2) don't create any shadow decls (or at least don't make them
12104 ///       visible) until we've fully parsed/instantiated the class.
12105 /// The problem with (1) is that we might have to retroactively remove
12106 /// a shadow decl, which requires several O(n) operations because the
12107 /// decl structures are (very reasonably) not designed for removal.
12108 /// (2) avoids this but is very fiddly and phase-dependent.
12109 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12110   if (Shadow->getDeclName().getNameKind() ==
12111         DeclarationName::CXXConversionFunctionName)
12112     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12113 
12114   // Remove it from the DeclContext...
12115   Shadow->getDeclContext()->removeDecl(Shadow);
12116 
12117   // ...and the scope, if applicable...
12118   if (S) {
12119     S->RemoveDecl(Shadow);
12120     IdResolver.RemoveDecl(Shadow);
12121   }
12122 
12123   // ...and the using decl.
12124   Shadow->getIntroducer()->removeShadowDecl(Shadow);
12125 
12126   // TODO: complain somehow if Shadow was used.  It shouldn't
12127   // be possible for this to happen, because...?
12128 }
12129 
12130 /// Find the base specifier for a base class with the given type.
12131 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12132                                                 QualType DesiredBase,
12133                                                 bool &AnyDependentBases) {
12134   // Check whether the named type is a direct base class.
12135   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12136     .getUnqualifiedType();
12137   for (auto &Base : Derived->bases()) {
12138     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12139     if (CanonicalDesiredBase == BaseType)
12140       return &Base;
12141     if (BaseType->isDependentType())
12142       AnyDependentBases = true;
12143   }
12144   return nullptr;
12145 }
12146 
12147 namespace {
12148 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12149 public:
12150   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12151                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12152       : HasTypenameKeyword(HasTypenameKeyword),
12153         IsInstantiation(IsInstantiation), OldNNS(NNS),
12154         RequireMemberOf(RequireMemberOf) {}
12155 
12156   bool ValidateCandidate(const TypoCorrection &Candidate) override {
12157     NamedDecl *ND = Candidate.getCorrectionDecl();
12158 
12159     // Keywords are not valid here.
12160     if (!ND || isa<NamespaceDecl>(ND))
12161       return false;
12162 
12163     // Completely unqualified names are invalid for a 'using' declaration.
12164     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12165       return false;
12166 
12167     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12168     // reject.
12169 
12170     if (RequireMemberOf) {
12171       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12172       if (FoundRecord && FoundRecord->isInjectedClassName()) {
12173         // No-one ever wants a using-declaration to name an injected-class-name
12174         // of a base class, unless they're declaring an inheriting constructor.
12175         ASTContext &Ctx = ND->getASTContext();
12176         if (!Ctx.getLangOpts().CPlusPlus11)
12177           return false;
12178         QualType FoundType = Ctx.getRecordType(FoundRecord);
12179 
12180         // Check that the injected-class-name is named as a member of its own
12181         // type; we don't want to suggest 'using Derived::Base;', since that
12182         // means something else.
12183         NestedNameSpecifier *Specifier =
12184             Candidate.WillReplaceSpecifier()
12185                 ? Candidate.getCorrectionSpecifier()
12186                 : OldNNS;
12187         if (!Specifier->getAsType() ||
12188             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12189           return false;
12190 
12191         // Check that this inheriting constructor declaration actually names a
12192         // direct base class of the current class.
12193         bool AnyDependentBases = false;
12194         if (!findDirectBaseWithType(RequireMemberOf,
12195                                     Ctx.getRecordType(FoundRecord),
12196                                     AnyDependentBases) &&
12197             !AnyDependentBases)
12198           return false;
12199       } else {
12200         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12201         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12202           return false;
12203 
12204         // FIXME: Check that the base class member is accessible?
12205       }
12206     } else {
12207       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12208       if (FoundRecord && FoundRecord->isInjectedClassName())
12209         return false;
12210     }
12211 
12212     if (isa<TypeDecl>(ND))
12213       return HasTypenameKeyword || !IsInstantiation;
12214 
12215     return !HasTypenameKeyword;
12216   }
12217 
12218   std::unique_ptr<CorrectionCandidateCallback> clone() override {
12219     return std::make_unique<UsingValidatorCCC>(*this);
12220   }
12221 
12222 private:
12223   bool HasTypenameKeyword;
12224   bool IsInstantiation;
12225   NestedNameSpecifier *OldNNS;
12226   CXXRecordDecl *RequireMemberOf;
12227 };
12228 } // end anonymous namespace
12229 
12230 /// Remove decls we can't actually see from a lookup being used to declare
12231 /// shadow using decls.
12232 ///
12233 /// \param S - The scope of the potential shadow decl
12234 /// \param Previous - The lookup of a potential shadow decl's name.
12235 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12236   // It is really dumb that we have to do this.
12237   LookupResult::Filter F = Previous.makeFilter();
12238   while (F.hasNext()) {
12239     NamedDecl *D = F.next();
12240     if (!isDeclInScope(D, CurContext, S))
12241       F.erase();
12242     // If we found a local extern declaration that's not ordinarily visible,
12243     // and this declaration is being added to a non-block scope, ignore it.
12244     // We're only checking for scope conflicts here, not also for violations
12245     // of the linkage rules.
12246     else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12247              !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12248       F.erase();
12249   }
12250   F.done();
12251 }
12252 
12253 /// Builds a using declaration.
12254 ///
12255 /// \param IsInstantiation - Whether this call arises from an
12256 ///   instantiation of an unresolved using declaration.  We treat
12257 ///   the lookup differently for these declarations.
12258 NamedDecl *Sema::BuildUsingDeclaration(
12259     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12260     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12261     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12262     const ParsedAttributesView &AttrList, bool IsInstantiation,
12263     bool IsUsingIfExists) {
12264   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12265   SourceLocation IdentLoc = NameInfo.getLoc();
12266   assert(IdentLoc.isValid() && "Invalid TargetName location.");
12267 
12268   // FIXME: We ignore attributes for now.
12269 
12270   // For an inheriting constructor declaration, the name of the using
12271   // declaration is the name of a constructor in this class, not in the
12272   // base class.
12273   DeclarationNameInfo UsingName = NameInfo;
12274   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12275     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12276       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12277           Context.getCanonicalType(Context.getRecordType(RD))));
12278 
12279   // Do the redeclaration lookup in the current scope.
12280   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12281                         ForVisibleRedeclaration);
12282   Previous.setHideTags(false);
12283   if (S) {
12284     LookupName(Previous, S);
12285 
12286     FilterUsingLookup(S, Previous);
12287   } else {
12288     assert(IsInstantiation && "no scope in non-instantiation");
12289     if (CurContext->isRecord())
12290       LookupQualifiedName(Previous, CurContext);
12291     else {
12292       // No redeclaration check is needed here; in non-member contexts we
12293       // diagnosed all possible conflicts with other using-declarations when
12294       // building the template:
12295       //
12296       // For a dependent non-type using declaration, the only valid case is
12297       // if we instantiate to a single enumerator. We check for conflicts
12298       // between shadow declarations we introduce, and we check in the template
12299       // definition for conflicts between a non-type using declaration and any
12300       // other declaration, which together covers all cases.
12301       //
12302       // A dependent typename using declaration will never successfully
12303       // instantiate, since it will always name a class member, so we reject
12304       // that in the template definition.
12305     }
12306   }
12307 
12308   // Check for invalid redeclarations.
12309   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12310                                   SS, IdentLoc, Previous))
12311     return nullptr;
12312 
12313   // 'using_if_exists' doesn't make sense on an inherited constructor.
12314   if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12315                              DeclarationName::CXXConstructorName) {
12316     Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12317     return nullptr;
12318   }
12319 
12320   DeclContext *LookupContext = computeDeclContext(SS);
12321   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12322   if (!LookupContext || EllipsisLoc.isValid()) {
12323     NamedDecl *D;
12324     // Dependent scope, or an unexpanded pack
12325     if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12326                                                   SS, NameInfo, IdentLoc))
12327       return nullptr;
12328 
12329     if (HasTypenameKeyword) {
12330       // FIXME: not all declaration name kinds are legal here
12331       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12332                                               UsingLoc, TypenameLoc,
12333                                               QualifierLoc,
12334                                               IdentLoc, NameInfo.getName(),
12335                                               EllipsisLoc);
12336     } else {
12337       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12338                                            QualifierLoc, NameInfo, EllipsisLoc);
12339     }
12340     D->setAccess(AS);
12341     CurContext->addDecl(D);
12342     ProcessDeclAttributeList(S, D, AttrList);
12343     return D;
12344   }
12345 
12346   auto Build = [&](bool Invalid) {
12347     UsingDecl *UD =
12348         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12349                           UsingName, HasTypenameKeyword);
12350     UD->setAccess(AS);
12351     CurContext->addDecl(UD);
12352     ProcessDeclAttributeList(S, UD, AttrList);
12353     UD->setInvalidDecl(Invalid);
12354     return UD;
12355   };
12356   auto BuildInvalid = [&]{ return Build(true); };
12357   auto BuildValid = [&]{ return Build(false); };
12358 
12359   if (RequireCompleteDeclContext(SS, LookupContext))
12360     return BuildInvalid();
12361 
12362   // Look up the target name.
12363   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12364 
12365   // Unlike most lookups, we don't always want to hide tag
12366   // declarations: tag names are visible through the using declaration
12367   // even if hidden by ordinary names, *except* in a dependent context
12368   // where they may be used by two-phase lookup.
12369   if (!IsInstantiation)
12370     R.setHideTags(false);
12371 
12372   // For the purposes of this lookup, we have a base object type
12373   // equal to that of the current context.
12374   if (CurContext->isRecord()) {
12375     R.setBaseObjectType(
12376                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12377   }
12378 
12379   LookupQualifiedName(R, LookupContext);
12380 
12381   // Validate the context, now we have a lookup
12382   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12383                               IdentLoc, &R))
12384     return nullptr;
12385 
12386   if (R.empty() && IsUsingIfExists)
12387     R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12388                                                   UsingName.getName()),
12389               AS_public);
12390 
12391   // Try to correct typos if possible. If constructor name lookup finds no
12392   // results, that means the named class has no explicit constructors, and we
12393   // suppressed declaring implicit ones (probably because it's dependent or
12394   // invalid).
12395   if (R.empty() &&
12396       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12397     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12398     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12399     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12400     auto *II = NameInfo.getName().getAsIdentifierInfo();
12401     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12402         CurContext->isStdNamespace() &&
12403         isa<TranslationUnitDecl>(LookupContext) &&
12404         getSourceManager().isInSystemHeader(UsingLoc))
12405       return nullptr;
12406     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12407                           dyn_cast<CXXRecordDecl>(CurContext));
12408     if (TypoCorrection Corrected =
12409             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12410                         CTK_ErrorRecovery)) {
12411       // We reject candidates where DroppedSpecifier == true, hence the
12412       // literal '0' below.
12413       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12414                                 << NameInfo.getName() << LookupContext << 0
12415                                 << SS.getRange());
12416 
12417       // If we picked a correction with no attached Decl we can't do anything
12418       // useful with it, bail out.
12419       NamedDecl *ND = Corrected.getCorrectionDecl();
12420       if (!ND)
12421         return BuildInvalid();
12422 
12423       // If we corrected to an inheriting constructor, handle it as one.
12424       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12425       if (RD && RD->isInjectedClassName()) {
12426         // The parent of the injected class name is the class itself.
12427         RD = cast<CXXRecordDecl>(RD->getParent());
12428 
12429         // Fix up the information we'll use to build the using declaration.
12430         if (Corrected.WillReplaceSpecifier()) {
12431           NestedNameSpecifierLocBuilder Builder;
12432           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12433                               QualifierLoc.getSourceRange());
12434           QualifierLoc = Builder.getWithLocInContext(Context);
12435         }
12436 
12437         // In this case, the name we introduce is the name of a derived class
12438         // constructor.
12439         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12440         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12441             Context.getCanonicalType(Context.getRecordType(CurClass))));
12442         UsingName.setNamedTypeInfo(nullptr);
12443         for (auto *Ctor : LookupConstructors(RD))
12444           R.addDecl(Ctor);
12445         R.resolveKind();
12446       } else {
12447         // FIXME: Pick up all the declarations if we found an overloaded
12448         // function.
12449         UsingName.setName(ND->getDeclName());
12450         R.addDecl(ND);
12451       }
12452     } else {
12453       Diag(IdentLoc, diag::err_no_member)
12454         << NameInfo.getName() << LookupContext << SS.getRange();
12455       return BuildInvalid();
12456     }
12457   }
12458 
12459   if (R.isAmbiguous())
12460     return BuildInvalid();
12461 
12462   if (HasTypenameKeyword) {
12463     // If we asked for a typename and got a non-type decl, error out.
12464     if (!R.getAsSingle<TypeDecl>() &&
12465         !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12466       Diag(IdentLoc, diag::err_using_typename_non_type);
12467       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12468         Diag((*I)->getUnderlyingDecl()->getLocation(),
12469              diag::note_using_decl_target);
12470       return BuildInvalid();
12471     }
12472   } else {
12473     // If we asked for a non-typename and we got a type, error out,
12474     // but only if this is an instantiation of an unresolved using
12475     // decl.  Otherwise just silently find the type name.
12476     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12477       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12478       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12479       return BuildInvalid();
12480     }
12481   }
12482 
12483   // C++14 [namespace.udecl]p6:
12484   // A using-declaration shall not name a namespace.
12485   if (R.getAsSingle<NamespaceDecl>()) {
12486     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12487       << SS.getRange();
12488     return BuildInvalid();
12489   }
12490 
12491   UsingDecl *UD = BuildValid();
12492 
12493   // Some additional rules apply to inheriting constructors.
12494   if (UsingName.getName().getNameKind() ==
12495         DeclarationName::CXXConstructorName) {
12496     // Suppress access diagnostics; the access check is instead performed at the
12497     // point of use for an inheriting constructor.
12498     R.suppressDiagnostics();
12499     if (CheckInheritingConstructorUsingDecl(UD))
12500       return UD;
12501   }
12502 
12503   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12504     UsingShadowDecl *PrevDecl = nullptr;
12505     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12506       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12507   }
12508 
12509   return UD;
12510 }
12511 
12512 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12513                                            SourceLocation UsingLoc,
12514                                            SourceLocation EnumLoc,
12515                                            SourceLocation NameLoc,
12516                                            EnumDecl *ED) {
12517   bool Invalid = false;
12518 
12519   if (CurContext->getRedeclContext()->isRecord()) {
12520     /// In class scope, check if this is a duplicate, for better a diagnostic.
12521     DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12522     LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12523                           ForVisibleRedeclaration);
12524 
12525     LookupName(Previous, S);
12526 
12527     for (NamedDecl *D : Previous)
12528       if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12529         if (UED->getEnumDecl() == ED) {
12530           Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12531               << SourceRange(EnumLoc, NameLoc);
12532           Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12533           Invalid = true;
12534           break;
12535         }
12536   }
12537 
12538   if (RequireCompleteEnumDecl(ED, NameLoc))
12539     Invalid = true;
12540 
12541   UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12542                                             EnumLoc, NameLoc, ED);
12543   UD->setAccess(AS);
12544   CurContext->addDecl(UD);
12545 
12546   if (Invalid) {
12547     UD->setInvalidDecl();
12548     return UD;
12549   }
12550 
12551   // Create the shadow decls for each enumerator
12552   for (EnumConstantDecl *EC : ED->enumerators()) {
12553     UsingShadowDecl *PrevDecl = nullptr;
12554     DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12555     LookupResult Previous(*this, DNI, LookupOrdinaryName,
12556                           ForVisibleRedeclaration);
12557     LookupName(Previous, S);
12558     FilterUsingLookup(S, Previous);
12559 
12560     if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12561       BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12562   }
12563 
12564   return UD;
12565 }
12566 
12567 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12568                                     ArrayRef<NamedDecl *> Expansions) {
12569   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12570          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12571          isa<UsingPackDecl>(InstantiatedFrom));
12572 
12573   auto *UPD =
12574       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12575   UPD->setAccess(InstantiatedFrom->getAccess());
12576   CurContext->addDecl(UPD);
12577   return UPD;
12578 }
12579 
12580 /// Additional checks for a using declaration referring to a constructor name.
12581 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12582   assert(!UD->hasTypename() && "expecting a constructor name");
12583 
12584   const Type *SourceType = UD->getQualifier()->getAsType();
12585   assert(SourceType &&
12586          "Using decl naming constructor doesn't have type in scope spec.");
12587   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12588 
12589   // Check whether the named type is a direct base class.
12590   bool AnyDependentBases = false;
12591   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12592                                       AnyDependentBases);
12593   if (!Base && !AnyDependentBases) {
12594     Diag(UD->getUsingLoc(),
12595          diag::err_using_decl_constructor_not_in_direct_base)
12596       << UD->getNameInfo().getSourceRange()
12597       << QualType(SourceType, 0) << TargetClass;
12598     UD->setInvalidDecl();
12599     return true;
12600   }
12601 
12602   if (Base)
12603     Base->setInheritConstructors();
12604 
12605   return false;
12606 }
12607 
12608 /// Checks that the given using declaration is not an invalid
12609 /// redeclaration.  Note that this is checking only for the using decl
12610 /// itself, not for any ill-formedness among the UsingShadowDecls.
12611 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12612                                        bool HasTypenameKeyword,
12613                                        const CXXScopeSpec &SS,
12614                                        SourceLocation NameLoc,
12615                                        const LookupResult &Prev) {
12616   NestedNameSpecifier *Qual = SS.getScopeRep();
12617 
12618   // C++03 [namespace.udecl]p8:
12619   // C++0x [namespace.udecl]p10:
12620   //   A using-declaration is a declaration and can therefore be used
12621   //   repeatedly where (and only where) multiple declarations are
12622   //   allowed.
12623   //
12624   // That's in non-member contexts.
12625   if (!CurContext->getRedeclContext()->isRecord()) {
12626     // A dependent qualifier outside a class can only ever resolve to an
12627     // enumeration type. Therefore it conflicts with any other non-type
12628     // declaration in the same scope.
12629     // FIXME: How should we check for dependent type-type conflicts at block
12630     // scope?
12631     if (Qual->isDependent() && !HasTypenameKeyword) {
12632       for (auto *D : Prev) {
12633         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12634           bool OldCouldBeEnumerator =
12635               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12636           Diag(NameLoc,
12637                OldCouldBeEnumerator ? diag::err_redefinition
12638                                     : diag::err_redefinition_different_kind)
12639               << Prev.getLookupName();
12640           Diag(D->getLocation(), diag::note_previous_definition);
12641           return true;
12642         }
12643       }
12644     }
12645     return false;
12646   }
12647 
12648   const NestedNameSpecifier *CNNS =
12649       Context.getCanonicalNestedNameSpecifier(Qual);
12650   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12651     NamedDecl *D = *I;
12652 
12653     bool DTypename;
12654     NestedNameSpecifier *DQual;
12655     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12656       DTypename = UD->hasTypename();
12657       DQual = UD->getQualifier();
12658     } else if (UnresolvedUsingValueDecl *UD
12659                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12660       DTypename = false;
12661       DQual = UD->getQualifier();
12662     } else if (UnresolvedUsingTypenameDecl *UD
12663                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12664       DTypename = true;
12665       DQual = UD->getQualifier();
12666     } else continue;
12667 
12668     // using decls differ if one says 'typename' and the other doesn't.
12669     // FIXME: non-dependent using decls?
12670     if (HasTypenameKeyword != DTypename) continue;
12671 
12672     // using decls differ if they name different scopes (but note that
12673     // template instantiation can cause this check to trigger when it
12674     // didn't before instantiation).
12675     if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12676       continue;
12677 
12678     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12679     Diag(D->getLocation(), diag::note_using_decl) << 1;
12680     return true;
12681   }
12682 
12683   return false;
12684 }
12685 
12686 /// Checks that the given nested-name qualifier used in a using decl
12687 /// in the current context is appropriately related to the current
12688 /// scope.  If an error is found, diagnoses it and returns true.
12689 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12690 /// result of that lookup. UD is likewise nullptr, except when we have an
12691 /// already-populated UsingDecl whose shadow decls contain the same information
12692 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12693 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12694                                    const CXXScopeSpec &SS,
12695                                    const DeclarationNameInfo &NameInfo,
12696                                    SourceLocation NameLoc,
12697                                    const LookupResult *R, const UsingDecl *UD) {
12698   DeclContext *NamedContext = computeDeclContext(SS);
12699   assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
12700          "resolvable context must have exactly one set of decls");
12701 
12702   // C++ 20 permits using an enumerator that does not have a class-hierarchy
12703   // relationship.
12704   bool Cxx20Enumerator = false;
12705   if (NamedContext) {
12706     EnumConstantDecl *EC = nullptr;
12707     if (R)
12708       EC = R->getAsSingle<EnumConstantDecl>();
12709     else if (UD && UD->shadow_size() == 1)
12710       EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12711     if (EC)
12712       Cxx20Enumerator = getLangOpts().CPlusPlus20;
12713 
12714     if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12715       // C++14 [namespace.udecl]p7:
12716       // A using-declaration shall not name a scoped enumerator.
12717       // C++20 p1099 permits enumerators.
12718       if (EC && R && ED->isScoped())
12719         Diag(SS.getBeginLoc(),
12720              getLangOpts().CPlusPlus20
12721                  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12722                  : diag::ext_using_decl_scoped_enumerator)
12723             << SS.getRange();
12724 
12725       // We want to consider the scope of the enumerator
12726       NamedContext = ED->getDeclContext();
12727     }
12728   }
12729 
12730   if (!CurContext->isRecord()) {
12731     // C++03 [namespace.udecl]p3:
12732     // C++0x [namespace.udecl]p8:
12733     //   A using-declaration for a class member shall be a member-declaration.
12734     // C++20 [namespace.udecl]p7
12735     //   ... other than an enumerator ...
12736 
12737     // If we weren't able to compute a valid scope, it might validly be a
12738     // dependent class or enumeration scope. If we have a 'typename' keyword,
12739     // the scope must resolve to a class type.
12740     if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12741                      : !HasTypename)
12742       return false; // OK
12743 
12744     Diag(NameLoc,
12745          Cxx20Enumerator
12746              ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12747              : diag::err_using_decl_can_not_refer_to_class_member)
12748         << SS.getRange();
12749 
12750     if (Cxx20Enumerator)
12751       return false; // OK
12752 
12753     auto *RD = NamedContext
12754                    ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12755                    : nullptr;
12756     if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12757       // See if there's a helpful fixit
12758 
12759       if (!R) {
12760         // We will have already diagnosed the problem on the template
12761         // definition,  Maybe we should do so again?
12762       } else if (R->getAsSingle<TypeDecl>()) {
12763         if (getLangOpts().CPlusPlus11) {
12764           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12765           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12766             << 0 // alias declaration
12767             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12768                                           NameInfo.getName().getAsString() +
12769                                               " = ");
12770         } else {
12771           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12772           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12773           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12774             << 1 // typedef declaration
12775             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12776             << FixItHint::CreateInsertion(
12777                    InsertLoc, " " + NameInfo.getName().getAsString());
12778         }
12779       } else if (R->getAsSingle<VarDecl>()) {
12780         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12781         // repeating the type of the static data member here.
12782         FixItHint FixIt;
12783         if (getLangOpts().CPlusPlus11) {
12784           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12785           FixIt = FixItHint::CreateReplacement(
12786               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12787         }
12788 
12789         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12790           << 2 // reference declaration
12791           << FixIt;
12792       } else if (R->getAsSingle<EnumConstantDecl>()) {
12793         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12794         // repeating the type of the enumeration here, and we can't do so if
12795         // the type is anonymous.
12796         FixItHint FixIt;
12797         if (getLangOpts().CPlusPlus11) {
12798           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12799           FixIt = FixItHint::CreateReplacement(
12800               UsingLoc,
12801               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12802         }
12803 
12804         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12805           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12806           << FixIt;
12807       }
12808     }
12809 
12810     return true; // Fail
12811   }
12812 
12813   // If the named context is dependent, we can't decide much.
12814   if (!NamedContext) {
12815     // FIXME: in C++0x, we can diagnose if we can prove that the
12816     // nested-name-specifier does not refer to a base class, which is
12817     // still possible in some cases.
12818 
12819     // Otherwise we have to conservatively report that things might be
12820     // okay.
12821     return false;
12822   }
12823 
12824   // The current scope is a record.
12825   if (!NamedContext->isRecord()) {
12826     // Ideally this would point at the last name in the specifier,
12827     // but we don't have that level of source info.
12828     Diag(SS.getBeginLoc(),
12829          Cxx20Enumerator
12830              ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12831              : diag::err_using_decl_nested_name_specifier_is_not_class)
12832         << SS.getScopeRep() << SS.getRange();
12833 
12834     if (Cxx20Enumerator)
12835       return false; // OK
12836 
12837     return true;
12838   }
12839 
12840   if (!NamedContext->isDependentContext() &&
12841       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12842     return true;
12843 
12844   if (getLangOpts().CPlusPlus11) {
12845     // C++11 [namespace.udecl]p3:
12846     //   In a using-declaration used as a member-declaration, the
12847     //   nested-name-specifier shall name a base class of the class
12848     //   being defined.
12849 
12850     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12851                                  cast<CXXRecordDecl>(NamedContext))) {
12852 
12853       if (Cxx20Enumerator) {
12854         Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12855             << SS.getRange();
12856         return false;
12857       }
12858 
12859       if (CurContext == NamedContext) {
12860         Diag(SS.getBeginLoc(),
12861              diag::err_using_decl_nested_name_specifier_is_current_class)
12862             << SS.getRange();
12863         return !getLangOpts().CPlusPlus20;
12864       }
12865 
12866       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12867         Diag(SS.getBeginLoc(),
12868              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12869             << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12870             << SS.getRange();
12871       }
12872       return true;
12873     }
12874 
12875     return false;
12876   }
12877 
12878   // C++03 [namespace.udecl]p4:
12879   //   A using-declaration used as a member-declaration shall refer
12880   //   to a member of a base class of the class being defined [etc.].
12881 
12882   // Salient point: SS doesn't have to name a base class as long as
12883   // lookup only finds members from base classes.  Therefore we can
12884   // diagnose here only if we can prove that that can't happen,
12885   // i.e. if the class hierarchies provably don't intersect.
12886 
12887   // TODO: it would be nice if "definitely valid" results were cached
12888   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12889   // need to be repeated.
12890 
12891   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12892   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12893     Bases.insert(Base);
12894     return true;
12895   };
12896 
12897   // Collect all bases. Return false if we find a dependent base.
12898   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12899     return false;
12900 
12901   // Returns true if the base is dependent or is one of the accumulated base
12902   // classes.
12903   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12904     return !Bases.count(Base);
12905   };
12906 
12907   // Return false if the class has a dependent base or if it or one
12908   // of its bases is present in the base set of the current context.
12909   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12910       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12911     return false;
12912 
12913   Diag(SS.getRange().getBegin(),
12914        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12915     << SS.getScopeRep()
12916     << cast<CXXRecordDecl>(CurContext)
12917     << SS.getRange();
12918 
12919   return true;
12920 }
12921 
12922 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12923                                   MultiTemplateParamsArg TemplateParamLists,
12924                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12925                                   const ParsedAttributesView &AttrList,
12926                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12927   // Skip up to the relevant declaration scope.
12928   while (S->isTemplateParamScope())
12929     S = S->getParent();
12930   assert((S->getFlags() & Scope::DeclScope) &&
12931          "got alias-declaration outside of declaration scope");
12932 
12933   if (Type.isInvalid())
12934     return nullptr;
12935 
12936   bool Invalid = false;
12937   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12938   TypeSourceInfo *TInfo = nullptr;
12939   GetTypeFromParser(Type.get(), &TInfo);
12940 
12941   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12942     return nullptr;
12943 
12944   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12945                                       UPPC_DeclarationType)) {
12946     Invalid = true;
12947     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12948                                              TInfo->getTypeLoc().getBeginLoc());
12949   }
12950 
12951   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12952                         TemplateParamLists.size()
12953                             ? forRedeclarationInCurContext()
12954                             : ForVisibleRedeclaration);
12955   LookupName(Previous, S);
12956 
12957   // Warn about shadowing the name of a template parameter.
12958   if (Previous.isSingleResult() &&
12959       Previous.getFoundDecl()->isTemplateParameter()) {
12960     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12961     Previous.clear();
12962   }
12963 
12964   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12965          "name in alias declaration must be an identifier");
12966   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12967                                                Name.StartLocation,
12968                                                Name.Identifier, TInfo);
12969 
12970   NewTD->setAccess(AS);
12971 
12972   if (Invalid)
12973     NewTD->setInvalidDecl();
12974 
12975   ProcessDeclAttributeList(S, NewTD, AttrList);
12976   AddPragmaAttributes(S, NewTD);
12977 
12978   CheckTypedefForVariablyModifiedType(S, NewTD);
12979   Invalid |= NewTD->isInvalidDecl();
12980 
12981   bool Redeclaration = false;
12982 
12983   NamedDecl *NewND;
12984   if (TemplateParamLists.size()) {
12985     TypeAliasTemplateDecl *OldDecl = nullptr;
12986     TemplateParameterList *OldTemplateParams = nullptr;
12987 
12988     if (TemplateParamLists.size() != 1) {
12989       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12990         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12991          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12992     }
12993     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12994 
12995     // Check that we can declare a template here.
12996     if (CheckTemplateDeclScope(S, TemplateParams))
12997       return nullptr;
12998 
12999     // Only consider previous declarations in the same scope.
13000     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13001                          /*ExplicitInstantiationOrSpecialization*/false);
13002     if (!Previous.empty()) {
13003       Redeclaration = true;
13004 
13005       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13006       if (!OldDecl && !Invalid) {
13007         Diag(UsingLoc, diag::err_redefinition_different_kind)
13008           << Name.Identifier;
13009 
13010         NamedDecl *OldD = Previous.getRepresentativeDecl();
13011         if (OldD->getLocation().isValid())
13012           Diag(OldD->getLocation(), diag::note_previous_definition);
13013 
13014         Invalid = true;
13015       }
13016 
13017       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13018         if (TemplateParameterListsAreEqual(TemplateParams,
13019                                            OldDecl->getTemplateParameters(),
13020                                            /*Complain=*/true,
13021                                            TPL_TemplateMatch))
13022           OldTemplateParams =
13023               OldDecl->getMostRecentDecl()->getTemplateParameters();
13024         else
13025           Invalid = true;
13026 
13027         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13028         if (!Invalid &&
13029             !Context.hasSameType(OldTD->getUnderlyingType(),
13030                                  NewTD->getUnderlyingType())) {
13031           // FIXME: The C++0x standard does not clearly say this is ill-formed,
13032           // but we can't reasonably accept it.
13033           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13034             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13035           if (OldTD->getLocation().isValid())
13036             Diag(OldTD->getLocation(), diag::note_previous_definition);
13037           Invalid = true;
13038         }
13039       }
13040     }
13041 
13042     // Merge any previous default template arguments into our parameters,
13043     // and check the parameter list.
13044     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13045                                    TPC_TypeAliasTemplate))
13046       return nullptr;
13047 
13048     TypeAliasTemplateDecl *NewDecl =
13049       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13050                                     Name.Identifier, TemplateParams,
13051                                     NewTD);
13052     NewTD->setDescribedAliasTemplate(NewDecl);
13053 
13054     NewDecl->setAccess(AS);
13055 
13056     if (Invalid)
13057       NewDecl->setInvalidDecl();
13058     else if (OldDecl) {
13059       NewDecl->setPreviousDecl(OldDecl);
13060       CheckRedeclarationInModule(NewDecl, OldDecl);
13061     }
13062 
13063     NewND = NewDecl;
13064   } else {
13065     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13066       setTagNameForLinkagePurposes(TD, NewTD);
13067       handleTagNumbering(TD, S);
13068     }
13069     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13070     NewND = NewTD;
13071   }
13072 
13073   PushOnScopeChains(NewND, S);
13074   ActOnDocumentableDecl(NewND);
13075   return NewND;
13076 }
13077 
13078 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13079                                    SourceLocation AliasLoc,
13080                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
13081                                    SourceLocation IdentLoc,
13082                                    IdentifierInfo *Ident) {
13083 
13084   // Lookup the namespace name.
13085   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13086   LookupParsedName(R, S, &SS);
13087 
13088   if (R.isAmbiguous())
13089     return nullptr;
13090 
13091   if (R.empty()) {
13092     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13093       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13094       return nullptr;
13095     }
13096   }
13097   assert(!R.isAmbiguous() && !R.empty());
13098   NamedDecl *ND = R.getRepresentativeDecl();
13099 
13100   // Check if we have a previous declaration with the same name.
13101   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13102                      ForVisibleRedeclaration);
13103   LookupName(PrevR, S);
13104 
13105   // Check we're not shadowing a template parameter.
13106   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13107     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13108     PrevR.clear();
13109   }
13110 
13111   // Filter out any other lookup result from an enclosing scope.
13112   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13113                        /*AllowInlineNamespace*/false);
13114 
13115   // Find the previous declaration and check that we can redeclare it.
13116   NamespaceAliasDecl *Prev = nullptr;
13117   if (PrevR.isSingleResult()) {
13118     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13119     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13120       // We already have an alias with the same name that points to the same
13121       // namespace; check that it matches.
13122       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13123         Prev = AD;
13124       } else if (isVisible(PrevDecl)) {
13125         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13126           << Alias;
13127         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13128           << AD->getNamespace();
13129         return nullptr;
13130       }
13131     } else if (isVisible(PrevDecl)) {
13132       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13133                             ? diag::err_redefinition
13134                             : diag::err_redefinition_different_kind;
13135       Diag(AliasLoc, DiagID) << Alias;
13136       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13137       return nullptr;
13138     }
13139   }
13140 
13141   // The use of a nested name specifier may trigger deprecation warnings.
13142   DiagnoseUseOfDecl(ND, IdentLoc);
13143 
13144   NamespaceAliasDecl *AliasDecl =
13145     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13146                                Alias, SS.getWithLocInContext(Context),
13147                                IdentLoc, ND);
13148   if (Prev)
13149     AliasDecl->setPreviousDecl(Prev);
13150 
13151   PushOnScopeChains(AliasDecl, S);
13152   return AliasDecl;
13153 }
13154 
13155 namespace {
13156 struct SpecialMemberExceptionSpecInfo
13157     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13158   SourceLocation Loc;
13159   Sema::ImplicitExceptionSpecification ExceptSpec;
13160 
13161   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13162                                  Sema::CXXSpecialMember CSM,
13163                                  Sema::InheritedConstructorInfo *ICI,
13164                                  SourceLocation Loc)
13165       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13166 
13167   bool visitBase(CXXBaseSpecifier *Base);
13168   bool visitField(FieldDecl *FD);
13169 
13170   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13171                            unsigned Quals);
13172 
13173   void visitSubobjectCall(Subobject Subobj,
13174                           Sema::SpecialMemberOverloadResult SMOR);
13175 };
13176 }
13177 
13178 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13179   auto *RT = Base->getType()->getAs<RecordType>();
13180   if (!RT)
13181     return false;
13182 
13183   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13184   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13185   if (auto *BaseCtor = SMOR.getMethod()) {
13186     visitSubobjectCall(Base, BaseCtor);
13187     return false;
13188   }
13189 
13190   visitClassSubobject(BaseClass, Base, 0);
13191   return false;
13192 }
13193 
13194 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13195   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13196     Expr *E = FD->getInClassInitializer();
13197     if (!E)
13198       // FIXME: It's a little wasteful to build and throw away a
13199       // CXXDefaultInitExpr here.
13200       // FIXME: We should have a single context note pointing at Loc, and
13201       // this location should be MD->getLocation() instead, since that's
13202       // the location where we actually use the default init expression.
13203       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13204     if (E)
13205       ExceptSpec.CalledExpr(E);
13206   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13207                             ->getAs<RecordType>()) {
13208     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13209                         FD->getType().getCVRQualifiers());
13210   }
13211   return false;
13212 }
13213 
13214 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13215                                                          Subobject Subobj,
13216                                                          unsigned Quals) {
13217   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13218   bool IsMutable = Field && Field->isMutable();
13219   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13220 }
13221 
13222 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13223     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13224   // Note, if lookup fails, it doesn't matter what exception specification we
13225   // choose because the special member will be deleted.
13226   if (CXXMethodDecl *MD = SMOR.getMethod())
13227     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13228 }
13229 
13230 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13231   llvm::APSInt Result;
13232   ExprResult Converted = CheckConvertedConstantExpression(
13233       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13234   ExplicitSpec.setExpr(Converted.get());
13235   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13236     ExplicitSpec.setKind(Result.getBoolValue()
13237                              ? ExplicitSpecKind::ResolvedTrue
13238                              : ExplicitSpecKind::ResolvedFalse);
13239     return true;
13240   }
13241   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13242   return false;
13243 }
13244 
13245 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13246   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13247   if (!ExplicitExpr->isTypeDependent())
13248     tryResolveExplicitSpecifier(ES);
13249   return ES;
13250 }
13251 
13252 static Sema::ImplicitExceptionSpecification
13253 ComputeDefaultedSpecialMemberExceptionSpec(
13254     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13255     Sema::InheritedConstructorInfo *ICI) {
13256   ComputingExceptionSpec CES(S, MD, Loc);
13257 
13258   CXXRecordDecl *ClassDecl = MD->getParent();
13259 
13260   // C++ [except.spec]p14:
13261   //   An implicitly declared special member function (Clause 12) shall have an
13262   //   exception-specification. [...]
13263   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13264   if (ClassDecl->isInvalidDecl())
13265     return Info.ExceptSpec;
13266 
13267   // FIXME: If this diagnostic fires, we're probably missing a check for
13268   // attempting to resolve an exception specification before it's known
13269   // at a higher level.
13270   if (S.RequireCompleteType(MD->getLocation(),
13271                             S.Context.getRecordType(ClassDecl),
13272                             diag::err_exception_spec_incomplete_type))
13273     return Info.ExceptSpec;
13274 
13275   // C++1z [except.spec]p7:
13276   //   [Look for exceptions thrown by] a constructor selected [...] to
13277   //   initialize a potentially constructed subobject,
13278   // C++1z [except.spec]p8:
13279   //   The exception specification for an implicitly-declared destructor, or a
13280   //   destructor without a noexcept-specifier, is potentially-throwing if and
13281   //   only if any of the destructors for any of its potentially constructed
13282   //   subojects is potentially throwing.
13283   // FIXME: We respect the first rule but ignore the "potentially constructed"
13284   // in the second rule to resolve a core issue (no number yet) that would have
13285   // us reject:
13286   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13287   //   struct B : A {};
13288   //   struct C : B { void f(); };
13289   // ... due to giving B::~B() a non-throwing exception specification.
13290   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13291                                 : Info.VisitAllBases);
13292 
13293   return Info.ExceptSpec;
13294 }
13295 
13296 namespace {
13297 /// RAII object to register a special member as being currently declared.
13298 struct DeclaringSpecialMember {
13299   Sema &S;
13300   Sema::SpecialMemberDecl D;
13301   Sema::ContextRAII SavedContext;
13302   bool WasAlreadyBeingDeclared;
13303 
13304   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13305       : S(S), D(RD, CSM), SavedContext(S, RD) {
13306     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13307     if (WasAlreadyBeingDeclared)
13308       // This almost never happens, but if it does, ensure that our cache
13309       // doesn't contain a stale result.
13310       S.SpecialMemberCache.clear();
13311     else {
13312       // Register a note to be produced if we encounter an error while
13313       // declaring the special member.
13314       Sema::CodeSynthesisContext Ctx;
13315       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13316       // FIXME: We don't have a location to use here. Using the class's
13317       // location maintains the fiction that we declare all special members
13318       // with the class, but (1) it's not clear that lying about that helps our
13319       // users understand what's going on, and (2) there may be outer contexts
13320       // on the stack (some of which are relevant) and printing them exposes
13321       // our lies.
13322       Ctx.PointOfInstantiation = RD->getLocation();
13323       Ctx.Entity = RD;
13324       Ctx.SpecialMember = CSM;
13325       S.pushCodeSynthesisContext(Ctx);
13326     }
13327   }
13328   ~DeclaringSpecialMember() {
13329     if (!WasAlreadyBeingDeclared) {
13330       S.SpecialMembersBeingDeclared.erase(D);
13331       S.popCodeSynthesisContext();
13332     }
13333   }
13334 
13335   /// Are we already trying to declare this special member?
13336   bool isAlreadyBeingDeclared() const {
13337     return WasAlreadyBeingDeclared;
13338   }
13339 };
13340 }
13341 
13342 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13343   // Look up any existing declarations, but don't trigger declaration of all
13344   // implicit special members with this name.
13345   DeclarationName Name = FD->getDeclName();
13346   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13347                  ForExternalRedeclaration);
13348   for (auto *D : FD->getParent()->lookup(Name))
13349     if (auto *Acceptable = R.getAcceptableDecl(D))
13350       R.addDecl(Acceptable);
13351   R.resolveKind();
13352   R.suppressDiagnostics();
13353 
13354   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
13355 }
13356 
13357 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13358                                           QualType ResultTy,
13359                                           ArrayRef<QualType> Args) {
13360   // Build an exception specification pointing back at this constructor.
13361   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13362 
13363   LangAS AS = getDefaultCXXMethodAddrSpace();
13364   if (AS != LangAS::Default) {
13365     EPI.TypeQuals.addAddressSpace(AS);
13366   }
13367 
13368   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13369   SpecialMem->setType(QT);
13370 
13371   // During template instantiation of implicit special member functions we need
13372   // a reliable TypeSourceInfo for the function prototype in order to allow
13373   // functions to be substituted.
13374   if (inTemplateInstantiation() &&
13375       cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13376     TypeSourceInfo *TSI =
13377         Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13378     SpecialMem->setTypeSourceInfo(TSI);
13379   }
13380 }
13381 
13382 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13383                                                      CXXRecordDecl *ClassDecl) {
13384   // C++ [class.ctor]p5:
13385   //   A default constructor for a class X is a constructor of class X
13386   //   that can be called without an argument. If there is no
13387   //   user-declared constructor for class X, a default constructor is
13388   //   implicitly declared. An implicitly-declared default constructor
13389   //   is an inline public member of its class.
13390   assert(ClassDecl->needsImplicitDefaultConstructor() &&
13391          "Should not build implicit default constructor!");
13392 
13393   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13394   if (DSM.isAlreadyBeingDeclared())
13395     return nullptr;
13396 
13397   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13398                                                      CXXDefaultConstructor,
13399                                                      false);
13400 
13401   // Create the actual constructor declaration.
13402   CanQualType ClassType
13403     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13404   SourceLocation ClassLoc = ClassDecl->getLocation();
13405   DeclarationName Name
13406     = Context.DeclarationNames.getCXXConstructorName(ClassType);
13407   DeclarationNameInfo NameInfo(Name, ClassLoc);
13408   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13409       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13410       /*TInfo=*/nullptr, ExplicitSpecifier(),
13411       getCurFPFeatures().isFPConstrained(),
13412       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13413       Constexpr ? ConstexprSpecKind::Constexpr
13414                 : ConstexprSpecKind::Unspecified);
13415   DefaultCon->setAccess(AS_public);
13416   DefaultCon->setDefaulted();
13417 
13418   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13419 
13420   if (getLangOpts().CUDA)
13421     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13422                                             DefaultCon,
13423                                             /* ConstRHS */ false,
13424                                             /* Diagnose */ false);
13425 
13426   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13427   // constructors is easy to compute.
13428   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13429 
13430   // Note that we have declared this constructor.
13431   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13432 
13433   Scope *S = getScopeForContext(ClassDecl);
13434   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13435 
13436   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13437     SetDeclDeleted(DefaultCon, ClassLoc);
13438 
13439   if (S)
13440     PushOnScopeChains(DefaultCon, S, false);
13441   ClassDecl->addDecl(DefaultCon);
13442 
13443   return DefaultCon;
13444 }
13445 
13446 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13447                                             CXXConstructorDecl *Constructor) {
13448   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13449           !Constructor->doesThisDeclarationHaveABody() &&
13450           !Constructor->isDeleted()) &&
13451     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13452   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13453     return;
13454 
13455   CXXRecordDecl *ClassDecl = Constructor->getParent();
13456   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13457 
13458   SynthesizedFunctionScope Scope(*this, Constructor);
13459 
13460   // The exception specification is needed because we are defining the
13461   // function.
13462   ResolveExceptionSpec(CurrentLocation,
13463                        Constructor->getType()->castAs<FunctionProtoType>());
13464   MarkVTableUsed(CurrentLocation, ClassDecl);
13465 
13466   // Add a context note for diagnostics produced after this point.
13467   Scope.addContextNote(CurrentLocation);
13468 
13469   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13470     Constructor->setInvalidDecl();
13471     return;
13472   }
13473 
13474   SourceLocation Loc = Constructor->getEndLoc().isValid()
13475                            ? Constructor->getEndLoc()
13476                            : Constructor->getLocation();
13477   Constructor->setBody(new (Context) CompoundStmt(Loc));
13478   Constructor->markUsed(Context);
13479 
13480   if (ASTMutationListener *L = getASTMutationListener()) {
13481     L->CompletedImplicitDefinition(Constructor);
13482   }
13483 
13484   DiagnoseUninitializedFields(*this, Constructor);
13485 }
13486 
13487 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13488   // Perform any delayed checks on exception specifications.
13489   CheckDelayedMemberExceptionSpecs();
13490 }
13491 
13492 /// Find or create the fake constructor we synthesize to model constructing an
13493 /// object of a derived class via a constructor of a base class.
13494 CXXConstructorDecl *
13495 Sema::findInheritingConstructor(SourceLocation Loc,
13496                                 CXXConstructorDecl *BaseCtor,
13497                                 ConstructorUsingShadowDecl *Shadow) {
13498   CXXRecordDecl *Derived = Shadow->getParent();
13499   SourceLocation UsingLoc = Shadow->getLocation();
13500 
13501   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13502   // For now we use the name of the base class constructor as a member of the
13503   // derived class to indicate a (fake) inherited constructor name.
13504   DeclarationName Name = BaseCtor->getDeclName();
13505 
13506   // Check to see if we already have a fake constructor for this inherited
13507   // constructor call.
13508   for (NamedDecl *Ctor : Derived->lookup(Name))
13509     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13510                                ->getInheritedConstructor()
13511                                .getConstructor(),
13512                            BaseCtor))
13513       return cast<CXXConstructorDecl>(Ctor);
13514 
13515   DeclarationNameInfo NameInfo(Name, UsingLoc);
13516   TypeSourceInfo *TInfo =
13517       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13518   FunctionProtoTypeLoc ProtoLoc =
13519       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13520 
13521   // Check the inherited constructor is valid and find the list of base classes
13522   // from which it was inherited.
13523   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13524 
13525   bool Constexpr =
13526       BaseCtor->isConstexpr() &&
13527       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13528                                         false, BaseCtor, &ICI);
13529 
13530   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13531       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13532       BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13533       /*isInline=*/true,
13534       /*isImplicitlyDeclared=*/true,
13535       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13536       InheritedConstructor(Shadow, BaseCtor),
13537       BaseCtor->getTrailingRequiresClause());
13538   if (Shadow->isInvalidDecl())
13539     DerivedCtor->setInvalidDecl();
13540 
13541   // Build an unevaluated exception specification for this fake constructor.
13542   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13543   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13544   EPI.ExceptionSpec.Type = EST_Unevaluated;
13545   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13546   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13547                                                FPT->getParamTypes(), EPI));
13548 
13549   // Build the parameter declarations.
13550   SmallVector<ParmVarDecl *, 16> ParamDecls;
13551   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13552     TypeSourceInfo *TInfo =
13553         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13554     ParmVarDecl *PD = ParmVarDecl::Create(
13555         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13556         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13557     PD->setScopeInfo(0, I);
13558     PD->setImplicit();
13559     // Ensure attributes are propagated onto parameters (this matters for
13560     // format, pass_object_size, ...).
13561     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13562     ParamDecls.push_back(PD);
13563     ProtoLoc.setParam(I, PD);
13564   }
13565 
13566   // Set up the new constructor.
13567   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13568   DerivedCtor->setAccess(BaseCtor->getAccess());
13569   DerivedCtor->setParams(ParamDecls);
13570   Derived->addDecl(DerivedCtor);
13571 
13572   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13573     SetDeclDeleted(DerivedCtor, UsingLoc);
13574 
13575   return DerivedCtor;
13576 }
13577 
13578 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13579   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13580                                Ctor->getInheritedConstructor().getShadowDecl());
13581   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13582                             /*Diagnose*/true);
13583 }
13584 
13585 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13586                                        CXXConstructorDecl *Constructor) {
13587   CXXRecordDecl *ClassDecl = Constructor->getParent();
13588   assert(Constructor->getInheritedConstructor() &&
13589          !Constructor->doesThisDeclarationHaveABody() &&
13590          !Constructor->isDeleted());
13591   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13592     return;
13593 
13594   // Initializations are performed "as if by a defaulted default constructor",
13595   // so enter the appropriate scope.
13596   SynthesizedFunctionScope Scope(*this, Constructor);
13597 
13598   // The exception specification is needed because we are defining the
13599   // function.
13600   ResolveExceptionSpec(CurrentLocation,
13601                        Constructor->getType()->castAs<FunctionProtoType>());
13602   MarkVTableUsed(CurrentLocation, ClassDecl);
13603 
13604   // Add a context note for diagnostics produced after this point.
13605   Scope.addContextNote(CurrentLocation);
13606 
13607   ConstructorUsingShadowDecl *Shadow =
13608       Constructor->getInheritedConstructor().getShadowDecl();
13609   CXXConstructorDecl *InheritedCtor =
13610       Constructor->getInheritedConstructor().getConstructor();
13611 
13612   // [class.inhctor.init]p1:
13613   //   initialization proceeds as if a defaulted default constructor is used to
13614   //   initialize the D object and each base class subobject from which the
13615   //   constructor was inherited
13616 
13617   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13618   CXXRecordDecl *RD = Shadow->getParent();
13619   SourceLocation InitLoc = Shadow->getLocation();
13620 
13621   // Build explicit initializers for all base classes from which the
13622   // constructor was inherited.
13623   SmallVector<CXXCtorInitializer*, 8> Inits;
13624   for (bool VBase : {false, true}) {
13625     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13626       if (B.isVirtual() != VBase)
13627         continue;
13628 
13629       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13630       if (!BaseRD)
13631         continue;
13632 
13633       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13634       if (!BaseCtor.first)
13635         continue;
13636 
13637       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13638       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13639           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13640 
13641       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13642       Inits.push_back(new (Context) CXXCtorInitializer(
13643           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13644           SourceLocation()));
13645     }
13646   }
13647 
13648   // We now proceed as if for a defaulted default constructor, with the relevant
13649   // initializers replaced.
13650 
13651   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13652     Constructor->setInvalidDecl();
13653     return;
13654   }
13655 
13656   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13657   Constructor->markUsed(Context);
13658 
13659   if (ASTMutationListener *L = getASTMutationListener()) {
13660     L->CompletedImplicitDefinition(Constructor);
13661   }
13662 
13663   DiagnoseUninitializedFields(*this, Constructor);
13664 }
13665 
13666 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13667   // C++ [class.dtor]p2:
13668   //   If a class has no user-declared destructor, a destructor is
13669   //   declared implicitly. An implicitly-declared destructor is an
13670   //   inline public member of its class.
13671   assert(ClassDecl->needsImplicitDestructor());
13672 
13673   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13674   if (DSM.isAlreadyBeingDeclared())
13675     return nullptr;
13676 
13677   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13678                                                      CXXDestructor,
13679                                                      false);
13680 
13681   // Create the actual destructor declaration.
13682   CanQualType ClassType
13683     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13684   SourceLocation ClassLoc = ClassDecl->getLocation();
13685   DeclarationName Name
13686     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13687   DeclarationNameInfo NameInfo(Name, ClassLoc);
13688   CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
13689       Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13690       getCurFPFeatures().isFPConstrained(),
13691       /*isInline=*/true,
13692       /*isImplicitlyDeclared=*/true,
13693       Constexpr ? ConstexprSpecKind::Constexpr
13694                 : ConstexprSpecKind::Unspecified);
13695   Destructor->setAccess(AS_public);
13696   Destructor->setDefaulted();
13697 
13698   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13699 
13700   if (getLangOpts().CUDA)
13701     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13702                                             Destructor,
13703                                             /* ConstRHS */ false,
13704                                             /* Diagnose */ false);
13705 
13706   // We don't need to use SpecialMemberIsTrivial here; triviality for
13707   // destructors is easy to compute.
13708   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13709   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13710                                 ClassDecl->hasTrivialDestructorForCall());
13711 
13712   // Note that we have declared this destructor.
13713   ++getASTContext().NumImplicitDestructorsDeclared;
13714 
13715   Scope *S = getScopeForContext(ClassDecl);
13716   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13717 
13718   // We can't check whether an implicit destructor is deleted before we complete
13719   // the definition of the class, because its validity depends on the alignment
13720   // of the class. We'll check this from ActOnFields once the class is complete.
13721   if (ClassDecl->isCompleteDefinition() &&
13722       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13723     SetDeclDeleted(Destructor, ClassLoc);
13724 
13725   // Introduce this destructor into its scope.
13726   if (S)
13727     PushOnScopeChains(Destructor, S, false);
13728   ClassDecl->addDecl(Destructor);
13729 
13730   return Destructor;
13731 }
13732 
13733 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13734                                     CXXDestructorDecl *Destructor) {
13735   assert((Destructor->isDefaulted() &&
13736           !Destructor->doesThisDeclarationHaveABody() &&
13737           !Destructor->isDeleted()) &&
13738          "DefineImplicitDestructor - call it for implicit default dtor");
13739   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13740     return;
13741 
13742   CXXRecordDecl *ClassDecl = Destructor->getParent();
13743   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13744 
13745   SynthesizedFunctionScope Scope(*this, Destructor);
13746 
13747   // The exception specification is needed because we are defining the
13748   // function.
13749   ResolveExceptionSpec(CurrentLocation,
13750                        Destructor->getType()->castAs<FunctionProtoType>());
13751   MarkVTableUsed(CurrentLocation, ClassDecl);
13752 
13753   // Add a context note for diagnostics produced after this point.
13754   Scope.addContextNote(CurrentLocation);
13755 
13756   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13757                                          Destructor->getParent());
13758 
13759   if (CheckDestructor(Destructor)) {
13760     Destructor->setInvalidDecl();
13761     return;
13762   }
13763 
13764   SourceLocation Loc = Destructor->getEndLoc().isValid()
13765                            ? Destructor->getEndLoc()
13766                            : Destructor->getLocation();
13767   Destructor->setBody(new (Context) CompoundStmt(Loc));
13768   Destructor->markUsed(Context);
13769 
13770   if (ASTMutationListener *L = getASTMutationListener()) {
13771     L->CompletedImplicitDefinition(Destructor);
13772   }
13773 }
13774 
13775 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13776                                           CXXDestructorDecl *Destructor) {
13777   if (Destructor->isInvalidDecl())
13778     return;
13779 
13780   CXXRecordDecl *ClassDecl = Destructor->getParent();
13781   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13782          "implicit complete dtors unneeded outside MS ABI");
13783   assert(ClassDecl->getNumVBases() > 0 &&
13784          "complete dtor only exists for classes with vbases");
13785 
13786   SynthesizedFunctionScope Scope(*this, Destructor);
13787 
13788   // Add a context note for diagnostics produced after this point.
13789   Scope.addContextNote(CurrentLocation);
13790 
13791   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13792 }
13793 
13794 /// Perform any semantic analysis which needs to be delayed until all
13795 /// pending class member declarations have been parsed.
13796 void Sema::ActOnFinishCXXMemberDecls() {
13797   // If the context is an invalid C++ class, just suppress these checks.
13798   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13799     if (Record->isInvalidDecl()) {
13800       DelayedOverridingExceptionSpecChecks.clear();
13801       DelayedEquivalentExceptionSpecChecks.clear();
13802       return;
13803     }
13804     checkForMultipleExportedDefaultConstructors(*this, Record);
13805   }
13806 }
13807 
13808 void Sema::ActOnFinishCXXNonNestedClass() {
13809   referenceDLLExportedClassMethods();
13810 
13811   if (!DelayedDllExportMemberFunctions.empty()) {
13812     SmallVector<CXXMethodDecl*, 4> WorkList;
13813     std::swap(DelayedDllExportMemberFunctions, WorkList);
13814     for (CXXMethodDecl *M : WorkList) {
13815       DefineDefaultedFunction(*this, M, M->getLocation());
13816 
13817       // Pass the method to the consumer to get emitted. This is not necessary
13818       // for explicit instantiation definitions, as they will get emitted
13819       // anyway.
13820       if (M->getParent()->getTemplateSpecializationKind() !=
13821           TSK_ExplicitInstantiationDefinition)
13822         ActOnFinishInlineFunctionDef(M);
13823     }
13824   }
13825 }
13826 
13827 void Sema::referenceDLLExportedClassMethods() {
13828   if (!DelayedDllExportClasses.empty()) {
13829     // Calling ReferenceDllExportedMembers might cause the current function to
13830     // be called again, so use a local copy of DelayedDllExportClasses.
13831     SmallVector<CXXRecordDecl *, 4> WorkList;
13832     std::swap(DelayedDllExportClasses, WorkList);
13833     for (CXXRecordDecl *Class : WorkList)
13834       ReferenceDllExportedMembers(*this, Class);
13835   }
13836 }
13837 
13838 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13839   assert(getLangOpts().CPlusPlus11 &&
13840          "adjusting dtor exception specs was introduced in c++11");
13841 
13842   if (Destructor->isDependentContext())
13843     return;
13844 
13845   // C++11 [class.dtor]p3:
13846   //   A declaration of a destructor that does not have an exception-
13847   //   specification is implicitly considered to have the same exception-
13848   //   specification as an implicit declaration.
13849   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13850   if (DtorType->hasExceptionSpec())
13851     return;
13852 
13853   // Replace the destructor's type, building off the existing one. Fortunately,
13854   // the only thing of interest in the destructor type is its extended info.
13855   // The return and arguments are fixed.
13856   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13857   EPI.ExceptionSpec.Type = EST_Unevaluated;
13858   EPI.ExceptionSpec.SourceDecl = Destructor;
13859   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13860 
13861   // FIXME: If the destructor has a body that could throw, and the newly created
13862   // spec doesn't allow exceptions, we should emit a warning, because this
13863   // change in behavior can break conforming C++03 programs at runtime.
13864   // However, we don't have a body or an exception specification yet, so it
13865   // needs to be done somewhere else.
13866 }
13867 
13868 namespace {
13869 /// An abstract base class for all helper classes used in building the
13870 //  copy/move operators. These classes serve as factory functions and help us
13871 //  avoid using the same Expr* in the AST twice.
13872 class ExprBuilder {
13873   ExprBuilder(const ExprBuilder&) = delete;
13874   ExprBuilder &operator=(const ExprBuilder&) = delete;
13875 
13876 protected:
13877   static Expr *assertNotNull(Expr *E) {
13878     assert(E && "Expression construction must not fail.");
13879     return E;
13880   }
13881 
13882 public:
13883   ExprBuilder() {}
13884   virtual ~ExprBuilder() {}
13885 
13886   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13887 };
13888 
13889 class RefBuilder: public ExprBuilder {
13890   VarDecl *Var;
13891   QualType VarType;
13892 
13893 public:
13894   Expr *build(Sema &S, SourceLocation Loc) const override {
13895     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13896   }
13897 
13898   RefBuilder(VarDecl *Var, QualType VarType)
13899       : Var(Var), VarType(VarType) {}
13900 };
13901 
13902 class ThisBuilder: public ExprBuilder {
13903 public:
13904   Expr *build(Sema &S, SourceLocation Loc) const override {
13905     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13906   }
13907 };
13908 
13909 class CastBuilder: public ExprBuilder {
13910   const ExprBuilder &Builder;
13911   QualType Type;
13912   ExprValueKind Kind;
13913   const CXXCastPath &Path;
13914 
13915 public:
13916   Expr *build(Sema &S, SourceLocation Loc) const override {
13917     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13918                                              CK_UncheckedDerivedToBase, Kind,
13919                                              &Path).get());
13920   }
13921 
13922   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13923               const CXXCastPath &Path)
13924       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13925 };
13926 
13927 class DerefBuilder: public ExprBuilder {
13928   const ExprBuilder &Builder;
13929 
13930 public:
13931   Expr *build(Sema &S, SourceLocation Loc) const override {
13932     return assertNotNull(
13933         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13934   }
13935 
13936   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13937 };
13938 
13939 class MemberBuilder: public ExprBuilder {
13940   const ExprBuilder &Builder;
13941   QualType Type;
13942   CXXScopeSpec SS;
13943   bool IsArrow;
13944   LookupResult &MemberLookup;
13945 
13946 public:
13947   Expr *build(Sema &S, SourceLocation Loc) const override {
13948     return assertNotNull(S.BuildMemberReferenceExpr(
13949         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13950         nullptr, MemberLookup, nullptr, nullptr).get());
13951   }
13952 
13953   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13954                 LookupResult &MemberLookup)
13955       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13956         MemberLookup(MemberLookup) {}
13957 };
13958 
13959 class MoveCastBuilder: public ExprBuilder {
13960   const ExprBuilder &Builder;
13961 
13962 public:
13963   Expr *build(Sema &S, SourceLocation Loc) const override {
13964     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13965   }
13966 
13967   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13968 };
13969 
13970 class LvalueConvBuilder: public ExprBuilder {
13971   const ExprBuilder &Builder;
13972 
13973 public:
13974   Expr *build(Sema &S, SourceLocation Loc) const override {
13975     return assertNotNull(
13976         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13977   }
13978 
13979   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13980 };
13981 
13982 class SubscriptBuilder: public ExprBuilder {
13983   const ExprBuilder &Base;
13984   const ExprBuilder &Index;
13985 
13986 public:
13987   Expr *build(Sema &S, SourceLocation Loc) const override {
13988     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13989         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13990   }
13991 
13992   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13993       : Base(Base), Index(Index) {}
13994 };
13995 
13996 } // end anonymous namespace
13997 
13998 /// When generating a defaulted copy or move assignment operator, if a field
13999 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14000 /// do so. This optimization only applies for arrays of scalars, and for arrays
14001 /// of class type where the selected copy/move-assignment operator is trivial.
14002 static StmtResult
14003 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14004                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
14005   // Compute the size of the memory buffer to be copied.
14006   QualType SizeType = S.Context.getSizeType();
14007   llvm::APInt Size(S.Context.getTypeSize(SizeType),
14008                    S.Context.getTypeSizeInChars(T).getQuantity());
14009 
14010   // Take the address of the field references for "from" and "to". We
14011   // directly construct UnaryOperators here because semantic analysis
14012   // does not permit us to take the address of an xvalue.
14013   Expr *From = FromB.build(S, Loc);
14014   From = UnaryOperator::Create(
14015       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14016       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14017   Expr *To = ToB.build(S, Loc);
14018   To = UnaryOperator::Create(
14019       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14020       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14021 
14022   const Type *E = T->getBaseElementTypeUnsafe();
14023   bool NeedsCollectableMemCpy =
14024       E->isRecordType() &&
14025       E->castAs<RecordType>()->getDecl()->hasObjectMember();
14026 
14027   // Create a reference to the __builtin_objc_memmove_collectable function
14028   StringRef MemCpyName = NeedsCollectableMemCpy ?
14029     "__builtin_objc_memmove_collectable" :
14030     "__builtin_memcpy";
14031   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14032                  Sema::LookupOrdinaryName);
14033   S.LookupName(R, S.TUScope, true);
14034 
14035   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14036   if (!MemCpy)
14037     // Something went horribly wrong earlier, and we will have complained
14038     // about it.
14039     return StmtError();
14040 
14041   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14042                                             VK_PRValue, Loc, nullptr);
14043   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14044 
14045   Expr *CallArgs[] = {
14046     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14047   };
14048   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14049                                     Loc, CallArgs, Loc);
14050 
14051   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14052   return Call.getAs<Stmt>();
14053 }
14054 
14055 /// Builds a statement that copies/moves the given entity from \p From to
14056 /// \c To.
14057 ///
14058 /// This routine is used to copy/move the members of a class with an
14059 /// implicitly-declared copy/move assignment operator. When the entities being
14060 /// copied are arrays, this routine builds for loops to copy them.
14061 ///
14062 /// \param S The Sema object used for type-checking.
14063 ///
14064 /// \param Loc The location where the implicit copy/move is being generated.
14065 ///
14066 /// \param T The type of the expressions being copied/moved. Both expressions
14067 /// must have this type.
14068 ///
14069 /// \param To The expression we are copying/moving to.
14070 ///
14071 /// \param From The expression we are copying/moving from.
14072 ///
14073 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14074 /// Otherwise, it's a non-static member subobject.
14075 ///
14076 /// \param Copying Whether we're copying or moving.
14077 ///
14078 /// \param Depth Internal parameter recording the depth of the recursion.
14079 ///
14080 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14081 /// if a memcpy should be used instead.
14082 static StmtResult
14083 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14084                                  const ExprBuilder &To, const ExprBuilder &From,
14085                                  bool CopyingBaseSubobject, bool Copying,
14086                                  unsigned Depth = 0) {
14087   // C++11 [class.copy]p28:
14088   //   Each subobject is assigned in the manner appropriate to its type:
14089   //
14090   //     - if the subobject is of class type, as if by a call to operator= with
14091   //       the subobject as the object expression and the corresponding
14092   //       subobject of x as a single function argument (as if by explicit
14093   //       qualification; that is, ignoring any possible virtual overriding
14094   //       functions in more derived classes);
14095   //
14096   // C++03 [class.copy]p13:
14097   //     - if the subobject is of class type, the copy assignment operator for
14098   //       the class is used (as if by explicit qualification; that is,
14099   //       ignoring any possible virtual overriding functions in more derived
14100   //       classes);
14101   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14102     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14103 
14104     // Look for operator=.
14105     DeclarationName Name
14106       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14107     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14108     S.LookupQualifiedName(OpLookup, ClassDecl, false);
14109 
14110     // Prior to C++11, filter out any result that isn't a copy/move-assignment
14111     // operator.
14112     if (!S.getLangOpts().CPlusPlus11) {
14113       LookupResult::Filter F = OpLookup.makeFilter();
14114       while (F.hasNext()) {
14115         NamedDecl *D = F.next();
14116         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14117           if (Method->isCopyAssignmentOperator() ||
14118               (!Copying && Method->isMoveAssignmentOperator()))
14119             continue;
14120 
14121         F.erase();
14122       }
14123       F.done();
14124     }
14125 
14126     // Suppress the protected check (C++ [class.protected]) for each of the
14127     // assignment operators we found. This strange dance is required when
14128     // we're assigning via a base classes's copy-assignment operator. To
14129     // ensure that we're getting the right base class subobject (without
14130     // ambiguities), we need to cast "this" to that subobject type; to
14131     // ensure that we don't go through the virtual call mechanism, we need
14132     // to qualify the operator= name with the base class (see below). However,
14133     // this means that if the base class has a protected copy assignment
14134     // operator, the protected member access check will fail. So, we
14135     // rewrite "protected" access to "public" access in this case, since we
14136     // know by construction that we're calling from a derived class.
14137     if (CopyingBaseSubobject) {
14138       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14139            L != LEnd; ++L) {
14140         if (L.getAccess() == AS_protected)
14141           L.setAccess(AS_public);
14142       }
14143     }
14144 
14145     // Create the nested-name-specifier that will be used to qualify the
14146     // reference to operator=; this is required to suppress the virtual
14147     // call mechanism.
14148     CXXScopeSpec SS;
14149     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14150     SS.MakeTrivial(S.Context,
14151                    NestedNameSpecifier::Create(S.Context, nullptr, false,
14152                                                CanonicalT),
14153                    Loc);
14154 
14155     // Create the reference to operator=.
14156     ExprResult OpEqualRef
14157       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14158                                    SS, /*TemplateKWLoc=*/SourceLocation(),
14159                                    /*FirstQualifierInScope=*/nullptr,
14160                                    OpLookup,
14161                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
14162                                    /*SuppressQualifierCheck=*/true);
14163     if (OpEqualRef.isInvalid())
14164       return StmtError();
14165 
14166     // Build the call to the assignment operator.
14167 
14168     Expr *FromInst = From.build(S, Loc);
14169     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14170                                                   OpEqualRef.getAs<Expr>(),
14171                                                   Loc, FromInst, Loc);
14172     if (Call.isInvalid())
14173       return StmtError();
14174 
14175     // If we built a call to a trivial 'operator=' while copying an array,
14176     // bail out. We'll replace the whole shebang with a memcpy.
14177     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14178     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14179       return StmtResult((Stmt*)nullptr);
14180 
14181     // Convert to an expression-statement, and clean up any produced
14182     // temporaries.
14183     return S.ActOnExprStmt(Call);
14184   }
14185 
14186   //     - if the subobject is of scalar type, the built-in assignment
14187   //       operator is used.
14188   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14189   if (!ArrayTy) {
14190     ExprResult Assignment = S.CreateBuiltinBinOp(
14191         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14192     if (Assignment.isInvalid())
14193       return StmtError();
14194     return S.ActOnExprStmt(Assignment);
14195   }
14196 
14197   //     - if the subobject is an array, each element is assigned, in the
14198   //       manner appropriate to the element type;
14199 
14200   // Construct a loop over the array bounds, e.g.,
14201   //
14202   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14203   //
14204   // that will copy each of the array elements.
14205   QualType SizeType = S.Context.getSizeType();
14206 
14207   // Create the iteration variable.
14208   IdentifierInfo *IterationVarName = nullptr;
14209   {
14210     SmallString<8> Str;
14211     llvm::raw_svector_ostream OS(Str);
14212     OS << "__i" << Depth;
14213     IterationVarName = &S.Context.Idents.get(OS.str());
14214   }
14215   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14216                                           IterationVarName, SizeType,
14217                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14218                                           SC_None);
14219 
14220   // Initialize the iteration variable to zero.
14221   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14222   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14223 
14224   // Creates a reference to the iteration variable.
14225   RefBuilder IterationVarRef(IterationVar, SizeType);
14226   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14227 
14228   // Create the DeclStmt that holds the iteration variable.
14229   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14230 
14231   // Subscript the "from" and "to" expressions with the iteration variable.
14232   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14233   MoveCastBuilder FromIndexMove(FromIndexCopy);
14234   const ExprBuilder *FromIndex;
14235   if (Copying)
14236     FromIndex = &FromIndexCopy;
14237   else
14238     FromIndex = &FromIndexMove;
14239 
14240   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14241 
14242   // Build the copy/move for an individual element of the array.
14243   StmtResult Copy =
14244     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14245                                      ToIndex, *FromIndex, CopyingBaseSubobject,
14246                                      Copying, Depth + 1);
14247   // Bail out if copying fails or if we determined that we should use memcpy.
14248   if (Copy.isInvalid() || !Copy.get())
14249     return Copy;
14250 
14251   // Create the comparison against the array bound.
14252   llvm::APInt Upper
14253     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14254   Expr *Comparison = BinaryOperator::Create(
14255       S.Context, IterationVarRefRVal.build(S, Loc),
14256       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14257       S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14258       S.CurFPFeatureOverrides());
14259 
14260   // Create the pre-increment of the iteration variable. We can determine
14261   // whether the increment will overflow based on the value of the array
14262   // bound.
14263   Expr *Increment = UnaryOperator::Create(
14264       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14265       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14266 
14267   // Construct the loop that copies all elements of this array.
14268   return S.ActOnForStmt(
14269       Loc, Loc, InitStmt,
14270       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14271       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14272 }
14273 
14274 static StmtResult
14275 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14276                       const ExprBuilder &To, const ExprBuilder &From,
14277                       bool CopyingBaseSubobject, bool Copying) {
14278   // Maybe we should use a memcpy?
14279   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14280       T.isTriviallyCopyableType(S.Context))
14281     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14282 
14283   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14284                                                      CopyingBaseSubobject,
14285                                                      Copying, 0));
14286 
14287   // If we ended up picking a trivial assignment operator for an array of a
14288   // non-trivially-copyable class type, just emit a memcpy.
14289   if (!Result.isInvalid() && !Result.get())
14290     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14291 
14292   return Result;
14293 }
14294 
14295 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14296   // Note: The following rules are largely analoguous to the copy
14297   // constructor rules. Note that virtual bases are not taken into account
14298   // for determining the argument type of the operator. Note also that
14299   // operators taking an object instead of a reference are allowed.
14300   assert(ClassDecl->needsImplicitCopyAssignment());
14301 
14302   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14303   if (DSM.isAlreadyBeingDeclared())
14304     return nullptr;
14305 
14306   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14307   LangAS AS = getDefaultCXXMethodAddrSpace();
14308   if (AS != LangAS::Default)
14309     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14310   QualType RetType = Context.getLValueReferenceType(ArgType);
14311   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14312   if (Const)
14313     ArgType = ArgType.withConst();
14314 
14315   ArgType = Context.getLValueReferenceType(ArgType);
14316 
14317   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14318                                                      CXXCopyAssignment,
14319                                                      Const);
14320 
14321   //   An implicitly-declared copy assignment operator is an inline public
14322   //   member of its class.
14323   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14324   SourceLocation ClassLoc = ClassDecl->getLocation();
14325   DeclarationNameInfo NameInfo(Name, ClassLoc);
14326   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14327       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14328       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14329       getCurFPFeatures().isFPConstrained(),
14330       /*isInline=*/true,
14331       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14332       SourceLocation());
14333   CopyAssignment->setAccess(AS_public);
14334   CopyAssignment->setDefaulted();
14335   CopyAssignment->setImplicit();
14336 
14337   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14338 
14339   if (getLangOpts().CUDA)
14340     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14341                                             CopyAssignment,
14342                                             /* ConstRHS */ Const,
14343                                             /* Diagnose */ false);
14344 
14345   // Add the parameter to the operator.
14346   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14347                                                ClassLoc, ClassLoc,
14348                                                /*Id=*/nullptr, ArgType,
14349                                                /*TInfo=*/nullptr, SC_None,
14350                                                nullptr);
14351   CopyAssignment->setParams(FromParam);
14352 
14353   CopyAssignment->setTrivial(
14354     ClassDecl->needsOverloadResolutionForCopyAssignment()
14355       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14356       : ClassDecl->hasTrivialCopyAssignment());
14357 
14358   // Note that we have added this copy-assignment operator.
14359   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14360 
14361   Scope *S = getScopeForContext(ClassDecl);
14362   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14363 
14364   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14365     ClassDecl->setImplicitCopyAssignmentIsDeleted();
14366     SetDeclDeleted(CopyAssignment, ClassLoc);
14367   }
14368 
14369   if (S)
14370     PushOnScopeChains(CopyAssignment, S, false);
14371   ClassDecl->addDecl(CopyAssignment);
14372 
14373   return CopyAssignment;
14374 }
14375 
14376 /// Diagnose an implicit copy operation for a class which is odr-used, but
14377 /// which is deprecated because the class has a user-declared copy constructor,
14378 /// copy assignment operator, or destructor.
14379 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14380   assert(CopyOp->isImplicit());
14381 
14382   CXXRecordDecl *RD = CopyOp->getParent();
14383   CXXMethodDecl *UserDeclaredOperation = nullptr;
14384 
14385   // In Microsoft mode, assignment operations don't affect constructors and
14386   // vice versa.
14387   if (RD->hasUserDeclaredDestructor()) {
14388     UserDeclaredOperation = RD->getDestructor();
14389   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14390              RD->hasUserDeclaredCopyConstructor() &&
14391              !S.getLangOpts().MSVCCompat) {
14392     // Find any user-declared copy constructor.
14393     for (auto *I : RD->ctors()) {
14394       if (I->isCopyConstructor()) {
14395         UserDeclaredOperation = I;
14396         break;
14397       }
14398     }
14399     assert(UserDeclaredOperation);
14400   } else if (isa<CXXConstructorDecl>(CopyOp) &&
14401              RD->hasUserDeclaredCopyAssignment() &&
14402              !S.getLangOpts().MSVCCompat) {
14403     // Find any user-declared move assignment operator.
14404     for (auto *I : RD->methods()) {
14405       if (I->isCopyAssignmentOperator()) {
14406         UserDeclaredOperation = I;
14407         break;
14408       }
14409     }
14410     assert(UserDeclaredOperation);
14411   }
14412 
14413   if (UserDeclaredOperation) {
14414     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14415     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14416     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14417     unsigned DiagID =
14418         (UDOIsUserProvided && UDOIsDestructor)
14419             ? diag::warn_deprecated_copy_with_user_provided_dtor
14420         : (UDOIsUserProvided && !UDOIsDestructor)
14421             ? diag::warn_deprecated_copy_with_user_provided_copy
14422         : (!UDOIsUserProvided && UDOIsDestructor)
14423             ? diag::warn_deprecated_copy_with_dtor
14424             : diag::warn_deprecated_copy;
14425     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14426         << RD << IsCopyAssignment;
14427   }
14428 }
14429 
14430 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14431                                         CXXMethodDecl *CopyAssignOperator) {
14432   assert((CopyAssignOperator->isDefaulted() &&
14433           CopyAssignOperator->isOverloadedOperator() &&
14434           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14435           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14436           !CopyAssignOperator->isDeleted()) &&
14437          "DefineImplicitCopyAssignment called for wrong function");
14438   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14439     return;
14440 
14441   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14442   if (ClassDecl->isInvalidDecl()) {
14443     CopyAssignOperator->setInvalidDecl();
14444     return;
14445   }
14446 
14447   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14448 
14449   // The exception specification is needed because we are defining the
14450   // function.
14451   ResolveExceptionSpec(CurrentLocation,
14452                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14453 
14454   // Add a context note for diagnostics produced after this point.
14455   Scope.addContextNote(CurrentLocation);
14456 
14457   // C++11 [class.copy]p18:
14458   //   The [definition of an implicitly declared copy assignment operator] is
14459   //   deprecated if the class has a user-declared copy constructor or a
14460   //   user-declared destructor.
14461   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14462     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14463 
14464   // C++0x [class.copy]p30:
14465   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14466   //   for a non-union class X performs memberwise copy assignment of its
14467   //   subobjects. The direct base classes of X are assigned first, in the
14468   //   order of their declaration in the base-specifier-list, and then the
14469   //   immediate non-static data members of X are assigned, in the order in
14470   //   which they were declared in the class definition.
14471 
14472   // The statements that form the synthesized function body.
14473   SmallVector<Stmt*, 8> Statements;
14474 
14475   // The parameter for the "other" object, which we are copying from.
14476   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14477   Qualifiers OtherQuals = Other->getType().getQualifiers();
14478   QualType OtherRefType = Other->getType();
14479   if (const LValueReferenceType *OtherRef
14480                                 = OtherRefType->getAs<LValueReferenceType>()) {
14481     OtherRefType = OtherRef->getPointeeType();
14482     OtherQuals = OtherRefType.getQualifiers();
14483   }
14484 
14485   // Our location for everything implicitly-generated.
14486   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14487                            ? CopyAssignOperator->getEndLoc()
14488                            : CopyAssignOperator->getLocation();
14489 
14490   // Builds a DeclRefExpr for the "other" object.
14491   RefBuilder OtherRef(Other, OtherRefType);
14492 
14493   // Builds the "this" pointer.
14494   ThisBuilder This;
14495 
14496   // Assign base classes.
14497   bool Invalid = false;
14498   for (auto &Base : ClassDecl->bases()) {
14499     // Form the assignment:
14500     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14501     QualType BaseType = Base.getType().getUnqualifiedType();
14502     if (!BaseType->isRecordType()) {
14503       Invalid = true;
14504       continue;
14505     }
14506 
14507     CXXCastPath BasePath;
14508     BasePath.push_back(&Base);
14509 
14510     // Construct the "from" expression, which is an implicit cast to the
14511     // appropriately-qualified base type.
14512     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14513                      VK_LValue, BasePath);
14514 
14515     // Dereference "this".
14516     DerefBuilder DerefThis(This);
14517     CastBuilder To(DerefThis,
14518                    Context.getQualifiedType(
14519                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14520                    VK_LValue, BasePath);
14521 
14522     // Build the copy.
14523     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14524                                             To, From,
14525                                             /*CopyingBaseSubobject=*/true,
14526                                             /*Copying=*/true);
14527     if (Copy.isInvalid()) {
14528       CopyAssignOperator->setInvalidDecl();
14529       return;
14530     }
14531 
14532     // Success! Record the copy.
14533     Statements.push_back(Copy.getAs<Expr>());
14534   }
14535 
14536   // Assign non-static members.
14537   for (auto *Field : ClassDecl->fields()) {
14538     // FIXME: We should form some kind of AST representation for the implied
14539     // memcpy in a union copy operation.
14540     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14541       continue;
14542 
14543     if (Field->isInvalidDecl()) {
14544       Invalid = true;
14545       continue;
14546     }
14547 
14548     // Check for members of reference type; we can't copy those.
14549     if (Field->getType()->isReferenceType()) {
14550       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14551         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14552       Diag(Field->getLocation(), diag::note_declared_at);
14553       Invalid = true;
14554       continue;
14555     }
14556 
14557     // Check for members of const-qualified, non-class type.
14558     QualType BaseType = Context.getBaseElementType(Field->getType());
14559     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14560       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14561         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14562       Diag(Field->getLocation(), diag::note_declared_at);
14563       Invalid = true;
14564       continue;
14565     }
14566 
14567     // Suppress assigning zero-width bitfields.
14568     if (Field->isZeroLengthBitField(Context))
14569       continue;
14570 
14571     QualType FieldType = Field->getType().getNonReferenceType();
14572     if (FieldType->isIncompleteArrayType()) {
14573       assert(ClassDecl->hasFlexibleArrayMember() &&
14574              "Incomplete array type is not valid");
14575       continue;
14576     }
14577 
14578     // Build references to the field in the object we're copying from and to.
14579     CXXScopeSpec SS; // Intentionally empty
14580     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14581                               LookupMemberName);
14582     MemberLookup.addDecl(Field);
14583     MemberLookup.resolveKind();
14584 
14585     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14586 
14587     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14588 
14589     // Build the copy of this field.
14590     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14591                                             To, From,
14592                                             /*CopyingBaseSubobject=*/false,
14593                                             /*Copying=*/true);
14594     if (Copy.isInvalid()) {
14595       CopyAssignOperator->setInvalidDecl();
14596       return;
14597     }
14598 
14599     // Success! Record the copy.
14600     Statements.push_back(Copy.getAs<Stmt>());
14601   }
14602 
14603   if (!Invalid) {
14604     // Add a "return *this;"
14605     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14606 
14607     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14608     if (Return.isInvalid())
14609       Invalid = true;
14610     else
14611       Statements.push_back(Return.getAs<Stmt>());
14612   }
14613 
14614   if (Invalid) {
14615     CopyAssignOperator->setInvalidDecl();
14616     return;
14617   }
14618 
14619   StmtResult Body;
14620   {
14621     CompoundScopeRAII CompoundScope(*this);
14622     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14623                              /*isStmtExpr=*/false);
14624     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14625   }
14626   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14627   CopyAssignOperator->markUsed(Context);
14628 
14629   if (ASTMutationListener *L = getASTMutationListener()) {
14630     L->CompletedImplicitDefinition(CopyAssignOperator);
14631   }
14632 }
14633 
14634 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14635   assert(ClassDecl->needsImplicitMoveAssignment());
14636 
14637   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14638   if (DSM.isAlreadyBeingDeclared())
14639     return nullptr;
14640 
14641   // Note: The following rules are largely analoguous to the move
14642   // constructor rules.
14643 
14644   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14645   LangAS AS = getDefaultCXXMethodAddrSpace();
14646   if (AS != LangAS::Default)
14647     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14648   QualType RetType = Context.getLValueReferenceType(ArgType);
14649   ArgType = Context.getRValueReferenceType(ArgType);
14650 
14651   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14652                                                      CXXMoveAssignment,
14653                                                      false);
14654 
14655   //   An implicitly-declared move assignment operator is an inline public
14656   //   member of its class.
14657   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14658   SourceLocation ClassLoc = ClassDecl->getLocation();
14659   DeclarationNameInfo NameInfo(Name, ClassLoc);
14660   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14661       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14662       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14663       getCurFPFeatures().isFPConstrained(),
14664       /*isInline=*/true,
14665       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14666       SourceLocation());
14667   MoveAssignment->setAccess(AS_public);
14668   MoveAssignment->setDefaulted();
14669   MoveAssignment->setImplicit();
14670 
14671   setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14672 
14673   if (getLangOpts().CUDA)
14674     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14675                                             MoveAssignment,
14676                                             /* ConstRHS */ false,
14677                                             /* Diagnose */ false);
14678 
14679   // Add the parameter to the operator.
14680   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14681                                                ClassLoc, ClassLoc,
14682                                                /*Id=*/nullptr, ArgType,
14683                                                /*TInfo=*/nullptr, SC_None,
14684                                                nullptr);
14685   MoveAssignment->setParams(FromParam);
14686 
14687   MoveAssignment->setTrivial(
14688     ClassDecl->needsOverloadResolutionForMoveAssignment()
14689       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14690       : ClassDecl->hasTrivialMoveAssignment());
14691 
14692   // Note that we have added this copy-assignment operator.
14693   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14694 
14695   Scope *S = getScopeForContext(ClassDecl);
14696   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14697 
14698   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14699     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14700     SetDeclDeleted(MoveAssignment, ClassLoc);
14701   }
14702 
14703   if (S)
14704     PushOnScopeChains(MoveAssignment, S, false);
14705   ClassDecl->addDecl(MoveAssignment);
14706 
14707   return MoveAssignment;
14708 }
14709 
14710 /// Check if we're implicitly defining a move assignment operator for a class
14711 /// with virtual bases. Such a move assignment might move-assign the virtual
14712 /// base multiple times.
14713 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14714                                                SourceLocation CurrentLocation) {
14715   assert(!Class->isDependentContext() && "should not define dependent move");
14716 
14717   // Only a virtual base could get implicitly move-assigned multiple times.
14718   // Only a non-trivial move assignment can observe this. We only want to
14719   // diagnose if we implicitly define an assignment operator that assigns
14720   // two base classes, both of which move-assign the same virtual base.
14721   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14722       Class->getNumBases() < 2)
14723     return;
14724 
14725   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14726   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14727   VBaseMap VBases;
14728 
14729   for (auto &BI : Class->bases()) {
14730     Worklist.push_back(&BI);
14731     while (!Worklist.empty()) {
14732       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14733       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14734 
14735       // If the base has no non-trivial move assignment operators,
14736       // we don't care about moves from it.
14737       if (!Base->hasNonTrivialMoveAssignment())
14738         continue;
14739 
14740       // If there's nothing virtual here, skip it.
14741       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14742         continue;
14743 
14744       // If we're not actually going to call a move assignment for this base,
14745       // or the selected move assignment is trivial, skip it.
14746       Sema::SpecialMemberOverloadResult SMOR =
14747         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14748                               /*ConstArg*/false, /*VolatileArg*/false,
14749                               /*RValueThis*/true, /*ConstThis*/false,
14750                               /*VolatileThis*/false);
14751       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14752           !SMOR.getMethod()->isMoveAssignmentOperator())
14753         continue;
14754 
14755       if (BaseSpec->isVirtual()) {
14756         // We're going to move-assign this virtual base, and its move
14757         // assignment operator is not trivial. If this can happen for
14758         // multiple distinct direct bases of Class, diagnose it. (If it
14759         // only happens in one base, we'll diagnose it when synthesizing
14760         // that base class's move assignment operator.)
14761         CXXBaseSpecifier *&Existing =
14762             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14763                 .first->second;
14764         if (Existing && Existing != &BI) {
14765           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14766             << Class << Base;
14767           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14768               << (Base->getCanonicalDecl() ==
14769                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14770               << Base << Existing->getType() << Existing->getSourceRange();
14771           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14772               << (Base->getCanonicalDecl() ==
14773                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14774               << Base << BI.getType() << BaseSpec->getSourceRange();
14775 
14776           // Only diagnose each vbase once.
14777           Existing = nullptr;
14778         }
14779       } else {
14780         // Only walk over bases that have defaulted move assignment operators.
14781         // We assume that any user-provided move assignment operator handles
14782         // the multiple-moves-of-vbase case itself somehow.
14783         if (!SMOR.getMethod()->isDefaulted())
14784           continue;
14785 
14786         // We're going to move the base classes of Base. Add them to the list.
14787         llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
14788       }
14789     }
14790   }
14791 }
14792 
14793 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14794                                         CXXMethodDecl *MoveAssignOperator) {
14795   assert((MoveAssignOperator->isDefaulted() &&
14796           MoveAssignOperator->isOverloadedOperator() &&
14797           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14798           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14799           !MoveAssignOperator->isDeleted()) &&
14800          "DefineImplicitMoveAssignment called for wrong function");
14801   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14802     return;
14803 
14804   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14805   if (ClassDecl->isInvalidDecl()) {
14806     MoveAssignOperator->setInvalidDecl();
14807     return;
14808   }
14809 
14810   // C++0x [class.copy]p28:
14811   //   The implicitly-defined or move assignment operator for a non-union class
14812   //   X performs memberwise move assignment of its subobjects. The direct base
14813   //   classes of X are assigned first, in the order of their declaration in the
14814   //   base-specifier-list, and then the immediate non-static data members of X
14815   //   are assigned, in the order in which they were declared in the class
14816   //   definition.
14817 
14818   // Issue a warning if our implicit move assignment operator will move
14819   // from a virtual base more than once.
14820   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14821 
14822   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14823 
14824   // The exception specification is needed because we are defining the
14825   // function.
14826   ResolveExceptionSpec(CurrentLocation,
14827                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14828 
14829   // Add a context note for diagnostics produced after this point.
14830   Scope.addContextNote(CurrentLocation);
14831 
14832   // The statements that form the synthesized function body.
14833   SmallVector<Stmt*, 8> Statements;
14834 
14835   // The parameter for the "other" object, which we are move from.
14836   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14837   QualType OtherRefType =
14838       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14839 
14840   // Our location for everything implicitly-generated.
14841   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14842                            ? MoveAssignOperator->getEndLoc()
14843                            : MoveAssignOperator->getLocation();
14844 
14845   // Builds a reference to the "other" object.
14846   RefBuilder OtherRef(Other, OtherRefType);
14847   // Cast to rvalue.
14848   MoveCastBuilder MoveOther(OtherRef);
14849 
14850   // Builds the "this" pointer.
14851   ThisBuilder This;
14852 
14853   // Assign base classes.
14854   bool Invalid = false;
14855   for (auto &Base : ClassDecl->bases()) {
14856     // C++11 [class.copy]p28:
14857     //   It is unspecified whether subobjects representing virtual base classes
14858     //   are assigned more than once by the implicitly-defined copy assignment
14859     //   operator.
14860     // FIXME: Do not assign to a vbase that will be assigned by some other base
14861     // class. For a move-assignment, this can result in the vbase being moved
14862     // multiple times.
14863 
14864     // Form the assignment:
14865     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14866     QualType BaseType = Base.getType().getUnqualifiedType();
14867     if (!BaseType->isRecordType()) {
14868       Invalid = true;
14869       continue;
14870     }
14871 
14872     CXXCastPath BasePath;
14873     BasePath.push_back(&Base);
14874 
14875     // Construct the "from" expression, which is an implicit cast to the
14876     // appropriately-qualified base type.
14877     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14878 
14879     // Dereference "this".
14880     DerefBuilder DerefThis(This);
14881 
14882     // Implicitly cast "this" to the appropriately-qualified base type.
14883     CastBuilder To(DerefThis,
14884                    Context.getQualifiedType(
14885                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14886                    VK_LValue, BasePath);
14887 
14888     // Build the move.
14889     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14890                                             To, From,
14891                                             /*CopyingBaseSubobject=*/true,
14892                                             /*Copying=*/false);
14893     if (Move.isInvalid()) {
14894       MoveAssignOperator->setInvalidDecl();
14895       return;
14896     }
14897 
14898     // Success! Record the move.
14899     Statements.push_back(Move.getAs<Expr>());
14900   }
14901 
14902   // Assign non-static members.
14903   for (auto *Field : ClassDecl->fields()) {
14904     // FIXME: We should form some kind of AST representation for the implied
14905     // memcpy in a union copy operation.
14906     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14907       continue;
14908 
14909     if (Field->isInvalidDecl()) {
14910       Invalid = true;
14911       continue;
14912     }
14913 
14914     // Check for members of reference type; we can't move those.
14915     if (Field->getType()->isReferenceType()) {
14916       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14917         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14918       Diag(Field->getLocation(), diag::note_declared_at);
14919       Invalid = true;
14920       continue;
14921     }
14922 
14923     // Check for members of const-qualified, non-class type.
14924     QualType BaseType = Context.getBaseElementType(Field->getType());
14925     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14926       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14927         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14928       Diag(Field->getLocation(), diag::note_declared_at);
14929       Invalid = true;
14930       continue;
14931     }
14932 
14933     // Suppress assigning zero-width bitfields.
14934     if (Field->isZeroLengthBitField(Context))
14935       continue;
14936 
14937     QualType FieldType = Field->getType().getNonReferenceType();
14938     if (FieldType->isIncompleteArrayType()) {
14939       assert(ClassDecl->hasFlexibleArrayMember() &&
14940              "Incomplete array type is not valid");
14941       continue;
14942     }
14943 
14944     // Build references to the field in the object we're copying from and to.
14945     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14946                               LookupMemberName);
14947     MemberLookup.addDecl(Field);
14948     MemberLookup.resolveKind();
14949     MemberBuilder From(MoveOther, OtherRefType,
14950                        /*IsArrow=*/false, MemberLookup);
14951     MemberBuilder To(This, getCurrentThisType(),
14952                      /*IsArrow=*/true, MemberLookup);
14953 
14954     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14955         "Member reference with rvalue base must be rvalue except for reference "
14956         "members, which aren't allowed for move assignment.");
14957 
14958     // Build the move of this field.
14959     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14960                                             To, From,
14961                                             /*CopyingBaseSubobject=*/false,
14962                                             /*Copying=*/false);
14963     if (Move.isInvalid()) {
14964       MoveAssignOperator->setInvalidDecl();
14965       return;
14966     }
14967 
14968     // Success! Record the copy.
14969     Statements.push_back(Move.getAs<Stmt>());
14970   }
14971 
14972   if (!Invalid) {
14973     // Add a "return *this;"
14974     ExprResult ThisObj =
14975         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14976 
14977     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14978     if (Return.isInvalid())
14979       Invalid = true;
14980     else
14981       Statements.push_back(Return.getAs<Stmt>());
14982   }
14983 
14984   if (Invalid) {
14985     MoveAssignOperator->setInvalidDecl();
14986     return;
14987   }
14988 
14989   StmtResult Body;
14990   {
14991     CompoundScopeRAII CompoundScope(*this);
14992     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14993                              /*isStmtExpr=*/false);
14994     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14995   }
14996   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14997   MoveAssignOperator->markUsed(Context);
14998 
14999   if (ASTMutationListener *L = getASTMutationListener()) {
15000     L->CompletedImplicitDefinition(MoveAssignOperator);
15001   }
15002 }
15003 
15004 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15005                                                     CXXRecordDecl *ClassDecl) {
15006   // C++ [class.copy]p4:
15007   //   If the class definition does not explicitly declare a copy
15008   //   constructor, one is declared implicitly.
15009   assert(ClassDecl->needsImplicitCopyConstructor());
15010 
15011   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15012   if (DSM.isAlreadyBeingDeclared())
15013     return nullptr;
15014 
15015   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15016   QualType ArgType = ClassType;
15017   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15018   if (Const)
15019     ArgType = ArgType.withConst();
15020 
15021   LangAS AS = getDefaultCXXMethodAddrSpace();
15022   if (AS != LangAS::Default)
15023     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15024 
15025   ArgType = Context.getLValueReferenceType(ArgType);
15026 
15027   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15028                                                      CXXCopyConstructor,
15029                                                      Const);
15030 
15031   DeclarationName Name
15032     = Context.DeclarationNames.getCXXConstructorName(
15033                                            Context.getCanonicalType(ClassType));
15034   SourceLocation ClassLoc = ClassDecl->getLocation();
15035   DeclarationNameInfo NameInfo(Name, ClassLoc);
15036 
15037   //   An implicitly-declared copy constructor is an inline public
15038   //   member of its class.
15039   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15040       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15041       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15042       /*isInline=*/true,
15043       /*isImplicitlyDeclared=*/true,
15044       Constexpr ? ConstexprSpecKind::Constexpr
15045                 : ConstexprSpecKind::Unspecified);
15046   CopyConstructor->setAccess(AS_public);
15047   CopyConstructor->setDefaulted();
15048 
15049   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15050 
15051   if (getLangOpts().CUDA)
15052     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15053                                             CopyConstructor,
15054                                             /* ConstRHS */ Const,
15055                                             /* Diagnose */ false);
15056 
15057   // During template instantiation of special member functions we need a
15058   // reliable TypeSourceInfo for the parameter types in order to allow functions
15059   // to be substituted.
15060   TypeSourceInfo *TSI = nullptr;
15061   if (inTemplateInstantiation() && ClassDecl->isLambda())
15062     TSI = Context.getTrivialTypeSourceInfo(ArgType);
15063 
15064   // Add the parameter to the constructor.
15065   ParmVarDecl *FromParam =
15066       ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15067                           /*IdentifierInfo=*/nullptr, ArgType,
15068                           /*TInfo=*/TSI, SC_None, nullptr);
15069   CopyConstructor->setParams(FromParam);
15070 
15071   CopyConstructor->setTrivial(
15072       ClassDecl->needsOverloadResolutionForCopyConstructor()
15073           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15074           : ClassDecl->hasTrivialCopyConstructor());
15075 
15076   CopyConstructor->setTrivialForCall(
15077       ClassDecl->hasAttr<TrivialABIAttr>() ||
15078       (ClassDecl->needsOverloadResolutionForCopyConstructor()
15079            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15080              TAH_ConsiderTrivialABI)
15081            : ClassDecl->hasTrivialCopyConstructorForCall()));
15082 
15083   // Note that we have declared this constructor.
15084   ++getASTContext().NumImplicitCopyConstructorsDeclared;
15085 
15086   Scope *S = getScopeForContext(ClassDecl);
15087   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15088 
15089   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15090     ClassDecl->setImplicitCopyConstructorIsDeleted();
15091     SetDeclDeleted(CopyConstructor, ClassLoc);
15092   }
15093 
15094   if (S)
15095     PushOnScopeChains(CopyConstructor, S, false);
15096   ClassDecl->addDecl(CopyConstructor);
15097 
15098   return CopyConstructor;
15099 }
15100 
15101 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15102                                          CXXConstructorDecl *CopyConstructor) {
15103   assert((CopyConstructor->isDefaulted() &&
15104           CopyConstructor->isCopyConstructor() &&
15105           !CopyConstructor->doesThisDeclarationHaveABody() &&
15106           !CopyConstructor->isDeleted()) &&
15107          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15108   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15109     return;
15110 
15111   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15112   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15113 
15114   SynthesizedFunctionScope Scope(*this, CopyConstructor);
15115 
15116   // The exception specification is needed because we are defining the
15117   // function.
15118   ResolveExceptionSpec(CurrentLocation,
15119                        CopyConstructor->getType()->castAs<FunctionProtoType>());
15120   MarkVTableUsed(CurrentLocation, ClassDecl);
15121 
15122   // Add a context note for diagnostics produced after this point.
15123   Scope.addContextNote(CurrentLocation);
15124 
15125   // C++11 [class.copy]p7:
15126   //   The [definition of an implicitly declared copy constructor] is
15127   //   deprecated if the class has a user-declared copy assignment operator
15128   //   or a user-declared destructor.
15129   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15130     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15131 
15132   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15133     CopyConstructor->setInvalidDecl();
15134   }  else {
15135     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15136                              ? CopyConstructor->getEndLoc()
15137                              : CopyConstructor->getLocation();
15138     Sema::CompoundScopeRAII CompoundScope(*this);
15139     CopyConstructor->setBody(
15140         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
15141     CopyConstructor->markUsed(Context);
15142   }
15143 
15144   if (ASTMutationListener *L = getASTMutationListener()) {
15145     L->CompletedImplicitDefinition(CopyConstructor);
15146   }
15147 }
15148 
15149 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15150                                                     CXXRecordDecl *ClassDecl) {
15151   assert(ClassDecl->needsImplicitMoveConstructor());
15152 
15153   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15154   if (DSM.isAlreadyBeingDeclared())
15155     return nullptr;
15156 
15157   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15158 
15159   QualType ArgType = ClassType;
15160   LangAS AS = getDefaultCXXMethodAddrSpace();
15161   if (AS != LangAS::Default)
15162     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15163   ArgType = Context.getRValueReferenceType(ArgType);
15164 
15165   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15166                                                      CXXMoveConstructor,
15167                                                      false);
15168 
15169   DeclarationName Name
15170     = Context.DeclarationNames.getCXXConstructorName(
15171                                            Context.getCanonicalType(ClassType));
15172   SourceLocation ClassLoc = ClassDecl->getLocation();
15173   DeclarationNameInfo NameInfo(Name, ClassLoc);
15174 
15175   // C++11 [class.copy]p11:
15176   //   An implicitly-declared copy/move constructor is an inline public
15177   //   member of its class.
15178   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15179       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15180       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15181       /*isInline=*/true,
15182       /*isImplicitlyDeclared=*/true,
15183       Constexpr ? ConstexprSpecKind::Constexpr
15184                 : ConstexprSpecKind::Unspecified);
15185   MoveConstructor->setAccess(AS_public);
15186   MoveConstructor->setDefaulted();
15187 
15188   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15189 
15190   if (getLangOpts().CUDA)
15191     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15192                                             MoveConstructor,
15193                                             /* ConstRHS */ false,
15194                                             /* Diagnose */ false);
15195 
15196   // Add the parameter to the constructor.
15197   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15198                                                ClassLoc, ClassLoc,
15199                                                /*IdentifierInfo=*/nullptr,
15200                                                ArgType, /*TInfo=*/nullptr,
15201                                                SC_None, nullptr);
15202   MoveConstructor->setParams(FromParam);
15203 
15204   MoveConstructor->setTrivial(
15205       ClassDecl->needsOverloadResolutionForMoveConstructor()
15206           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15207           : ClassDecl->hasTrivialMoveConstructor());
15208 
15209   MoveConstructor->setTrivialForCall(
15210       ClassDecl->hasAttr<TrivialABIAttr>() ||
15211       (ClassDecl->needsOverloadResolutionForMoveConstructor()
15212            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15213                                     TAH_ConsiderTrivialABI)
15214            : ClassDecl->hasTrivialMoveConstructorForCall()));
15215 
15216   // Note that we have declared this constructor.
15217   ++getASTContext().NumImplicitMoveConstructorsDeclared;
15218 
15219   Scope *S = getScopeForContext(ClassDecl);
15220   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15221 
15222   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15223     ClassDecl->setImplicitMoveConstructorIsDeleted();
15224     SetDeclDeleted(MoveConstructor, ClassLoc);
15225   }
15226 
15227   if (S)
15228     PushOnScopeChains(MoveConstructor, S, false);
15229   ClassDecl->addDecl(MoveConstructor);
15230 
15231   return MoveConstructor;
15232 }
15233 
15234 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15235                                          CXXConstructorDecl *MoveConstructor) {
15236   assert((MoveConstructor->isDefaulted() &&
15237           MoveConstructor->isMoveConstructor() &&
15238           !MoveConstructor->doesThisDeclarationHaveABody() &&
15239           !MoveConstructor->isDeleted()) &&
15240          "DefineImplicitMoveConstructor - call it for implicit move ctor");
15241   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15242     return;
15243 
15244   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15245   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15246 
15247   SynthesizedFunctionScope Scope(*this, MoveConstructor);
15248 
15249   // The exception specification is needed because we are defining the
15250   // function.
15251   ResolveExceptionSpec(CurrentLocation,
15252                        MoveConstructor->getType()->castAs<FunctionProtoType>());
15253   MarkVTableUsed(CurrentLocation, ClassDecl);
15254 
15255   // Add a context note for diagnostics produced after this point.
15256   Scope.addContextNote(CurrentLocation);
15257 
15258   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15259     MoveConstructor->setInvalidDecl();
15260   } else {
15261     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15262                              ? MoveConstructor->getEndLoc()
15263                              : MoveConstructor->getLocation();
15264     Sema::CompoundScopeRAII CompoundScope(*this);
15265     MoveConstructor->setBody(ActOnCompoundStmt(
15266         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
15267     MoveConstructor->markUsed(Context);
15268   }
15269 
15270   if (ASTMutationListener *L = getASTMutationListener()) {
15271     L->CompletedImplicitDefinition(MoveConstructor);
15272   }
15273 }
15274 
15275 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15276   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15277 }
15278 
15279 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15280                             SourceLocation CurrentLocation,
15281                             CXXConversionDecl *Conv) {
15282   SynthesizedFunctionScope Scope(*this, Conv);
15283   assert(!Conv->getReturnType()->isUndeducedType());
15284 
15285   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15286   CallingConv CC =
15287       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15288 
15289   CXXRecordDecl *Lambda = Conv->getParent();
15290   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15291   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
15292 
15293   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15294     CallOp = InstantiateFunctionDeclaration(
15295         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15296     if (!CallOp)
15297       return;
15298 
15299     Invoker = InstantiateFunctionDeclaration(
15300         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15301     if (!Invoker)
15302       return;
15303   }
15304 
15305   if (CallOp->isInvalidDecl())
15306     return;
15307 
15308   // Mark the call operator referenced (and add to pending instantiations
15309   // if necessary).
15310   // For both the conversion and static-invoker template specializations
15311   // we construct their body's in this function, so no need to add them
15312   // to the PendingInstantiations.
15313   MarkFunctionReferenced(CurrentLocation, CallOp);
15314 
15315   // Fill in the __invoke function with a dummy implementation. IR generation
15316   // will fill in the actual details. Update its type in case it contained
15317   // an 'auto'.
15318   Invoker->markUsed(Context);
15319   Invoker->setReferenced();
15320   Invoker->setType(Conv->getReturnType()->getPointeeType());
15321   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15322 
15323   // Construct the body of the conversion function { return __invoke; }.
15324   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
15325                                        VK_LValue, Conv->getLocation());
15326   assert(FunctionRef && "Can't refer to __invoke function?");
15327   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15328   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
15329                                      Conv->getLocation()));
15330   Conv->markUsed(Context);
15331   Conv->setReferenced();
15332 
15333   if (ASTMutationListener *L = getASTMutationListener()) {
15334     L->CompletedImplicitDefinition(Conv);
15335     L->CompletedImplicitDefinition(Invoker);
15336   }
15337 }
15338 
15339 
15340 
15341 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15342        SourceLocation CurrentLocation,
15343        CXXConversionDecl *Conv)
15344 {
15345   assert(!Conv->getParent()->isGenericLambda());
15346 
15347   SynthesizedFunctionScope Scope(*this, Conv);
15348 
15349   // Copy-initialize the lambda object as needed to capture it.
15350   Expr *This = ActOnCXXThis(CurrentLocation).get();
15351   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15352 
15353   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15354                                                         Conv->getLocation(),
15355                                                         Conv, DerefThis);
15356 
15357   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15358   // behavior.  Note that only the general conversion function does this
15359   // (since it's unusable otherwise); in the case where we inline the
15360   // block literal, it has block literal lifetime semantics.
15361   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15362     BuildBlock = ImplicitCastExpr::Create(
15363         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15364         BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15365 
15366   if (BuildBlock.isInvalid()) {
15367     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15368     Conv->setInvalidDecl();
15369     return;
15370   }
15371 
15372   // Create the return statement that returns the block from the conversion
15373   // function.
15374   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15375   if (Return.isInvalid()) {
15376     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15377     Conv->setInvalidDecl();
15378     return;
15379   }
15380 
15381   // Set the body of the conversion function.
15382   Stmt *ReturnS = Return.get();
15383   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
15384                                      Conv->getLocation()));
15385   Conv->markUsed(Context);
15386 
15387   // We're done; notify the mutation listener, if any.
15388   if (ASTMutationListener *L = getASTMutationListener()) {
15389     L->CompletedImplicitDefinition(Conv);
15390   }
15391 }
15392 
15393 /// Determine whether the given list arguments contains exactly one
15394 /// "real" (non-default) argument.
15395 static bool hasOneRealArgument(MultiExprArg Args) {
15396   switch (Args.size()) {
15397   case 0:
15398     return false;
15399 
15400   default:
15401     if (!Args[1]->isDefaultArgument())
15402       return false;
15403 
15404     LLVM_FALLTHROUGH;
15405   case 1:
15406     return !Args[0]->isDefaultArgument();
15407   }
15408 
15409   return false;
15410 }
15411 
15412 ExprResult
15413 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15414                             NamedDecl *FoundDecl,
15415                             CXXConstructorDecl *Constructor,
15416                             MultiExprArg ExprArgs,
15417                             bool HadMultipleCandidates,
15418                             bool IsListInitialization,
15419                             bool IsStdInitListInitialization,
15420                             bool RequiresZeroInit,
15421                             unsigned ConstructKind,
15422                             SourceRange ParenRange) {
15423   bool Elidable = false;
15424 
15425   // C++0x [class.copy]p34:
15426   //   When certain criteria are met, an implementation is allowed to
15427   //   omit the copy/move construction of a class object, even if the
15428   //   copy/move constructor and/or destructor for the object have
15429   //   side effects. [...]
15430   //     - when a temporary class object that has not been bound to a
15431   //       reference (12.2) would be copied/moved to a class object
15432   //       with the same cv-unqualified type, the copy/move operation
15433   //       can be omitted by constructing the temporary object
15434   //       directly into the target of the omitted copy/move
15435   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15436       // FIXME: Converting constructors should also be accepted.
15437       // But to fix this, the logic that digs down into a CXXConstructExpr
15438       // to find the source object needs to handle it.
15439       // Right now it assumes the source object is passed directly as the
15440       // first argument.
15441       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15442     Expr *SubExpr = ExprArgs[0];
15443     // FIXME: Per above, this is also incorrect if we want to accept
15444     //        converting constructors, as isTemporaryObject will
15445     //        reject temporaries with different type from the
15446     //        CXXRecord itself.
15447     Elidable = SubExpr->isTemporaryObject(
15448         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15449   }
15450 
15451   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15452                                FoundDecl, Constructor,
15453                                Elidable, ExprArgs, HadMultipleCandidates,
15454                                IsListInitialization,
15455                                IsStdInitListInitialization, RequiresZeroInit,
15456                                ConstructKind, ParenRange);
15457 }
15458 
15459 ExprResult
15460 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15461                             NamedDecl *FoundDecl,
15462                             CXXConstructorDecl *Constructor,
15463                             bool Elidable,
15464                             MultiExprArg ExprArgs,
15465                             bool HadMultipleCandidates,
15466                             bool IsListInitialization,
15467                             bool IsStdInitListInitialization,
15468                             bool RequiresZeroInit,
15469                             unsigned ConstructKind,
15470                             SourceRange ParenRange) {
15471   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15472     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15473     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15474       return ExprError();
15475   }
15476 
15477   return BuildCXXConstructExpr(
15478       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15479       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15480       RequiresZeroInit, ConstructKind, ParenRange);
15481 }
15482 
15483 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15484 /// including handling of its default argument expressions.
15485 ExprResult
15486 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15487                             CXXConstructorDecl *Constructor,
15488                             bool Elidable,
15489                             MultiExprArg ExprArgs,
15490                             bool HadMultipleCandidates,
15491                             bool IsListInitialization,
15492                             bool IsStdInitListInitialization,
15493                             bool RequiresZeroInit,
15494                             unsigned ConstructKind,
15495                             SourceRange ParenRange) {
15496   assert(declaresSameEntity(
15497              Constructor->getParent(),
15498              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15499          "given constructor for wrong type");
15500   MarkFunctionReferenced(ConstructLoc, Constructor);
15501   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15502     return ExprError();
15503   if (getLangOpts().SYCLIsDevice &&
15504       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15505     return ExprError();
15506 
15507   return CheckForImmediateInvocation(
15508       CXXConstructExpr::Create(
15509           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15510           HadMultipleCandidates, IsListInitialization,
15511           IsStdInitListInitialization, RequiresZeroInit,
15512           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15513           ParenRange),
15514       Constructor);
15515 }
15516 
15517 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15518   assert(Field->hasInClassInitializer());
15519 
15520   // If we already have the in-class initializer nothing needs to be done.
15521   if (Field->getInClassInitializer())
15522     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15523 
15524   // If we might have already tried and failed to instantiate, don't try again.
15525   if (Field->isInvalidDecl())
15526     return ExprError();
15527 
15528   // Maybe we haven't instantiated the in-class initializer. Go check the
15529   // pattern FieldDecl to see if it has one.
15530   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15531 
15532   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15533     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15534     DeclContext::lookup_result Lookup =
15535         ClassPattern->lookup(Field->getDeclName());
15536 
15537     FieldDecl *Pattern = nullptr;
15538     for (auto L : Lookup) {
15539       if (isa<FieldDecl>(L)) {
15540         Pattern = cast<FieldDecl>(L);
15541         break;
15542       }
15543     }
15544     assert(Pattern && "We must have set the Pattern!");
15545 
15546     if (!Pattern->hasInClassInitializer() ||
15547         InstantiateInClassInitializer(Loc, Field, Pattern,
15548                                       getTemplateInstantiationArgs(Field))) {
15549       // Don't diagnose this again.
15550       Field->setInvalidDecl();
15551       return ExprError();
15552     }
15553     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15554   }
15555 
15556   // DR1351:
15557   //   If the brace-or-equal-initializer of a non-static data member
15558   //   invokes a defaulted default constructor of its class or of an
15559   //   enclosing class in a potentially evaluated subexpression, the
15560   //   program is ill-formed.
15561   //
15562   // This resolution is unworkable: the exception specification of the
15563   // default constructor can be needed in an unevaluated context, in
15564   // particular, in the operand of a noexcept-expression, and we can be
15565   // unable to compute an exception specification for an enclosed class.
15566   //
15567   // Any attempt to resolve the exception specification of a defaulted default
15568   // constructor before the initializer is lexically complete will ultimately
15569   // come here at which point we can diagnose it.
15570   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15571   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15572       << OutermostClass << Field;
15573   Diag(Field->getEndLoc(),
15574        diag::note_default_member_initializer_not_yet_parsed);
15575   // Recover by marking the field invalid, unless we're in a SFINAE context.
15576   if (!isSFINAEContext())
15577     Field->setInvalidDecl();
15578   return ExprError();
15579 }
15580 
15581 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15582   if (VD->isInvalidDecl()) return;
15583   // If initializing the variable failed, don't also diagnose problems with
15584   // the destructor, they're likely related.
15585   if (VD->getInit() && VD->getInit()->containsErrors())
15586     return;
15587 
15588   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15589   if (ClassDecl->isInvalidDecl()) return;
15590   if (ClassDecl->hasIrrelevantDestructor()) return;
15591   if (ClassDecl->isDependentContext()) return;
15592 
15593   if (VD->isNoDestroy(getASTContext()))
15594     return;
15595 
15596   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15597 
15598   // If this is an array, we'll require the destructor during initialization, so
15599   // we can skip over this. We still want to emit exit-time destructor warnings
15600   // though.
15601   if (!VD->getType()->isArrayType()) {
15602     MarkFunctionReferenced(VD->getLocation(), Destructor);
15603     CheckDestructorAccess(VD->getLocation(), Destructor,
15604                           PDiag(diag::err_access_dtor_var)
15605                               << VD->getDeclName() << VD->getType());
15606     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15607   }
15608 
15609   if (Destructor->isTrivial()) return;
15610 
15611   // If the destructor is constexpr, check whether the variable has constant
15612   // destruction now.
15613   if (Destructor->isConstexpr()) {
15614     bool HasConstantInit = false;
15615     if (VD->getInit() && !VD->getInit()->isValueDependent())
15616       HasConstantInit = VD->evaluateValue();
15617     SmallVector<PartialDiagnosticAt, 8> Notes;
15618     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15619         HasConstantInit) {
15620       Diag(VD->getLocation(),
15621            diag::err_constexpr_var_requires_const_destruction) << VD;
15622       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15623         Diag(Notes[I].first, Notes[I].second);
15624     }
15625   }
15626 
15627   if (!VD->hasGlobalStorage()) return;
15628 
15629   // Emit warning for non-trivial dtor in global scope (a real global,
15630   // class-static, function-static).
15631   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15632 
15633   // TODO: this should be re-enabled for static locals by !CXAAtExit
15634   if (!VD->isStaticLocal())
15635     Diag(VD->getLocation(), diag::warn_global_destructor);
15636 }
15637 
15638 /// Given a constructor and the set of arguments provided for the
15639 /// constructor, convert the arguments and add any required default arguments
15640 /// to form a proper call to this constructor.
15641 ///
15642 /// \returns true if an error occurred, false otherwise.
15643 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15644                                    QualType DeclInitType, MultiExprArg ArgsPtr,
15645                                    SourceLocation Loc,
15646                                    SmallVectorImpl<Expr *> &ConvertedArgs,
15647                                    bool AllowExplicit,
15648                                    bool IsListInitialization) {
15649   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15650   unsigned NumArgs = ArgsPtr.size();
15651   Expr **Args = ArgsPtr.data();
15652 
15653   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15654   unsigned NumParams = Proto->getNumParams();
15655 
15656   // If too few arguments are available, we'll fill in the rest with defaults.
15657   if (NumArgs < NumParams)
15658     ConvertedArgs.reserve(NumParams);
15659   else
15660     ConvertedArgs.reserve(NumArgs);
15661 
15662   VariadicCallType CallType =
15663     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15664   SmallVector<Expr *, 8> AllArgs;
15665   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15666                                         Proto, 0,
15667                                         llvm::makeArrayRef(Args, NumArgs),
15668                                         AllArgs,
15669                                         CallType, AllowExplicit,
15670                                         IsListInitialization);
15671   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15672 
15673   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15674 
15675   CheckConstructorCall(Constructor, DeclInitType,
15676                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15677                        Proto, Loc);
15678 
15679   return Invalid;
15680 }
15681 
15682 static inline bool
15683 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15684                                        const FunctionDecl *FnDecl) {
15685   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15686   if (isa<NamespaceDecl>(DC)) {
15687     return SemaRef.Diag(FnDecl->getLocation(),
15688                         diag::err_operator_new_delete_declared_in_namespace)
15689       << FnDecl->getDeclName();
15690   }
15691 
15692   if (isa<TranslationUnitDecl>(DC) &&
15693       FnDecl->getStorageClass() == SC_Static) {
15694     return SemaRef.Diag(FnDecl->getLocation(),
15695                         diag::err_operator_new_delete_declared_static)
15696       << FnDecl->getDeclName();
15697   }
15698 
15699   return false;
15700 }
15701 
15702 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15703                                              const PointerType *PtrTy) {
15704   auto &Ctx = SemaRef.Context;
15705   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15706   PtrQuals.removeAddressSpace();
15707   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15708       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15709 }
15710 
15711 static inline bool
15712 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15713                             CanQualType ExpectedResultType,
15714                             CanQualType ExpectedFirstParamType,
15715                             unsigned DependentParamTypeDiag,
15716                             unsigned InvalidParamTypeDiag) {
15717   QualType ResultType =
15718       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15719 
15720   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15721     // The operator is valid on any address space for OpenCL.
15722     // Drop address space from actual and expected result types.
15723     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15724       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15725 
15726     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15727       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15728   }
15729 
15730   // Check that the result type is what we expect.
15731   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15732     // Reject even if the type is dependent; an operator delete function is
15733     // required to have a non-dependent result type.
15734     return SemaRef.Diag(
15735                FnDecl->getLocation(),
15736                ResultType->isDependentType()
15737                    ? diag::err_operator_new_delete_dependent_result_type
15738                    : diag::err_operator_new_delete_invalid_result_type)
15739            << FnDecl->getDeclName() << ExpectedResultType;
15740   }
15741 
15742   // A function template must have at least 2 parameters.
15743   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15744     return SemaRef.Diag(FnDecl->getLocation(),
15745                       diag::err_operator_new_delete_template_too_few_parameters)
15746         << FnDecl->getDeclName();
15747 
15748   // The function decl must have at least 1 parameter.
15749   if (FnDecl->getNumParams() == 0)
15750     return SemaRef.Diag(FnDecl->getLocation(),
15751                         diag::err_operator_new_delete_too_few_parameters)
15752       << FnDecl->getDeclName();
15753 
15754   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15755   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15756     // The operator is valid on any address space for OpenCL.
15757     // Drop address space from actual and expected first parameter types.
15758     if (const auto *PtrTy =
15759             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15760       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15761 
15762     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15763       ExpectedFirstParamType =
15764           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15765   }
15766 
15767   // Check that the first parameter type is what we expect.
15768   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15769       ExpectedFirstParamType) {
15770     // The first parameter type is not allowed to be dependent. As a tentative
15771     // DR resolution, we allow a dependent parameter type if it is the right
15772     // type anyway, to allow destroying operator delete in class templates.
15773     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15774                                                    ? DependentParamTypeDiag
15775                                                    : InvalidParamTypeDiag)
15776            << FnDecl->getDeclName() << ExpectedFirstParamType;
15777   }
15778 
15779   return false;
15780 }
15781 
15782 static bool
15783 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15784   // C++ [basic.stc.dynamic.allocation]p1:
15785   //   A program is ill-formed if an allocation function is declared in a
15786   //   namespace scope other than global scope or declared static in global
15787   //   scope.
15788   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15789     return true;
15790 
15791   CanQualType SizeTy =
15792     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15793 
15794   // C++ [basic.stc.dynamic.allocation]p1:
15795   //  The return type shall be void*. The first parameter shall have type
15796   //  std::size_t.
15797   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15798                                   SizeTy,
15799                                   diag::err_operator_new_dependent_param_type,
15800                                   diag::err_operator_new_param_type))
15801     return true;
15802 
15803   // C++ [basic.stc.dynamic.allocation]p1:
15804   //  The first parameter shall not have an associated default argument.
15805   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15806     return SemaRef.Diag(FnDecl->getLocation(),
15807                         diag::err_operator_new_default_arg)
15808       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15809 
15810   return false;
15811 }
15812 
15813 static bool
15814 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15815   // C++ [basic.stc.dynamic.deallocation]p1:
15816   //   A program is ill-formed if deallocation functions are declared in a
15817   //   namespace scope other than global scope or declared static in global
15818   //   scope.
15819   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15820     return true;
15821 
15822   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15823 
15824   // C++ P0722:
15825   //   Within a class C, the first parameter of a destroying operator delete
15826   //   shall be of type C *. The first parameter of any other deallocation
15827   //   function shall be of type void *.
15828   CanQualType ExpectedFirstParamType =
15829       MD && MD->isDestroyingOperatorDelete()
15830           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15831                 SemaRef.Context.getRecordType(MD->getParent())))
15832           : SemaRef.Context.VoidPtrTy;
15833 
15834   // C++ [basic.stc.dynamic.deallocation]p2:
15835   //   Each deallocation function shall return void
15836   if (CheckOperatorNewDeleteTypes(
15837           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15838           diag::err_operator_delete_dependent_param_type,
15839           diag::err_operator_delete_param_type))
15840     return true;
15841 
15842   // C++ P0722:
15843   //   A destroying operator delete shall be a usual deallocation function.
15844   if (MD && !MD->getParent()->isDependentContext() &&
15845       MD->isDestroyingOperatorDelete() &&
15846       !SemaRef.isUsualDeallocationFunction(MD)) {
15847     SemaRef.Diag(MD->getLocation(),
15848                  diag::err_destroying_operator_delete_not_usual);
15849     return true;
15850   }
15851 
15852   return false;
15853 }
15854 
15855 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15856 /// of this overloaded operator is well-formed. If so, returns false;
15857 /// otherwise, emits appropriate diagnostics and returns true.
15858 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15859   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15860          "Expected an overloaded operator declaration");
15861 
15862   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15863 
15864   // C++ [over.oper]p5:
15865   //   The allocation and deallocation functions, operator new,
15866   //   operator new[], operator delete and operator delete[], are
15867   //   described completely in 3.7.3. The attributes and restrictions
15868   //   found in the rest of this subclause do not apply to them unless
15869   //   explicitly stated in 3.7.3.
15870   if (Op == OO_Delete || Op == OO_Array_Delete)
15871     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15872 
15873   if (Op == OO_New || Op == OO_Array_New)
15874     return CheckOperatorNewDeclaration(*this, FnDecl);
15875 
15876   // C++ [over.oper]p6:
15877   //   An operator function shall either be a non-static member
15878   //   function or be a non-member function and have at least one
15879   //   parameter whose type is a class, a reference to a class, an
15880   //   enumeration, or a reference to an enumeration.
15881   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15882     if (MethodDecl->isStatic())
15883       return Diag(FnDecl->getLocation(),
15884                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15885   } else {
15886     bool ClassOrEnumParam = false;
15887     for (auto Param : FnDecl->parameters()) {
15888       QualType ParamType = Param->getType().getNonReferenceType();
15889       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15890           ParamType->isEnumeralType()) {
15891         ClassOrEnumParam = true;
15892         break;
15893       }
15894     }
15895 
15896     if (!ClassOrEnumParam)
15897       return Diag(FnDecl->getLocation(),
15898                   diag::err_operator_overload_needs_class_or_enum)
15899         << FnDecl->getDeclName();
15900   }
15901 
15902   // C++ [over.oper]p8:
15903   //   An operator function cannot have default arguments (8.3.6),
15904   //   except where explicitly stated below.
15905   //
15906   // Only the function-call operator (C++ [over.call]p1) and the subscript
15907   // operator (CWG2507) allow default arguments.
15908   if (Op != OO_Call) {
15909     ParmVarDecl *FirstDefaultedParam = nullptr;
15910     for (auto Param : FnDecl->parameters()) {
15911       if (Param->hasDefaultArg()) {
15912         FirstDefaultedParam = Param;
15913         break;
15914       }
15915     }
15916     if (FirstDefaultedParam) {
15917       if (Op == OO_Subscript) {
15918         Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15919                                         ? diag::ext_subscript_overload
15920                                         : diag::error_subscript_overload)
15921             << FnDecl->getDeclName() << 1
15922             << FirstDefaultedParam->getDefaultArgRange();
15923       } else {
15924         return Diag(FirstDefaultedParam->getLocation(),
15925                     diag::err_operator_overload_default_arg)
15926                << FnDecl->getDeclName()
15927                << FirstDefaultedParam->getDefaultArgRange();
15928       }
15929     }
15930   }
15931 
15932   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15933     { false, false, false }
15934 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15935     , { Unary, Binary, MemberOnly }
15936 #include "clang/Basic/OperatorKinds.def"
15937   };
15938 
15939   bool CanBeUnaryOperator = OperatorUses[Op][0];
15940   bool CanBeBinaryOperator = OperatorUses[Op][1];
15941   bool MustBeMemberOperator = OperatorUses[Op][2];
15942 
15943   // C++ [over.oper]p8:
15944   //   [...] Operator functions cannot have more or fewer parameters
15945   //   than the number required for the corresponding operator, as
15946   //   described in the rest of this subclause.
15947   unsigned NumParams = FnDecl->getNumParams()
15948                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15949   if (Op != OO_Call && Op != OO_Subscript &&
15950       ((NumParams == 1 && !CanBeUnaryOperator) ||
15951        (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
15952        (NumParams > 2))) {
15953     // We have the wrong number of parameters.
15954     unsigned ErrorKind;
15955     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15956       ErrorKind = 2;  // 2 -> unary or binary.
15957     } else if (CanBeUnaryOperator) {
15958       ErrorKind = 0;  // 0 -> unary
15959     } else {
15960       assert(CanBeBinaryOperator &&
15961              "All non-call overloaded operators are unary or binary!");
15962       ErrorKind = 1;  // 1 -> binary
15963     }
15964     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15965       << FnDecl->getDeclName() << NumParams << ErrorKind;
15966   }
15967 
15968   if (Op == OO_Subscript && NumParams != 2) {
15969     Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15970                                     ? diag::ext_subscript_overload
15971                                     : diag::error_subscript_overload)
15972         << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
15973   }
15974 
15975   // Overloaded operators other than operator() and operator[] cannot be
15976   // variadic.
15977   if (Op != OO_Call &&
15978       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15979     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15980            << FnDecl->getDeclName();
15981   }
15982 
15983   // Some operators must be non-static member functions.
15984   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15985     return Diag(FnDecl->getLocation(),
15986                 diag::err_operator_overload_must_be_member)
15987       << FnDecl->getDeclName();
15988   }
15989 
15990   // C++ [over.inc]p1:
15991   //   The user-defined function called operator++ implements the
15992   //   prefix and postfix ++ operator. If this function is a member
15993   //   function with no parameters, or a non-member function with one
15994   //   parameter of class or enumeration type, it defines the prefix
15995   //   increment operator ++ for objects of that type. If the function
15996   //   is a member function with one parameter (which shall be of type
15997   //   int) or a non-member function with two parameters (the second
15998   //   of which shall be of type int), it defines the postfix
15999   //   increment operator ++ for objects of that type.
16000   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16001     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16002     QualType ParamType = LastParam->getType();
16003 
16004     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16005         !ParamType->isDependentType())
16006       return Diag(LastParam->getLocation(),
16007                   diag::err_operator_overload_post_incdec_must_be_int)
16008         << LastParam->getType() << (Op == OO_MinusMinus);
16009   }
16010 
16011   return false;
16012 }
16013 
16014 static bool
16015 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16016                                           FunctionTemplateDecl *TpDecl) {
16017   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16018 
16019   // Must have one or two template parameters.
16020   if (TemplateParams->size() == 1) {
16021     NonTypeTemplateParmDecl *PmDecl =
16022         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16023 
16024     // The template parameter must be a char parameter pack.
16025     if (PmDecl && PmDecl->isTemplateParameterPack() &&
16026         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16027       return false;
16028 
16029     // C++20 [over.literal]p5:
16030     //   A string literal operator template is a literal operator template
16031     //   whose template-parameter-list comprises a single non-type
16032     //   template-parameter of class type.
16033     //
16034     // As a DR resolution, we also allow placeholders for deduced class
16035     // template specializations.
16036     if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16037         !PmDecl->isTemplateParameterPack() &&
16038         (PmDecl->getType()->isRecordType() ||
16039          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16040       return false;
16041   } else if (TemplateParams->size() == 2) {
16042     TemplateTypeParmDecl *PmType =
16043         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16044     NonTypeTemplateParmDecl *PmArgs =
16045         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16046 
16047     // The second template parameter must be a parameter pack with the
16048     // first template parameter as its type.
16049     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16050         PmArgs->isTemplateParameterPack()) {
16051       const TemplateTypeParmType *TArgs =
16052           PmArgs->getType()->getAs<TemplateTypeParmType>();
16053       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16054           TArgs->getIndex() == PmType->getIndex()) {
16055         if (!SemaRef.inTemplateInstantiation())
16056           SemaRef.Diag(TpDecl->getLocation(),
16057                        diag::ext_string_literal_operator_template);
16058         return false;
16059       }
16060     }
16061   }
16062 
16063   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16064                diag::err_literal_operator_template)
16065       << TpDecl->getTemplateParameters()->getSourceRange();
16066   return true;
16067 }
16068 
16069 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16070 /// of this literal operator function is well-formed. If so, returns
16071 /// false; otherwise, emits appropriate diagnostics and returns true.
16072 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16073   if (isa<CXXMethodDecl>(FnDecl)) {
16074     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16075       << FnDecl->getDeclName();
16076     return true;
16077   }
16078 
16079   if (FnDecl->isExternC()) {
16080     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16081     if (const LinkageSpecDecl *LSD =
16082             FnDecl->getDeclContext()->getExternCContext())
16083       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16084     return true;
16085   }
16086 
16087   // This might be the definition of a literal operator template.
16088   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16089 
16090   // This might be a specialization of a literal operator template.
16091   if (!TpDecl)
16092     TpDecl = FnDecl->getPrimaryTemplate();
16093 
16094   // template <char...> type operator "" name() and
16095   // template <class T, T...> type operator "" name() are the only valid
16096   // template signatures, and the only valid signatures with no parameters.
16097   //
16098   // C++20 also allows template <SomeClass T> type operator "" name().
16099   if (TpDecl) {
16100     if (FnDecl->param_size() != 0) {
16101       Diag(FnDecl->getLocation(),
16102            diag::err_literal_operator_template_with_params);
16103       return true;
16104     }
16105 
16106     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16107       return true;
16108 
16109   } else if (FnDecl->param_size() == 1) {
16110     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16111 
16112     QualType ParamType = Param->getType().getUnqualifiedType();
16113 
16114     // Only unsigned long long int, long double, any character type, and const
16115     // char * are allowed as the only parameters.
16116     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16117         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16118         Context.hasSameType(ParamType, Context.CharTy) ||
16119         Context.hasSameType(ParamType, Context.WideCharTy) ||
16120         Context.hasSameType(ParamType, Context.Char8Ty) ||
16121         Context.hasSameType(ParamType, Context.Char16Ty) ||
16122         Context.hasSameType(ParamType, Context.Char32Ty)) {
16123     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16124       QualType InnerType = Ptr->getPointeeType();
16125 
16126       // Pointer parameter must be a const char *.
16127       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16128                                 Context.CharTy) &&
16129             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16130         Diag(Param->getSourceRange().getBegin(),
16131              diag::err_literal_operator_param)
16132             << ParamType << "'const char *'" << Param->getSourceRange();
16133         return true;
16134       }
16135 
16136     } else if (ParamType->isRealFloatingType()) {
16137       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16138           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16139       return true;
16140 
16141     } else if (ParamType->isIntegerType()) {
16142       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16143           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16144       return true;
16145 
16146     } else {
16147       Diag(Param->getSourceRange().getBegin(),
16148            diag::err_literal_operator_invalid_param)
16149           << ParamType << Param->getSourceRange();
16150       return true;
16151     }
16152 
16153   } else if (FnDecl->param_size() == 2) {
16154     FunctionDecl::param_iterator Param = FnDecl->param_begin();
16155 
16156     // First, verify that the first parameter is correct.
16157 
16158     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16159 
16160     // Two parameter function must have a pointer to const as a
16161     // first parameter; let's strip those qualifiers.
16162     const PointerType *PT = FirstParamType->getAs<PointerType>();
16163 
16164     if (!PT) {
16165       Diag((*Param)->getSourceRange().getBegin(),
16166            diag::err_literal_operator_param)
16167           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16168       return true;
16169     }
16170 
16171     QualType PointeeType = PT->getPointeeType();
16172     // First parameter must be const
16173     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16174       Diag((*Param)->getSourceRange().getBegin(),
16175            diag::err_literal_operator_param)
16176           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16177       return true;
16178     }
16179 
16180     QualType InnerType = PointeeType.getUnqualifiedType();
16181     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16182     // const char32_t* are allowed as the first parameter to a two-parameter
16183     // function
16184     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16185           Context.hasSameType(InnerType, Context.WideCharTy) ||
16186           Context.hasSameType(InnerType, Context.Char8Ty) ||
16187           Context.hasSameType(InnerType, Context.Char16Ty) ||
16188           Context.hasSameType(InnerType, Context.Char32Ty))) {
16189       Diag((*Param)->getSourceRange().getBegin(),
16190            diag::err_literal_operator_param)
16191           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16192       return true;
16193     }
16194 
16195     // Move on to the second and final parameter.
16196     ++Param;
16197 
16198     // The second parameter must be a std::size_t.
16199     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16200     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16201       Diag((*Param)->getSourceRange().getBegin(),
16202            diag::err_literal_operator_param)
16203           << SecondParamType << Context.getSizeType()
16204           << (*Param)->getSourceRange();
16205       return true;
16206     }
16207   } else {
16208     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16209     return true;
16210   }
16211 
16212   // Parameters are good.
16213 
16214   // A parameter-declaration-clause containing a default argument is not
16215   // equivalent to any of the permitted forms.
16216   for (auto Param : FnDecl->parameters()) {
16217     if (Param->hasDefaultArg()) {
16218       Diag(Param->getDefaultArgRange().getBegin(),
16219            diag::err_literal_operator_default_argument)
16220         << Param->getDefaultArgRange();
16221       break;
16222     }
16223   }
16224 
16225   StringRef LiteralName
16226     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16227   if (LiteralName[0] != '_' &&
16228       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16229     // C++11 [usrlit.suffix]p1:
16230     //   Literal suffix identifiers that do not start with an underscore
16231     //   are reserved for future standardization.
16232     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16233       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16234   }
16235 
16236   return false;
16237 }
16238 
16239 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16240 /// linkage specification, including the language and (if present)
16241 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16242 /// language string literal. LBraceLoc, if valid, provides the location of
16243 /// the '{' brace. Otherwise, this linkage specification does not
16244 /// have any braces.
16245 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16246                                            Expr *LangStr,
16247                                            SourceLocation LBraceLoc) {
16248   StringLiteral *Lit = cast<StringLiteral>(LangStr);
16249   if (!Lit->isAscii()) {
16250     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16251       << LangStr->getSourceRange();
16252     return nullptr;
16253   }
16254 
16255   StringRef Lang = Lit->getString();
16256   LinkageSpecDecl::LanguageIDs Language;
16257   if (Lang == "C")
16258     Language = LinkageSpecDecl::lang_c;
16259   else if (Lang == "C++")
16260     Language = LinkageSpecDecl::lang_cxx;
16261   else {
16262     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16263       << LangStr->getSourceRange();
16264     return nullptr;
16265   }
16266 
16267   // FIXME: Add all the various semantics of linkage specifications
16268 
16269   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16270                                                LangStr->getExprLoc(), Language,
16271                                                LBraceLoc.isValid());
16272 
16273   /// C++ [module.unit]p7.2.3
16274   /// - Otherwise, if the declaration
16275   ///   - ...
16276   ///   - ...
16277   ///   - appears within a linkage-specification,
16278   ///   it is attached to the global module.
16279   ///
16280   /// If the declaration is already in global module fragment, we don't
16281   /// need to attach it again.
16282   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16283     Module *GlobalModule =
16284         PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
16285     D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16286     D->setLocalOwningModule(GlobalModule);
16287   }
16288 
16289   CurContext->addDecl(D);
16290   PushDeclContext(S, D);
16291   return D;
16292 }
16293 
16294 /// ActOnFinishLinkageSpecification - Complete the definition of
16295 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16296 /// valid, it's the position of the closing '}' brace in a linkage
16297 /// specification that uses braces.
16298 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16299                                             Decl *LinkageSpec,
16300                                             SourceLocation RBraceLoc) {
16301   if (RBraceLoc.isValid()) {
16302     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16303     LSDecl->setRBraceLoc(RBraceLoc);
16304   }
16305 
16306   // If the current module doesn't has Parent, it implies that the
16307   // LinkageSpec isn't in the module created by itself. So we don't
16308   // need to pop it.
16309   if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16310       getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
16311     PopGlobalModuleFragment();
16312 
16313   PopDeclContext();
16314   return LinkageSpec;
16315 }
16316 
16317 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16318                                   const ParsedAttributesView &AttrList,
16319                                   SourceLocation SemiLoc) {
16320   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16321   // Attribute declarations appertain to empty declaration so we handle
16322   // them here.
16323   ProcessDeclAttributeList(S, ED, AttrList);
16324 
16325   CurContext->addDecl(ED);
16326   return ED;
16327 }
16328 
16329 /// Perform semantic analysis for the variable declaration that
16330 /// occurs within a C++ catch clause, returning the newly-created
16331 /// variable.
16332 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16333                                          TypeSourceInfo *TInfo,
16334                                          SourceLocation StartLoc,
16335                                          SourceLocation Loc,
16336                                          IdentifierInfo *Name) {
16337   bool Invalid = false;
16338   QualType ExDeclType = TInfo->getType();
16339 
16340   // Arrays and functions decay.
16341   if (ExDeclType->isArrayType())
16342     ExDeclType = Context.getArrayDecayedType(ExDeclType);
16343   else if (ExDeclType->isFunctionType())
16344     ExDeclType = Context.getPointerType(ExDeclType);
16345 
16346   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16347   // The exception-declaration shall not denote a pointer or reference to an
16348   // incomplete type, other than [cv] void*.
16349   // N2844 forbids rvalue references.
16350   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16351     Diag(Loc, diag::err_catch_rvalue_ref);
16352     Invalid = true;
16353   }
16354 
16355   if (ExDeclType->isVariablyModifiedType()) {
16356     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16357     Invalid = true;
16358   }
16359 
16360   QualType BaseType = ExDeclType;
16361   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16362   unsigned DK = diag::err_catch_incomplete;
16363   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16364     BaseType = Ptr->getPointeeType();
16365     Mode = 1;
16366     DK = diag::err_catch_incomplete_ptr;
16367   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16368     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16369     BaseType = Ref->getPointeeType();
16370     Mode = 2;
16371     DK = diag::err_catch_incomplete_ref;
16372   }
16373   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16374       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16375     Invalid = true;
16376 
16377   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16378     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16379     Invalid = true;
16380   }
16381 
16382   if (!Invalid && !ExDeclType->isDependentType() &&
16383       RequireNonAbstractType(Loc, ExDeclType,
16384                              diag::err_abstract_type_in_decl,
16385                              AbstractVariableType))
16386     Invalid = true;
16387 
16388   // Only the non-fragile NeXT runtime currently supports C++ catches
16389   // of ObjC types, and no runtime supports catching ObjC types by value.
16390   if (!Invalid && getLangOpts().ObjC) {
16391     QualType T = ExDeclType;
16392     if (const ReferenceType *RT = T->getAs<ReferenceType>())
16393       T = RT->getPointeeType();
16394 
16395     if (T->isObjCObjectType()) {
16396       Diag(Loc, diag::err_objc_object_catch);
16397       Invalid = true;
16398     } else if (T->isObjCObjectPointerType()) {
16399       // FIXME: should this be a test for macosx-fragile specifically?
16400       if (getLangOpts().ObjCRuntime.isFragile())
16401         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16402     }
16403   }
16404 
16405   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16406                                     ExDeclType, TInfo, SC_None);
16407   ExDecl->setExceptionVariable(true);
16408 
16409   // In ARC, infer 'retaining' for variables of retainable type.
16410   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16411     Invalid = true;
16412 
16413   if (!Invalid && !ExDeclType->isDependentType()) {
16414     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16415       // Insulate this from anything else we might currently be parsing.
16416       EnterExpressionEvaluationContext scope(
16417           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16418 
16419       // C++ [except.handle]p16:
16420       //   The object declared in an exception-declaration or, if the
16421       //   exception-declaration does not specify a name, a temporary (12.2) is
16422       //   copy-initialized (8.5) from the exception object. [...]
16423       //   The object is destroyed when the handler exits, after the destruction
16424       //   of any automatic objects initialized within the handler.
16425       //
16426       // We just pretend to initialize the object with itself, then make sure
16427       // it can be destroyed later.
16428       QualType initType = Context.getExceptionObjectType(ExDeclType);
16429 
16430       InitializedEntity entity =
16431         InitializedEntity::InitializeVariable(ExDecl);
16432       InitializationKind initKind =
16433         InitializationKind::CreateCopy(Loc, SourceLocation());
16434 
16435       Expr *opaqueValue =
16436         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16437       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16438       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16439       if (result.isInvalid())
16440         Invalid = true;
16441       else {
16442         // If the constructor used was non-trivial, set this as the
16443         // "initializer".
16444         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16445         if (!construct->getConstructor()->isTrivial()) {
16446           Expr *init = MaybeCreateExprWithCleanups(construct);
16447           ExDecl->setInit(init);
16448         }
16449 
16450         // And make sure it's destructable.
16451         FinalizeVarWithDestructor(ExDecl, recordType);
16452       }
16453     }
16454   }
16455 
16456   if (Invalid)
16457     ExDecl->setInvalidDecl();
16458 
16459   return ExDecl;
16460 }
16461 
16462 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16463 /// handler.
16464 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16465   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16466   bool Invalid = D.isInvalidType();
16467 
16468   // Check for unexpanded parameter packs.
16469   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16470                                       UPPC_ExceptionType)) {
16471     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16472                                              D.getIdentifierLoc());
16473     Invalid = true;
16474   }
16475 
16476   IdentifierInfo *II = D.getIdentifier();
16477   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16478                                              LookupOrdinaryName,
16479                                              ForVisibleRedeclaration)) {
16480     // The scope should be freshly made just for us. There is just no way
16481     // it contains any previous declaration, except for function parameters in
16482     // a function-try-block's catch statement.
16483     assert(!S->isDeclScope(PrevDecl));
16484     if (isDeclInScope(PrevDecl, CurContext, S)) {
16485       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16486         << D.getIdentifier();
16487       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16488       Invalid = true;
16489     } else if (PrevDecl->isTemplateParameter())
16490       // Maybe we will complain about the shadowed template parameter.
16491       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16492   }
16493 
16494   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16495     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16496       << D.getCXXScopeSpec().getRange();
16497     Invalid = true;
16498   }
16499 
16500   VarDecl *ExDecl = BuildExceptionDeclaration(
16501       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16502   if (Invalid)
16503     ExDecl->setInvalidDecl();
16504 
16505   // Add the exception declaration into this scope.
16506   if (II)
16507     PushOnScopeChains(ExDecl, S);
16508   else
16509     CurContext->addDecl(ExDecl);
16510 
16511   ProcessDeclAttributes(S, ExDecl, D);
16512   return ExDecl;
16513 }
16514 
16515 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16516                                          Expr *AssertExpr,
16517                                          Expr *AssertMessageExpr,
16518                                          SourceLocation RParenLoc) {
16519   StringLiteral *AssertMessage =
16520       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16521 
16522   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16523     return nullptr;
16524 
16525   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16526                                       AssertMessage, RParenLoc, false);
16527 }
16528 
16529 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16530                                          Expr *AssertExpr,
16531                                          StringLiteral *AssertMessage,
16532                                          SourceLocation RParenLoc,
16533                                          bool Failed) {
16534   assert(AssertExpr != nullptr && "Expected non-null condition");
16535   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16536       !Failed) {
16537     // In a static_assert-declaration, the constant-expression shall be a
16538     // constant expression that can be contextually converted to bool.
16539     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16540     if (Converted.isInvalid())
16541       Failed = true;
16542 
16543     ExprResult FullAssertExpr =
16544         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16545                             /*DiscardedValue*/ false,
16546                             /*IsConstexpr*/ true);
16547     if (FullAssertExpr.isInvalid())
16548       Failed = true;
16549     else
16550       AssertExpr = FullAssertExpr.get();
16551 
16552     llvm::APSInt Cond;
16553     if (!Failed && VerifyIntegerConstantExpression(
16554                        AssertExpr, &Cond,
16555                        diag::err_static_assert_expression_is_not_constant)
16556                        .isInvalid())
16557       Failed = true;
16558 
16559     if (!Failed && !Cond) {
16560       SmallString<256> MsgBuffer;
16561       llvm::raw_svector_ostream Msg(MsgBuffer);
16562       if (AssertMessage)
16563         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16564 
16565       Expr *InnerCond = nullptr;
16566       std::string InnerCondDescription;
16567       std::tie(InnerCond, InnerCondDescription) =
16568         findFailedBooleanCondition(Converted.get());
16569       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16570         // Drill down into concept specialization expressions to see why they
16571         // weren't satisfied.
16572         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16573           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16574         ConstraintSatisfaction Satisfaction;
16575         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16576           DiagnoseUnsatisfiedConstraint(Satisfaction);
16577       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16578                            && !isa<IntegerLiteral>(InnerCond)) {
16579         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16580           << InnerCondDescription << !AssertMessage
16581           << Msg.str() << InnerCond->getSourceRange();
16582       } else {
16583         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16584           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16585       }
16586       Failed = true;
16587     }
16588   } else {
16589     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16590                                                     /*DiscardedValue*/false,
16591                                                     /*IsConstexpr*/true);
16592     if (FullAssertExpr.isInvalid())
16593       Failed = true;
16594     else
16595       AssertExpr = FullAssertExpr.get();
16596   }
16597 
16598   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16599                                         AssertExpr, AssertMessage, RParenLoc,
16600                                         Failed);
16601 
16602   CurContext->addDecl(Decl);
16603   return Decl;
16604 }
16605 
16606 /// Perform semantic analysis of the given friend type declaration.
16607 ///
16608 /// \returns A friend declaration that.
16609 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16610                                       SourceLocation FriendLoc,
16611                                       TypeSourceInfo *TSInfo) {
16612   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16613 
16614   QualType T = TSInfo->getType();
16615   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16616 
16617   // C++03 [class.friend]p2:
16618   //   An elaborated-type-specifier shall be used in a friend declaration
16619   //   for a class.*
16620   //
16621   //   * The class-key of the elaborated-type-specifier is required.
16622   if (!CodeSynthesisContexts.empty()) {
16623     // Do not complain about the form of friend template types during any kind
16624     // of code synthesis. For template instantiation, we will have complained
16625     // when the template was defined.
16626   } else {
16627     if (!T->isElaboratedTypeSpecifier()) {
16628       // If we evaluated the type to a record type, suggest putting
16629       // a tag in front.
16630       if (const RecordType *RT = T->getAs<RecordType>()) {
16631         RecordDecl *RD = RT->getDecl();
16632 
16633         SmallString<16> InsertionText(" ");
16634         InsertionText += RD->getKindName();
16635 
16636         Diag(TypeRange.getBegin(),
16637              getLangOpts().CPlusPlus11 ?
16638                diag::warn_cxx98_compat_unelaborated_friend_type :
16639                diag::ext_unelaborated_friend_type)
16640           << (unsigned) RD->getTagKind()
16641           << T
16642           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16643                                         InsertionText);
16644       } else {
16645         Diag(FriendLoc,
16646              getLangOpts().CPlusPlus11 ?
16647                diag::warn_cxx98_compat_nonclass_type_friend :
16648                diag::ext_nonclass_type_friend)
16649           << T
16650           << TypeRange;
16651       }
16652     } else if (T->getAs<EnumType>()) {
16653       Diag(FriendLoc,
16654            getLangOpts().CPlusPlus11 ?
16655              diag::warn_cxx98_compat_enum_friend :
16656              diag::ext_enum_friend)
16657         << T
16658         << TypeRange;
16659     }
16660 
16661     // C++11 [class.friend]p3:
16662     //   A friend declaration that does not declare a function shall have one
16663     //   of the following forms:
16664     //     friend elaborated-type-specifier ;
16665     //     friend simple-type-specifier ;
16666     //     friend typename-specifier ;
16667     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16668       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16669   }
16670 
16671   //   If the type specifier in a friend declaration designates a (possibly
16672   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16673   //   the friend declaration is ignored.
16674   return FriendDecl::Create(Context, CurContext,
16675                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16676                             FriendLoc);
16677 }
16678 
16679 /// Handle a friend tag declaration where the scope specifier was
16680 /// templated.
16681 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16682                                     unsigned TagSpec, SourceLocation TagLoc,
16683                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16684                                     SourceLocation NameLoc,
16685                                     const ParsedAttributesView &Attr,
16686                                     MultiTemplateParamsArg TempParamLists) {
16687   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16688 
16689   bool IsMemberSpecialization = false;
16690   bool Invalid = false;
16691 
16692   if (TemplateParameterList *TemplateParams =
16693           MatchTemplateParametersToScopeSpecifier(
16694               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16695               IsMemberSpecialization, Invalid)) {
16696     if (TemplateParams->size() > 0) {
16697       // This is a declaration of a class template.
16698       if (Invalid)
16699         return nullptr;
16700 
16701       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16702                                 NameLoc, Attr, TemplateParams, AS_public,
16703                                 /*ModulePrivateLoc=*/SourceLocation(),
16704                                 FriendLoc, TempParamLists.size() - 1,
16705                                 TempParamLists.data()).get();
16706     } else {
16707       // The "template<>" header is extraneous.
16708       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16709         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16710       IsMemberSpecialization = true;
16711     }
16712   }
16713 
16714   if (Invalid) return nullptr;
16715 
16716   bool isAllExplicitSpecializations = true;
16717   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16718     if (TempParamLists[I]->size()) {
16719       isAllExplicitSpecializations = false;
16720       break;
16721     }
16722   }
16723 
16724   // FIXME: don't ignore attributes.
16725 
16726   // If it's explicit specializations all the way down, just forget
16727   // about the template header and build an appropriate non-templated
16728   // friend.  TODO: for source fidelity, remember the headers.
16729   if (isAllExplicitSpecializations) {
16730     if (SS.isEmpty()) {
16731       bool Owned = false;
16732       bool IsDependent = false;
16733       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16734                       Attr, AS_public,
16735                       /*ModulePrivateLoc=*/SourceLocation(),
16736                       MultiTemplateParamsArg(), Owned, IsDependent,
16737                       /*ScopedEnumKWLoc=*/SourceLocation(),
16738                       /*ScopedEnumUsesClassTag=*/false,
16739                       /*UnderlyingType=*/TypeResult(),
16740                       /*IsTypeSpecifier=*/false,
16741                       /*IsTemplateParamOrArg=*/false);
16742     }
16743 
16744     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16745     ElaboratedTypeKeyword Keyword
16746       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16747     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16748                                    *Name, NameLoc);
16749     if (T.isNull())
16750       return nullptr;
16751 
16752     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16753     if (isa<DependentNameType>(T)) {
16754       DependentNameTypeLoc TL =
16755           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16756       TL.setElaboratedKeywordLoc(TagLoc);
16757       TL.setQualifierLoc(QualifierLoc);
16758       TL.setNameLoc(NameLoc);
16759     } else {
16760       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16761       TL.setElaboratedKeywordLoc(TagLoc);
16762       TL.setQualifierLoc(QualifierLoc);
16763       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16764     }
16765 
16766     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16767                                             TSI, FriendLoc, TempParamLists);
16768     Friend->setAccess(AS_public);
16769     CurContext->addDecl(Friend);
16770     return Friend;
16771   }
16772 
16773   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16774 
16775 
16776 
16777   // Handle the case of a templated-scope friend class.  e.g.
16778   //   template <class T> class A<T>::B;
16779   // FIXME: we don't support these right now.
16780   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16781     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16782   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16783   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16784   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16785   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16786   TL.setElaboratedKeywordLoc(TagLoc);
16787   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16788   TL.setNameLoc(NameLoc);
16789 
16790   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16791                                           TSI, FriendLoc, TempParamLists);
16792   Friend->setAccess(AS_public);
16793   Friend->setUnsupportedFriend(true);
16794   CurContext->addDecl(Friend);
16795   return Friend;
16796 }
16797 
16798 /// Handle a friend type declaration.  This works in tandem with
16799 /// ActOnTag.
16800 ///
16801 /// Notes on friend class templates:
16802 ///
16803 /// We generally treat friend class declarations as if they were
16804 /// declaring a class.  So, for example, the elaborated type specifier
16805 /// in a friend declaration is required to obey the restrictions of a
16806 /// class-head (i.e. no typedefs in the scope chain), template
16807 /// parameters are required to match up with simple template-ids, &c.
16808 /// However, unlike when declaring a template specialization, it's
16809 /// okay to refer to a template specialization without an empty
16810 /// template parameter declaration, e.g.
16811 ///   friend class A<T>::B<unsigned>;
16812 /// We permit this as a special case; if there are any template
16813 /// parameters present at all, require proper matching, i.e.
16814 ///   template <> template \<class T> friend class A<int>::B;
16815 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16816                                 MultiTemplateParamsArg TempParams) {
16817   SourceLocation Loc = DS.getBeginLoc();
16818 
16819   assert(DS.isFriendSpecified());
16820   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16821 
16822   // C++ [class.friend]p3:
16823   // A friend declaration that does not declare a function shall have one of
16824   // the following forms:
16825   //     friend elaborated-type-specifier ;
16826   //     friend simple-type-specifier ;
16827   //     friend typename-specifier ;
16828   //
16829   // Any declaration with a type qualifier does not have that form. (It's
16830   // legal to specify a qualified type as a friend, you just can't write the
16831   // keywords.)
16832   if (DS.getTypeQualifiers()) {
16833     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16834       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16835     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16836       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16837     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16838       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16839     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16840       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16841     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16842       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16843   }
16844 
16845   // Try to convert the decl specifier to a type.  This works for
16846   // friend templates because ActOnTag never produces a ClassTemplateDecl
16847   // for a TUK_Friend.
16848   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16849   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16850   QualType T = TSI->getType();
16851   if (TheDeclarator.isInvalidType())
16852     return nullptr;
16853 
16854   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16855     return nullptr;
16856 
16857   // This is definitely an error in C++98.  It's probably meant to
16858   // be forbidden in C++0x, too, but the specification is just
16859   // poorly written.
16860   //
16861   // The problem is with declarations like the following:
16862   //   template <T> friend A<T>::foo;
16863   // where deciding whether a class C is a friend or not now hinges
16864   // on whether there exists an instantiation of A that causes
16865   // 'foo' to equal C.  There are restrictions on class-heads
16866   // (which we declare (by fiat) elaborated friend declarations to
16867   // be) that makes this tractable.
16868   //
16869   // FIXME: handle "template <> friend class A<T>;", which
16870   // is possibly well-formed?  Who even knows?
16871   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16872     Diag(Loc, diag::err_tagless_friend_type_template)
16873       << DS.getSourceRange();
16874     return nullptr;
16875   }
16876 
16877   // C++98 [class.friend]p1: A friend of a class is a function
16878   //   or class that is not a member of the class . . .
16879   // This is fixed in DR77, which just barely didn't make the C++03
16880   // deadline.  It's also a very silly restriction that seriously
16881   // affects inner classes and which nobody else seems to implement;
16882   // thus we never diagnose it, not even in -pedantic.
16883   //
16884   // But note that we could warn about it: it's always useless to
16885   // friend one of your own members (it's not, however, worthless to
16886   // friend a member of an arbitrary specialization of your template).
16887 
16888   Decl *D;
16889   if (!TempParams.empty())
16890     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16891                                    TempParams,
16892                                    TSI,
16893                                    DS.getFriendSpecLoc());
16894   else
16895     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16896 
16897   if (!D)
16898     return nullptr;
16899 
16900   D->setAccess(AS_public);
16901   CurContext->addDecl(D);
16902 
16903   return D;
16904 }
16905 
16906 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16907                                         MultiTemplateParamsArg TemplateParams) {
16908   const DeclSpec &DS = D.getDeclSpec();
16909 
16910   assert(DS.isFriendSpecified());
16911   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16912 
16913   SourceLocation Loc = D.getIdentifierLoc();
16914   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16915 
16916   // C++ [class.friend]p1
16917   //   A friend of a class is a function or class....
16918   // Note that this sees through typedefs, which is intended.
16919   // It *doesn't* see through dependent types, which is correct
16920   // according to [temp.arg.type]p3:
16921   //   If a declaration acquires a function type through a
16922   //   type dependent on a template-parameter and this causes
16923   //   a declaration that does not use the syntactic form of a
16924   //   function declarator to have a function type, the program
16925   //   is ill-formed.
16926   if (!TInfo->getType()->isFunctionType()) {
16927     Diag(Loc, diag::err_unexpected_friend);
16928 
16929     // It might be worthwhile to try to recover by creating an
16930     // appropriate declaration.
16931     return nullptr;
16932   }
16933 
16934   // C++ [namespace.memdef]p3
16935   //  - If a friend declaration in a non-local class first declares a
16936   //    class or function, the friend class or function is a member
16937   //    of the innermost enclosing namespace.
16938   //  - The name of the friend is not found by simple name lookup
16939   //    until a matching declaration is provided in that namespace
16940   //    scope (either before or after the class declaration granting
16941   //    friendship).
16942   //  - If a friend function is called, its name may be found by the
16943   //    name lookup that considers functions from namespaces and
16944   //    classes associated with the types of the function arguments.
16945   //  - When looking for a prior declaration of a class or a function
16946   //    declared as a friend, scopes outside the innermost enclosing
16947   //    namespace scope are not considered.
16948 
16949   CXXScopeSpec &SS = D.getCXXScopeSpec();
16950   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16951   assert(NameInfo.getName());
16952 
16953   // Check for unexpanded parameter packs.
16954   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16955       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16956       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16957     return nullptr;
16958 
16959   // The context we found the declaration in, or in which we should
16960   // create the declaration.
16961   DeclContext *DC;
16962   Scope *DCScope = S;
16963   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16964                         ForExternalRedeclaration);
16965 
16966   // There are five cases here.
16967   //   - There's no scope specifier and we're in a local class. Only look
16968   //     for functions declared in the immediately-enclosing block scope.
16969   // We recover from invalid scope qualifiers as if they just weren't there.
16970   FunctionDecl *FunctionContainingLocalClass = nullptr;
16971   if ((SS.isInvalid() || !SS.isSet()) &&
16972       (FunctionContainingLocalClass =
16973            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16974     // C++11 [class.friend]p11:
16975     //   If a friend declaration appears in a local class and the name
16976     //   specified is an unqualified name, a prior declaration is
16977     //   looked up without considering scopes that are outside the
16978     //   innermost enclosing non-class scope. For a friend function
16979     //   declaration, if there is no prior declaration, the program is
16980     //   ill-formed.
16981 
16982     // Find the innermost enclosing non-class scope. This is the block
16983     // scope containing the local class definition (or for a nested class,
16984     // the outer local class).
16985     DCScope = S->getFnParent();
16986 
16987     // Look up the function name in the scope.
16988     Previous.clear(LookupLocalFriendName);
16989     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16990 
16991     if (!Previous.empty()) {
16992       // All possible previous declarations must have the same context:
16993       // either they were declared at block scope or they are members of
16994       // one of the enclosing local classes.
16995       DC = Previous.getRepresentativeDecl()->getDeclContext();
16996     } else {
16997       // This is ill-formed, but provide the context that we would have
16998       // declared the function in, if we were permitted to, for error recovery.
16999       DC = FunctionContainingLocalClass;
17000     }
17001     adjustContextForLocalExternDecl(DC);
17002 
17003     // C++ [class.friend]p6:
17004     //   A function can be defined in a friend declaration of a class if and
17005     //   only if the class is a non-local class (9.8), the function name is
17006     //   unqualified, and the function has namespace scope.
17007     if (D.isFunctionDefinition()) {
17008       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17009     }
17010 
17011   //   - There's no scope specifier, in which case we just go to the
17012   //     appropriate scope and look for a function or function template
17013   //     there as appropriate.
17014   } else if (SS.isInvalid() || !SS.isSet()) {
17015     // C++11 [namespace.memdef]p3:
17016     //   If the name in a friend declaration is neither qualified nor
17017     //   a template-id and the declaration is a function or an
17018     //   elaborated-type-specifier, the lookup to determine whether
17019     //   the entity has been previously declared shall not consider
17020     //   any scopes outside the innermost enclosing namespace.
17021     bool isTemplateId =
17022         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17023 
17024     // Find the appropriate context according to the above.
17025     DC = CurContext;
17026 
17027     // Skip class contexts.  If someone can cite chapter and verse
17028     // for this behavior, that would be nice --- it's what GCC and
17029     // EDG do, and it seems like a reasonable intent, but the spec
17030     // really only says that checks for unqualified existing
17031     // declarations should stop at the nearest enclosing namespace,
17032     // not that they should only consider the nearest enclosing
17033     // namespace.
17034     while (DC->isRecord())
17035       DC = DC->getParent();
17036 
17037     DeclContext *LookupDC = DC->getNonTransparentContext();
17038     while (true) {
17039       LookupQualifiedName(Previous, LookupDC);
17040 
17041       if (!Previous.empty()) {
17042         DC = LookupDC;
17043         break;
17044       }
17045 
17046       if (isTemplateId) {
17047         if (isa<TranslationUnitDecl>(LookupDC)) break;
17048       } else {
17049         if (LookupDC->isFileContext()) break;
17050       }
17051       LookupDC = LookupDC->getParent();
17052     }
17053 
17054     DCScope = getScopeForDeclContext(S, DC);
17055 
17056   //   - There's a non-dependent scope specifier, in which case we
17057   //     compute it and do a previous lookup there for a function
17058   //     or function template.
17059   } else if (!SS.getScopeRep()->isDependent()) {
17060     DC = computeDeclContext(SS);
17061     if (!DC) return nullptr;
17062 
17063     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17064 
17065     LookupQualifiedName(Previous, DC);
17066 
17067     // C++ [class.friend]p1: A friend of a class is a function or
17068     //   class that is not a member of the class . . .
17069     if (DC->Equals(CurContext))
17070       Diag(DS.getFriendSpecLoc(),
17071            getLangOpts().CPlusPlus11 ?
17072              diag::warn_cxx98_compat_friend_is_member :
17073              diag::err_friend_is_member);
17074 
17075     if (D.isFunctionDefinition()) {
17076       // C++ [class.friend]p6:
17077       //   A function can be defined in a friend declaration of a class if and
17078       //   only if the class is a non-local class (9.8), the function name is
17079       //   unqualified, and the function has namespace scope.
17080       //
17081       // FIXME: We should only do this if the scope specifier names the
17082       // innermost enclosing namespace; otherwise the fixit changes the
17083       // meaning of the code.
17084       SemaDiagnosticBuilder DB
17085         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17086 
17087       DB << SS.getScopeRep();
17088       if (DC->isFileContext())
17089         DB << FixItHint::CreateRemoval(SS.getRange());
17090       SS.clear();
17091     }
17092 
17093   //   - There's a scope specifier that does not match any template
17094   //     parameter lists, in which case we use some arbitrary context,
17095   //     create a method or method template, and wait for instantiation.
17096   //   - There's a scope specifier that does match some template
17097   //     parameter lists, which we don't handle right now.
17098   } else {
17099     if (D.isFunctionDefinition()) {
17100       // C++ [class.friend]p6:
17101       //   A function can be defined in a friend declaration of a class if and
17102       //   only if the class is a non-local class (9.8), the function name is
17103       //   unqualified, and the function has namespace scope.
17104       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17105         << SS.getScopeRep();
17106     }
17107 
17108     DC = CurContext;
17109     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17110   }
17111 
17112   if (!DC->isRecord()) {
17113     int DiagArg = -1;
17114     switch (D.getName().getKind()) {
17115     case UnqualifiedIdKind::IK_ConstructorTemplateId:
17116     case UnqualifiedIdKind::IK_ConstructorName:
17117       DiagArg = 0;
17118       break;
17119     case UnqualifiedIdKind::IK_DestructorName:
17120       DiagArg = 1;
17121       break;
17122     case UnqualifiedIdKind::IK_ConversionFunctionId:
17123       DiagArg = 2;
17124       break;
17125     case UnqualifiedIdKind::IK_DeductionGuideName:
17126       DiagArg = 3;
17127       break;
17128     case UnqualifiedIdKind::IK_Identifier:
17129     case UnqualifiedIdKind::IK_ImplicitSelfParam:
17130     case UnqualifiedIdKind::IK_LiteralOperatorId:
17131     case UnqualifiedIdKind::IK_OperatorFunctionId:
17132     case UnqualifiedIdKind::IK_TemplateId:
17133       break;
17134     }
17135     // This implies that it has to be an operator or function.
17136     if (DiagArg >= 0) {
17137       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17138       return nullptr;
17139     }
17140   }
17141 
17142   // FIXME: This is an egregious hack to cope with cases where the scope stack
17143   // does not contain the declaration context, i.e., in an out-of-line
17144   // definition of a class.
17145   Scope FakeDCScope(S, Scope::DeclScope, Diags);
17146   if (!DCScope) {
17147     FakeDCScope.setEntity(DC);
17148     DCScope = &FakeDCScope;
17149   }
17150 
17151   bool AddToScope = true;
17152   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17153                                           TemplateParams, AddToScope);
17154   if (!ND) return nullptr;
17155 
17156   assert(ND->getLexicalDeclContext() == CurContext);
17157 
17158   // If we performed typo correction, we might have added a scope specifier
17159   // and changed the decl context.
17160   DC = ND->getDeclContext();
17161 
17162   // Add the function declaration to the appropriate lookup tables,
17163   // adjusting the redeclarations list as necessary.  We don't
17164   // want to do this yet if the friending class is dependent.
17165   //
17166   // Also update the scope-based lookup if the target context's
17167   // lookup context is in lexical scope.
17168   if (!CurContext->isDependentContext()) {
17169     DC = DC->getRedeclContext();
17170     DC->makeDeclVisibleInContext(ND);
17171     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17172       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17173   }
17174 
17175   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17176                                        D.getIdentifierLoc(), ND,
17177                                        DS.getFriendSpecLoc());
17178   FrD->setAccess(AS_public);
17179   CurContext->addDecl(FrD);
17180 
17181   if (ND->isInvalidDecl()) {
17182     FrD->setInvalidDecl();
17183   } else {
17184     if (DC->isRecord()) CheckFriendAccess(ND);
17185 
17186     FunctionDecl *FD;
17187     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17188       FD = FTD->getTemplatedDecl();
17189     else
17190       FD = cast<FunctionDecl>(ND);
17191 
17192     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17193     // default argument expression, that declaration shall be a definition
17194     // and shall be the only declaration of the function or function
17195     // template in the translation unit.
17196     if (functionDeclHasDefaultArgument(FD)) {
17197       // We can't look at FD->getPreviousDecl() because it may not have been set
17198       // if we're in a dependent context. If the function is known to be a
17199       // redeclaration, we will have narrowed Previous down to the right decl.
17200       if (D.isRedeclaration()) {
17201         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17202         Diag(Previous.getRepresentativeDecl()->getLocation(),
17203              diag::note_previous_declaration);
17204       } else if (!D.isFunctionDefinition())
17205         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17206     }
17207 
17208     // Mark templated-scope function declarations as unsupported.
17209     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17210       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17211         << SS.getScopeRep() << SS.getRange()
17212         << cast<CXXRecordDecl>(CurContext);
17213       FrD->setUnsupportedFriend(true);
17214     }
17215   }
17216 
17217   warnOnReservedIdentifier(ND);
17218 
17219   return ND;
17220 }
17221 
17222 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17223   AdjustDeclIfTemplate(Dcl);
17224 
17225   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17226   if (!Fn) {
17227     Diag(DelLoc, diag::err_deleted_non_function);
17228     return;
17229   }
17230 
17231   // Deleted function does not have a body.
17232   Fn->setWillHaveBody(false);
17233 
17234   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17235     // Don't consider the implicit declaration we generate for explicit
17236     // specializations. FIXME: Do not generate these implicit declarations.
17237     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17238          Prev->getPreviousDecl()) &&
17239         !Prev->isDefined()) {
17240       Diag(DelLoc, diag::err_deleted_decl_not_first);
17241       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17242            Prev->isImplicit() ? diag::note_previous_implicit_declaration
17243                               : diag::note_previous_declaration);
17244       // We can't recover from this; the declaration might have already
17245       // been used.
17246       Fn->setInvalidDecl();
17247       return;
17248     }
17249 
17250     // To maintain the invariant that functions are only deleted on their first
17251     // declaration, mark the implicitly-instantiated declaration of the
17252     // explicitly-specialized function as deleted instead of marking the
17253     // instantiated redeclaration.
17254     Fn = Fn->getCanonicalDecl();
17255   }
17256 
17257   // dllimport/dllexport cannot be deleted.
17258   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17259     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17260     Fn->setInvalidDecl();
17261   }
17262 
17263   // C++11 [basic.start.main]p3:
17264   //   A program that defines main as deleted [...] is ill-formed.
17265   if (Fn->isMain())
17266     Diag(DelLoc, diag::err_deleted_main);
17267 
17268   // C++11 [dcl.fct.def.delete]p4:
17269   //  A deleted function is implicitly inline.
17270   Fn->setImplicitlyInline();
17271   Fn->setDeletedAsWritten();
17272 }
17273 
17274 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17275   if (!Dcl || Dcl->isInvalidDecl())
17276     return;
17277 
17278   auto *FD = dyn_cast<FunctionDecl>(Dcl);
17279   if (!FD) {
17280     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17281       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17282         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17283         return;
17284       }
17285     }
17286 
17287     Diag(DefaultLoc, diag::err_default_special_members)
17288         << getLangOpts().CPlusPlus20;
17289     return;
17290   }
17291 
17292   // Reject if this can't possibly be a defaultable function.
17293   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17294   if (!DefKind &&
17295       // A dependent function that doesn't locally look defaultable can
17296       // still instantiate to a defaultable function if it's a constructor
17297       // or assignment operator.
17298       (!FD->isDependentContext() ||
17299        (!isa<CXXConstructorDecl>(FD) &&
17300         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17301     Diag(DefaultLoc, diag::err_default_special_members)
17302         << getLangOpts().CPlusPlus20;
17303     return;
17304   }
17305 
17306   // Issue compatibility warning. We already warned if the operator is
17307   // 'operator<=>' when parsing the '<=>' token.
17308   if (DefKind.isComparison() &&
17309       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17310     Diag(DefaultLoc, getLangOpts().CPlusPlus20
17311                          ? diag::warn_cxx17_compat_defaulted_comparison
17312                          : diag::ext_defaulted_comparison);
17313   }
17314 
17315   FD->setDefaulted();
17316   FD->setExplicitlyDefaulted();
17317 
17318   // Defer checking functions that are defaulted in a dependent context.
17319   if (FD->isDependentContext())
17320     return;
17321 
17322   // Unset that we will have a body for this function. We might not,
17323   // if it turns out to be trivial, and we don't need this marking now
17324   // that we've marked it as defaulted.
17325   FD->setWillHaveBody(false);
17326 
17327   if (DefKind.isComparison()) {
17328     // If this comparison's defaulting occurs within the definition of its
17329     // lexical class context, we have to do the checking when complete.
17330     if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17331       if (!RD->isCompleteDefinition())
17332         return;
17333   }
17334 
17335   // If this member fn was defaulted on its first declaration, we will have
17336   // already performed the checking in CheckCompletedCXXClass. Such a
17337   // declaration doesn't trigger an implicit definition.
17338   if (isa<CXXMethodDecl>(FD)) {
17339     const FunctionDecl *Primary = FD;
17340     if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17341       // Ask the template instantiation pattern that actually had the
17342       // '= default' on it.
17343       Primary = Pattern;
17344     if (Primary->getCanonicalDecl()->isDefaulted())
17345       return;
17346   }
17347 
17348   if (DefKind.isComparison()) {
17349     if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17350       FD->setInvalidDecl();
17351     else
17352       DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17353   } else {
17354     auto *MD = cast<CXXMethodDecl>(FD);
17355 
17356     if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
17357       MD->setInvalidDecl();
17358     else
17359       DefineDefaultedFunction(*this, MD, DefaultLoc);
17360   }
17361 }
17362 
17363 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17364   for (Stmt *SubStmt : S->children()) {
17365     if (!SubStmt)
17366       continue;
17367     if (isa<ReturnStmt>(SubStmt))
17368       Self.Diag(SubStmt->getBeginLoc(),
17369                 diag::err_return_in_constructor_handler);
17370     if (!isa<Expr>(SubStmt))
17371       SearchForReturnInStmt(Self, SubStmt);
17372   }
17373 }
17374 
17375 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17376   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17377     CXXCatchStmt *Handler = TryBlock->getHandler(I);
17378     SearchForReturnInStmt(*this, Handler);
17379   }
17380 }
17381 
17382 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17383                                              const CXXMethodDecl *Old) {
17384   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17385   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17386 
17387   if (OldFT->hasExtParameterInfos()) {
17388     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17389       // A parameter of the overriding method should be annotated with noescape
17390       // if the corresponding parameter of the overridden method is annotated.
17391       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17392           !NewFT->getExtParameterInfo(I).isNoEscape()) {
17393         Diag(New->getParamDecl(I)->getLocation(),
17394              diag::warn_overriding_method_missing_noescape);
17395         Diag(Old->getParamDecl(I)->getLocation(),
17396              diag::note_overridden_marked_noescape);
17397       }
17398   }
17399 
17400   // Virtual overrides must have the same code_seg.
17401   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17402   const auto *NewCSA = New->getAttr<CodeSegAttr>();
17403   if ((NewCSA || OldCSA) &&
17404       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17405     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17406     Diag(Old->getLocation(), diag::note_previous_declaration);
17407     return true;
17408   }
17409 
17410   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17411 
17412   // If the calling conventions match, everything is fine
17413   if (NewCC == OldCC)
17414     return false;
17415 
17416   // If the calling conventions mismatch because the new function is static,
17417   // suppress the calling convention mismatch error; the error about static
17418   // function override (err_static_overrides_virtual from
17419   // Sema::CheckFunctionDeclaration) is more clear.
17420   if (New->getStorageClass() == SC_Static)
17421     return false;
17422 
17423   Diag(New->getLocation(),
17424        diag::err_conflicting_overriding_cc_attributes)
17425     << New->getDeclName() << New->getType() << Old->getType();
17426   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17427   return true;
17428 }
17429 
17430 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17431                                              const CXXMethodDecl *Old) {
17432   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17433   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17434 
17435   if (Context.hasSameType(NewTy, OldTy) ||
17436       NewTy->isDependentType() || OldTy->isDependentType())
17437     return false;
17438 
17439   // Check if the return types are covariant
17440   QualType NewClassTy, OldClassTy;
17441 
17442   /// Both types must be pointers or references to classes.
17443   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17444     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17445       NewClassTy = NewPT->getPointeeType();
17446       OldClassTy = OldPT->getPointeeType();
17447     }
17448   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17449     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17450       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17451         NewClassTy = NewRT->getPointeeType();
17452         OldClassTy = OldRT->getPointeeType();
17453       }
17454     }
17455   }
17456 
17457   // The return types aren't either both pointers or references to a class type.
17458   if (NewClassTy.isNull()) {
17459     Diag(New->getLocation(),
17460          diag::err_different_return_type_for_overriding_virtual_function)
17461         << New->getDeclName() << NewTy << OldTy
17462         << New->getReturnTypeSourceRange();
17463     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17464         << Old->getReturnTypeSourceRange();
17465 
17466     return true;
17467   }
17468 
17469   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17470     // C++14 [class.virtual]p8:
17471     //   If the class type in the covariant return type of D::f differs from
17472     //   that of B::f, the class type in the return type of D::f shall be
17473     //   complete at the point of declaration of D::f or shall be the class
17474     //   type D.
17475     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17476       if (!RT->isBeingDefined() &&
17477           RequireCompleteType(New->getLocation(), NewClassTy,
17478                               diag::err_covariant_return_incomplete,
17479                               New->getDeclName()))
17480         return true;
17481     }
17482 
17483     // Check if the new class derives from the old class.
17484     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17485       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17486           << New->getDeclName() << NewTy << OldTy
17487           << New->getReturnTypeSourceRange();
17488       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17489           << Old->getReturnTypeSourceRange();
17490       return true;
17491     }
17492 
17493     // Check if we the conversion from derived to base is valid.
17494     if (CheckDerivedToBaseConversion(
17495             NewClassTy, OldClassTy,
17496             diag::err_covariant_return_inaccessible_base,
17497             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17498             New->getLocation(), New->getReturnTypeSourceRange(),
17499             New->getDeclName(), nullptr)) {
17500       // FIXME: this note won't trigger for delayed access control
17501       // diagnostics, and it's impossible to get an undelayed error
17502       // here from access control during the original parse because
17503       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17504       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17505           << Old->getReturnTypeSourceRange();
17506       return true;
17507     }
17508   }
17509 
17510   // The qualifiers of the return types must be the same.
17511   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17512     Diag(New->getLocation(),
17513          diag::err_covariant_return_type_different_qualifications)
17514         << New->getDeclName() << NewTy << OldTy
17515         << New->getReturnTypeSourceRange();
17516     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17517         << Old->getReturnTypeSourceRange();
17518     return true;
17519   }
17520 
17521 
17522   // The new class type must have the same or less qualifiers as the old type.
17523   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17524     Diag(New->getLocation(),
17525          diag::err_covariant_return_type_class_type_more_qualified)
17526         << New->getDeclName() << NewTy << OldTy
17527         << New->getReturnTypeSourceRange();
17528     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17529         << Old->getReturnTypeSourceRange();
17530     return true;
17531   }
17532 
17533   return false;
17534 }
17535 
17536 /// Mark the given method pure.
17537 ///
17538 /// \param Method the method to be marked pure.
17539 ///
17540 /// \param InitRange the source range that covers the "0" initializer.
17541 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17542   SourceLocation EndLoc = InitRange.getEnd();
17543   if (EndLoc.isValid())
17544     Method->setRangeEnd(EndLoc);
17545 
17546   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17547     Method->setPure();
17548     return false;
17549   }
17550 
17551   if (!Method->isInvalidDecl())
17552     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17553       << Method->getDeclName() << InitRange;
17554   return true;
17555 }
17556 
17557 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17558   if (D->getFriendObjectKind())
17559     Diag(D->getLocation(), diag::err_pure_friend);
17560   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17561     CheckPureMethod(M, ZeroLoc);
17562   else
17563     Diag(D->getLocation(), diag::err_illegal_initializer);
17564 }
17565 
17566 /// Determine whether the given declaration is a global variable or
17567 /// static data member.
17568 static bool isNonlocalVariable(const Decl *D) {
17569   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17570     return Var->hasGlobalStorage();
17571 
17572   return false;
17573 }
17574 
17575 /// Invoked when we are about to parse an initializer for the declaration
17576 /// 'Dcl'.
17577 ///
17578 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17579 /// static data member of class X, names should be looked up in the scope of
17580 /// class X. If the declaration had a scope specifier, a scope will have
17581 /// been created and passed in for this purpose. Otherwise, S will be null.
17582 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17583   // If there is no declaration, there was an error parsing it.
17584   if (!D || D->isInvalidDecl())
17585     return;
17586 
17587   // We will always have a nested name specifier here, but this declaration
17588   // might not be out of line if the specifier names the current namespace:
17589   //   extern int n;
17590   //   int ::n = 0;
17591   if (S && D->isOutOfLine())
17592     EnterDeclaratorContext(S, D->getDeclContext());
17593 
17594   // If we are parsing the initializer for a static data member, push a
17595   // new expression evaluation context that is associated with this static
17596   // data member.
17597   if (isNonlocalVariable(D))
17598     PushExpressionEvaluationContext(
17599         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17600 }
17601 
17602 /// Invoked after we are finished parsing an initializer for the declaration D.
17603 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17604   // If there is no declaration, there was an error parsing it.
17605   if (!D || D->isInvalidDecl())
17606     return;
17607 
17608   if (isNonlocalVariable(D))
17609     PopExpressionEvaluationContext();
17610 
17611   if (S && D->isOutOfLine())
17612     ExitDeclaratorContext(S);
17613 }
17614 
17615 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17616 /// C++ if/switch/while/for statement.
17617 /// e.g: "if (int x = f()) {...}"
17618 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17619   // C++ 6.4p2:
17620   // The declarator shall not specify a function or an array.
17621   // The type-specifier-seq shall not contain typedef and shall not declare a
17622   // new class or enumeration.
17623   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17624          "Parser allowed 'typedef' as storage class of condition decl.");
17625 
17626   Decl *Dcl = ActOnDeclarator(S, D);
17627   if (!Dcl)
17628     return true;
17629 
17630   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17631     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17632       << D.getSourceRange();
17633     return true;
17634   }
17635 
17636   return Dcl;
17637 }
17638 
17639 void Sema::LoadExternalVTableUses() {
17640   if (!ExternalSource)
17641     return;
17642 
17643   SmallVector<ExternalVTableUse, 4> VTables;
17644   ExternalSource->ReadUsedVTables(VTables);
17645   SmallVector<VTableUse, 4> NewUses;
17646   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17647     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17648       = VTablesUsed.find(VTables[I].Record);
17649     // Even if a definition wasn't required before, it may be required now.
17650     if (Pos != VTablesUsed.end()) {
17651       if (!Pos->second && VTables[I].DefinitionRequired)
17652         Pos->second = true;
17653       continue;
17654     }
17655 
17656     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17657     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17658   }
17659 
17660   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17661 }
17662 
17663 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17664                           bool DefinitionRequired) {
17665   // Ignore any vtable uses in unevaluated operands or for classes that do
17666   // not have a vtable.
17667   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17668       CurContext->isDependentContext() || isUnevaluatedContext())
17669     return;
17670   // Do not mark as used if compiling for the device outside of the target
17671   // region.
17672   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17673       !isInOpenMPDeclareTargetContext() &&
17674       !isInOpenMPTargetExecutionDirective()) {
17675     if (!DefinitionRequired)
17676       MarkVirtualMembersReferenced(Loc, Class);
17677     return;
17678   }
17679 
17680   // Try to insert this class into the map.
17681   LoadExternalVTableUses();
17682   Class = Class->getCanonicalDecl();
17683   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17684     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17685   if (!Pos.second) {
17686     // If we already had an entry, check to see if we are promoting this vtable
17687     // to require a definition. If so, we need to reappend to the VTableUses
17688     // list, since we may have already processed the first entry.
17689     if (DefinitionRequired && !Pos.first->second) {
17690       Pos.first->second = true;
17691     } else {
17692       // Otherwise, we can early exit.
17693       return;
17694     }
17695   } else {
17696     // The Microsoft ABI requires that we perform the destructor body
17697     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17698     // the deleting destructor is emitted with the vtable, not with the
17699     // destructor definition as in the Itanium ABI.
17700     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17701       CXXDestructorDecl *DD = Class->getDestructor();
17702       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17703         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17704           // If this is an out-of-line declaration, marking it referenced will
17705           // not do anything. Manually call CheckDestructor to look up operator
17706           // delete().
17707           ContextRAII SavedContext(*this, DD);
17708           CheckDestructor(DD);
17709         } else {
17710           MarkFunctionReferenced(Loc, Class->getDestructor());
17711         }
17712       }
17713     }
17714   }
17715 
17716   // Local classes need to have their virtual members marked
17717   // immediately. For all other classes, we mark their virtual members
17718   // at the end of the translation unit.
17719   if (Class->isLocalClass())
17720     MarkVirtualMembersReferenced(Loc, Class);
17721   else
17722     VTableUses.push_back(std::make_pair(Class, Loc));
17723 }
17724 
17725 bool Sema::DefineUsedVTables() {
17726   LoadExternalVTableUses();
17727   if (VTableUses.empty())
17728     return false;
17729 
17730   // Note: The VTableUses vector could grow as a result of marking
17731   // the members of a class as "used", so we check the size each
17732   // time through the loop and prefer indices (which are stable) to
17733   // iterators (which are not).
17734   bool DefinedAnything = false;
17735   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17736     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17737     if (!Class)
17738       continue;
17739     TemplateSpecializationKind ClassTSK =
17740         Class->getTemplateSpecializationKind();
17741 
17742     SourceLocation Loc = VTableUses[I].second;
17743 
17744     bool DefineVTable = true;
17745 
17746     // If this class has a key function, but that key function is
17747     // defined in another translation unit, we don't need to emit the
17748     // vtable even though we're using it.
17749     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17750     if (KeyFunction && !KeyFunction->hasBody()) {
17751       // The key function is in another translation unit.
17752       DefineVTable = false;
17753       TemplateSpecializationKind TSK =
17754           KeyFunction->getTemplateSpecializationKind();
17755       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17756              TSK != TSK_ImplicitInstantiation &&
17757              "Instantiations don't have key functions");
17758       (void)TSK;
17759     } else if (!KeyFunction) {
17760       // If we have a class with no key function that is the subject
17761       // of an explicit instantiation declaration, suppress the
17762       // vtable; it will live with the explicit instantiation
17763       // definition.
17764       bool IsExplicitInstantiationDeclaration =
17765           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17766       for (auto R : Class->redecls()) {
17767         TemplateSpecializationKind TSK
17768           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17769         if (TSK == TSK_ExplicitInstantiationDeclaration)
17770           IsExplicitInstantiationDeclaration = true;
17771         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17772           IsExplicitInstantiationDeclaration = false;
17773           break;
17774         }
17775       }
17776 
17777       if (IsExplicitInstantiationDeclaration)
17778         DefineVTable = false;
17779     }
17780 
17781     // The exception specifications for all virtual members may be needed even
17782     // if we are not providing an authoritative form of the vtable in this TU.
17783     // We may choose to emit it available_externally anyway.
17784     if (!DefineVTable) {
17785       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17786       continue;
17787     }
17788 
17789     // Mark all of the virtual members of this class as referenced, so
17790     // that we can build a vtable. Then, tell the AST consumer that a
17791     // vtable for this class is required.
17792     DefinedAnything = true;
17793     MarkVirtualMembersReferenced(Loc, Class);
17794     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17795     if (VTablesUsed[Canonical])
17796       Consumer.HandleVTable(Class);
17797 
17798     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17799     // no key function or the key function is inlined. Don't warn in C++ ABIs
17800     // that lack key functions, since the user won't be able to make one.
17801     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17802         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
17803         ClassTSK != TSK_ExplicitInstantiationDefinition) {
17804       const FunctionDecl *KeyFunctionDef = nullptr;
17805       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17806                            KeyFunctionDef->isInlined()))
17807         Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
17808     }
17809   }
17810   VTableUses.clear();
17811 
17812   return DefinedAnything;
17813 }
17814 
17815 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17816                                                  const CXXRecordDecl *RD) {
17817   for (const auto *I : RD->methods())
17818     if (I->isVirtual() && !I->isPure())
17819       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17820 }
17821 
17822 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17823                                         const CXXRecordDecl *RD,
17824                                         bool ConstexprOnly) {
17825   // Mark all functions which will appear in RD's vtable as used.
17826   CXXFinalOverriderMap FinalOverriders;
17827   RD->getFinalOverriders(FinalOverriders);
17828   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17829                                             E = FinalOverriders.end();
17830        I != E; ++I) {
17831     for (OverridingMethods::const_iterator OI = I->second.begin(),
17832                                            OE = I->second.end();
17833          OI != OE; ++OI) {
17834       assert(OI->second.size() > 0 && "no final overrider");
17835       CXXMethodDecl *Overrider = OI->second.front().Method;
17836 
17837       // C++ [basic.def.odr]p2:
17838       //   [...] A virtual member function is used if it is not pure. [...]
17839       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17840         MarkFunctionReferenced(Loc, Overrider);
17841     }
17842   }
17843 
17844   // Only classes that have virtual bases need a VTT.
17845   if (RD->getNumVBases() == 0)
17846     return;
17847 
17848   for (const auto &I : RD->bases()) {
17849     const auto *Base =
17850         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17851     if (Base->getNumVBases() == 0)
17852       continue;
17853     MarkVirtualMembersReferenced(Loc, Base);
17854   }
17855 }
17856 
17857 /// SetIvarInitializers - This routine builds initialization ASTs for the
17858 /// Objective-C implementation whose ivars need be initialized.
17859 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17860   if (!getLangOpts().CPlusPlus)
17861     return;
17862   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17863     SmallVector<ObjCIvarDecl*, 8> ivars;
17864     CollectIvarsToConstructOrDestruct(OID, ivars);
17865     if (ivars.empty())
17866       return;
17867     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17868     for (unsigned i = 0; i < ivars.size(); i++) {
17869       FieldDecl *Field = ivars[i];
17870       if (Field->isInvalidDecl())
17871         continue;
17872 
17873       CXXCtorInitializer *Member;
17874       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17875       InitializationKind InitKind =
17876         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17877 
17878       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17879       ExprResult MemberInit =
17880         InitSeq.Perform(*this, InitEntity, InitKind, None);
17881       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17882       // Note, MemberInit could actually come back empty if no initialization
17883       // is required (e.g., because it would call a trivial default constructor)
17884       if (!MemberInit.get() || MemberInit.isInvalid())
17885         continue;
17886 
17887       Member =
17888         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17889                                          SourceLocation(),
17890                                          MemberInit.getAs<Expr>(),
17891                                          SourceLocation());
17892       AllToInit.push_back(Member);
17893 
17894       // Be sure that the destructor is accessible and is marked as referenced.
17895       if (const RecordType *RecordTy =
17896               Context.getBaseElementType(Field->getType())
17897                   ->getAs<RecordType>()) {
17898         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17899         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17900           MarkFunctionReferenced(Field->getLocation(), Destructor);
17901           CheckDestructorAccess(Field->getLocation(), Destructor,
17902                             PDiag(diag::err_access_dtor_ivar)
17903                               << Context.getBaseElementType(Field->getType()));
17904         }
17905       }
17906     }
17907     ObjCImplementation->setIvarInitializers(Context,
17908                                             AllToInit.data(), AllToInit.size());
17909   }
17910 }
17911 
17912 static
17913 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17914                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17915                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17916                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17917                            Sema &S) {
17918   if (Ctor->isInvalidDecl())
17919     return;
17920 
17921   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17922 
17923   // Target may not be determinable yet, for instance if this is a dependent
17924   // call in an uninstantiated template.
17925   if (Target) {
17926     const FunctionDecl *FNTarget = nullptr;
17927     (void)Target->hasBody(FNTarget);
17928     Target = const_cast<CXXConstructorDecl*>(
17929       cast_or_null<CXXConstructorDecl>(FNTarget));
17930   }
17931 
17932   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17933                      // Avoid dereferencing a null pointer here.
17934                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17935 
17936   if (!Current.insert(Canonical).second)
17937     return;
17938 
17939   // We know that beyond here, we aren't chaining into a cycle.
17940   if (!Target || !Target->isDelegatingConstructor() ||
17941       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17942     Valid.insert(Current.begin(), Current.end());
17943     Current.clear();
17944   // We've hit a cycle.
17945   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17946              Current.count(TCanonical)) {
17947     // If we haven't diagnosed this cycle yet, do so now.
17948     if (!Invalid.count(TCanonical)) {
17949       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17950              diag::warn_delegating_ctor_cycle)
17951         << Ctor;
17952 
17953       // Don't add a note for a function delegating directly to itself.
17954       if (TCanonical != Canonical)
17955         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17956 
17957       CXXConstructorDecl *C = Target;
17958       while (C->getCanonicalDecl() != Canonical) {
17959         const FunctionDecl *FNTarget = nullptr;
17960         (void)C->getTargetConstructor()->hasBody(FNTarget);
17961         assert(FNTarget && "Ctor cycle through bodiless function");
17962 
17963         C = const_cast<CXXConstructorDecl*>(
17964           cast<CXXConstructorDecl>(FNTarget));
17965         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17966       }
17967     }
17968 
17969     Invalid.insert(Current.begin(), Current.end());
17970     Current.clear();
17971   } else {
17972     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17973   }
17974 }
17975 
17976 
17977 void Sema::CheckDelegatingCtorCycles() {
17978   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17979 
17980   for (DelegatingCtorDeclsType::iterator
17981          I = DelegatingCtorDecls.begin(ExternalSource),
17982          E = DelegatingCtorDecls.end();
17983        I != E; ++I)
17984     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17985 
17986   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17987     (*CI)->setInvalidDecl();
17988 }
17989 
17990 namespace {
17991   /// AST visitor that finds references to the 'this' expression.
17992   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17993     Sema &S;
17994 
17995   public:
17996     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17997 
17998     bool VisitCXXThisExpr(CXXThisExpr *E) {
17999       S.Diag(E->getLocation(), diag::err_this_static_member_func)
18000         << E->isImplicit();
18001       return false;
18002     }
18003   };
18004 }
18005 
18006 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18007   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18008   if (!TSInfo)
18009     return false;
18010 
18011   TypeLoc TL = TSInfo->getTypeLoc();
18012   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18013   if (!ProtoTL)
18014     return false;
18015 
18016   // C++11 [expr.prim.general]p3:
18017   //   [The expression this] shall not appear before the optional
18018   //   cv-qualifier-seq and it shall not appear within the declaration of a
18019   //   static member function (although its type and value category are defined
18020   //   within a static member function as they are within a non-static member
18021   //   function). [ Note: this is because declaration matching does not occur
18022   //  until the complete declarator is known. - end note ]
18023   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18024   FindCXXThisExpr Finder(*this);
18025 
18026   // If the return type came after the cv-qualifier-seq, check it now.
18027   if (Proto->hasTrailingReturn() &&
18028       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18029     return true;
18030 
18031   // Check the exception specification.
18032   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18033     return true;
18034 
18035   // Check the trailing requires clause
18036   if (Expr *E = Method->getTrailingRequiresClause())
18037     if (!Finder.TraverseStmt(E))
18038       return true;
18039 
18040   return checkThisInStaticMemberFunctionAttributes(Method);
18041 }
18042 
18043 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18044   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18045   if (!TSInfo)
18046     return false;
18047 
18048   TypeLoc TL = TSInfo->getTypeLoc();
18049   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18050   if (!ProtoTL)
18051     return false;
18052 
18053   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18054   FindCXXThisExpr Finder(*this);
18055 
18056   switch (Proto->getExceptionSpecType()) {
18057   case EST_Unparsed:
18058   case EST_Uninstantiated:
18059   case EST_Unevaluated:
18060   case EST_BasicNoexcept:
18061   case EST_NoThrow:
18062   case EST_DynamicNone:
18063   case EST_MSAny:
18064   case EST_None:
18065     break;
18066 
18067   case EST_DependentNoexcept:
18068   case EST_NoexceptFalse:
18069   case EST_NoexceptTrue:
18070     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18071       return true;
18072     LLVM_FALLTHROUGH;
18073 
18074   case EST_Dynamic:
18075     for (const auto &E : Proto->exceptions()) {
18076       if (!Finder.TraverseType(E))
18077         return true;
18078     }
18079     break;
18080   }
18081 
18082   return false;
18083 }
18084 
18085 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
18086   FindCXXThisExpr Finder(*this);
18087 
18088   // Check attributes.
18089   for (const auto *A : Method->attrs()) {
18090     // FIXME: This should be emitted by tblgen.
18091     Expr *Arg = nullptr;
18092     ArrayRef<Expr *> Args;
18093     if (const auto *G = dyn_cast<GuardedByAttr>(A))
18094       Arg = G->getArg();
18095     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18096       Arg = G->getArg();
18097     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18098       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
18099     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18100       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
18101     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18102       Arg = ETLF->getSuccessValue();
18103       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
18104     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18105       Arg = STLF->getSuccessValue();
18106       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
18107     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18108       Arg = LR->getArg();
18109     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18110       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
18111     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18112       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18113     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18114       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18115     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18116       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18117     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18118       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18119 
18120     if (Arg && !Finder.TraverseStmt(Arg))
18121       return true;
18122 
18123     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18124       if (!Finder.TraverseStmt(Args[I]))
18125         return true;
18126     }
18127   }
18128 
18129   return false;
18130 }
18131 
18132 void Sema::checkExceptionSpecification(
18133     bool IsTopLevel, ExceptionSpecificationType EST,
18134     ArrayRef<ParsedType> DynamicExceptions,
18135     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18136     SmallVectorImpl<QualType> &Exceptions,
18137     FunctionProtoType::ExceptionSpecInfo &ESI) {
18138   Exceptions.clear();
18139   ESI.Type = EST;
18140   if (EST == EST_Dynamic) {
18141     Exceptions.reserve(DynamicExceptions.size());
18142     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18143       // FIXME: Preserve type source info.
18144       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18145 
18146       if (IsTopLevel) {
18147         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
18148         collectUnexpandedParameterPacks(ET, Unexpanded);
18149         if (!Unexpanded.empty()) {
18150           DiagnoseUnexpandedParameterPacks(
18151               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18152               Unexpanded);
18153           continue;
18154         }
18155       }
18156 
18157       // Check that the type is valid for an exception spec, and
18158       // drop it if not.
18159       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18160         Exceptions.push_back(ET);
18161     }
18162     ESI.Exceptions = Exceptions;
18163     return;
18164   }
18165 
18166   if (isComputedNoexcept(EST)) {
18167     assert((NoexceptExpr->isTypeDependent() ||
18168             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18169             Context.BoolTy) &&
18170            "Parser should have made sure that the expression is boolean");
18171     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18172       ESI.Type = EST_BasicNoexcept;
18173       return;
18174     }
18175 
18176     ESI.NoexceptExpr = NoexceptExpr;
18177     return;
18178   }
18179 }
18180 
18181 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
18182              ExceptionSpecificationType EST,
18183              SourceRange SpecificationRange,
18184              ArrayRef<ParsedType> DynamicExceptions,
18185              ArrayRef<SourceRange> DynamicExceptionRanges,
18186              Expr *NoexceptExpr) {
18187   if (!MethodD)
18188     return;
18189 
18190   // Dig out the method we're referring to.
18191   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18192     MethodD = FunTmpl->getTemplatedDecl();
18193 
18194   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18195   if (!Method)
18196     return;
18197 
18198   // Check the exception specification.
18199   llvm::SmallVector<QualType, 4> Exceptions;
18200   FunctionProtoType::ExceptionSpecInfo ESI;
18201   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18202                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
18203                               ESI);
18204 
18205   // Update the exception specification on the function type.
18206   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18207 
18208   if (Method->isStatic())
18209     checkThisInStaticMemberFunctionExceptionSpec(Method);
18210 
18211   if (Method->isVirtual()) {
18212     // Check overrides, which we previously had to delay.
18213     for (const CXXMethodDecl *O : Method->overridden_methods())
18214       CheckOverridingFunctionExceptionSpec(Method, O);
18215   }
18216 }
18217 
18218 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18219 ///
18220 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18221                                        SourceLocation DeclStart, Declarator &D,
18222                                        Expr *BitWidth,
18223                                        InClassInitStyle InitStyle,
18224                                        AccessSpecifier AS,
18225                                        const ParsedAttr &MSPropertyAttr) {
18226   IdentifierInfo *II = D.getIdentifier();
18227   if (!II) {
18228     Diag(DeclStart, diag::err_anonymous_property);
18229     return nullptr;
18230   }
18231   SourceLocation Loc = D.getIdentifierLoc();
18232 
18233   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18234   QualType T = TInfo->getType();
18235   if (getLangOpts().CPlusPlus) {
18236     CheckExtraCXXDefaultArguments(D);
18237 
18238     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18239                                         UPPC_DataMemberType)) {
18240       D.setInvalidType();
18241       T = Context.IntTy;
18242       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18243     }
18244   }
18245 
18246   DiagnoseFunctionSpecifiers(D.getDeclSpec());
18247 
18248   if (D.getDeclSpec().isInlineSpecified())
18249     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18250         << getLangOpts().CPlusPlus17;
18251   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18252     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18253          diag::err_invalid_thread)
18254       << DeclSpec::getSpecifierName(TSCS);
18255 
18256   // Check to see if this name was declared as a member previously
18257   NamedDecl *PrevDecl = nullptr;
18258   LookupResult Previous(*this, II, Loc, LookupMemberName,
18259                         ForVisibleRedeclaration);
18260   LookupName(Previous, S);
18261   switch (Previous.getResultKind()) {
18262   case LookupResult::Found:
18263   case LookupResult::FoundUnresolvedValue:
18264     PrevDecl = Previous.getAsSingle<NamedDecl>();
18265     break;
18266 
18267   case LookupResult::FoundOverloaded:
18268     PrevDecl = Previous.getRepresentativeDecl();
18269     break;
18270 
18271   case LookupResult::NotFound:
18272   case LookupResult::NotFoundInCurrentInstantiation:
18273   case LookupResult::Ambiguous:
18274     break;
18275   }
18276 
18277   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18278     // Maybe we will complain about the shadowed template parameter.
18279     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18280     // Just pretend that we didn't see the previous declaration.
18281     PrevDecl = nullptr;
18282   }
18283 
18284   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18285     PrevDecl = nullptr;
18286 
18287   SourceLocation TSSL = D.getBeginLoc();
18288   MSPropertyDecl *NewPD =
18289       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18290                              MSPropertyAttr.getPropertyDataGetter(),
18291                              MSPropertyAttr.getPropertyDataSetter());
18292   ProcessDeclAttributes(TUScope, NewPD, D);
18293   NewPD->setAccess(AS);
18294 
18295   if (NewPD->isInvalidDecl())
18296     Record->setInvalidDecl();
18297 
18298   if (D.getDeclSpec().isModulePrivateSpecified())
18299     NewPD->setModulePrivate();
18300 
18301   if (NewPD->isInvalidDecl() && PrevDecl) {
18302     // Don't introduce NewFD into scope; there's already something
18303     // with the same name in the same scope.
18304   } else if (II) {
18305     PushOnScopeChains(NewPD, S);
18306   } else
18307     Record->addDecl(NewPD);
18308 
18309   return NewPD;
18310 }
18311 
18312 void Sema::ActOnStartFunctionDeclarationDeclarator(
18313     Declarator &Declarator, unsigned TemplateParameterDepth) {
18314   auto &Info = InventedParameterInfos.emplace_back();
18315   TemplateParameterList *ExplicitParams = nullptr;
18316   ArrayRef<TemplateParameterList *> ExplicitLists =
18317       Declarator.getTemplateParameterLists();
18318   if (!ExplicitLists.empty()) {
18319     bool IsMemberSpecialization, IsInvalid;
18320     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18321         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18322         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18323         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18324         /*SuppressDiagnostic=*/true);
18325   }
18326   if (ExplicitParams) {
18327     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18328     llvm::append_range(Info.TemplateParams, *ExplicitParams);
18329     Info.NumExplicitTemplateParams = ExplicitParams->size();
18330   } else {
18331     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18332     Info.NumExplicitTemplateParams = 0;
18333   }
18334 }
18335 
18336 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18337   auto &FSI = InventedParameterInfos.back();
18338   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18339     if (FSI.NumExplicitTemplateParams != 0) {
18340       TemplateParameterList *ExplicitParams =
18341           Declarator.getTemplateParameterLists().back();
18342       Declarator.setInventedTemplateParameterList(
18343           TemplateParameterList::Create(
18344               Context, ExplicitParams->getTemplateLoc(),
18345               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18346               ExplicitParams->getRAngleLoc(),
18347               ExplicitParams->getRequiresClause()));
18348     } else {
18349       Declarator.setInventedTemplateParameterList(
18350           TemplateParameterList::Create(
18351               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18352               SourceLocation(), /*RequiresClause=*/nullptr));
18353     }
18354   }
18355   InventedParameterInfos.pop_back();
18356 }
18357