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_static_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::err_constexpr_local_var_non_literal_type,
1907                              isa<CXXConstructorDecl>(Dcl)))
1908           return false;
1909         if (!VD->getType()->isDependentType() &&
1910             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1911           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1912             SemaRef.Diag(
1913                 VD->getLocation(),
1914                 SemaRef.getLangOpts().CPlusPlus20
1915                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1916                     : diag::ext_constexpr_local_var_no_init)
1917                 << isa<CXXConstructorDecl>(Dcl);
1918           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1919             return false;
1920           }
1921           continue;
1922         }
1923       }
1924       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1925         SemaRef.Diag(VD->getLocation(),
1926                      SemaRef.getLangOpts().CPlusPlus14
1927                       ? diag::warn_cxx11_compat_constexpr_local_var
1928                       : diag::ext_constexpr_local_var)
1929           << isa<CXXConstructorDecl>(Dcl);
1930       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1931         return false;
1932       }
1933       continue;
1934     }
1935 
1936     case Decl::NamespaceAlias:
1937     case Decl::Function:
1938       // These are disallowed in C++11 and permitted in C++1y. Allow them
1939       // everywhere as an extension.
1940       if (!Cxx1yLoc.isValid())
1941         Cxx1yLoc = DS->getBeginLoc();
1942       continue;
1943 
1944     default:
1945       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1946         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1947             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1948       }
1949       return false;
1950     }
1951   }
1952 
1953   return true;
1954 }
1955 
1956 /// Check that the given field is initialized within a constexpr constructor.
1957 ///
1958 /// \param Dcl The constexpr constructor being checked.
1959 /// \param Field The field being checked. This may be a member of an anonymous
1960 ///        struct or union nested within the class being checked.
1961 /// \param Inits All declarations, including anonymous struct/union members and
1962 ///        indirect members, for which any initialization was provided.
1963 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1964 ///        multiple notes for different members to the same error.
1965 /// \param Kind Whether we're diagnosing a constructor as written or determining
1966 ///        whether the formal requirements are satisfied.
1967 /// \return \c false if we're checking for validity and the constructor does
1968 ///         not satisfy the requirements on a constexpr constructor.
1969 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1970                                           const FunctionDecl *Dcl,
1971                                           FieldDecl *Field,
1972                                           llvm::SmallSet<Decl*, 16> &Inits,
1973                                           bool &Diagnosed,
1974                                           Sema::CheckConstexprKind Kind) {
1975   // In C++20 onwards, there's nothing to check for validity.
1976   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1977       SemaRef.getLangOpts().CPlusPlus20)
1978     return true;
1979 
1980   if (Field->isInvalidDecl())
1981     return true;
1982 
1983   if (Field->isUnnamedBitfield())
1984     return true;
1985 
1986   // Anonymous unions with no variant members and empty anonymous structs do not
1987   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1988   // indirect fields don't need initializing.
1989   if (Field->isAnonymousStructOrUnion() &&
1990       (Field->getType()->isUnionType()
1991            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1992            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1993     return true;
1994 
1995   if (!Inits.count(Field)) {
1996     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1997       if (!Diagnosed) {
1998         SemaRef.Diag(Dcl->getLocation(),
1999                      SemaRef.getLangOpts().CPlusPlus20
2000                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2001                          : diag::ext_constexpr_ctor_missing_init);
2002         Diagnosed = true;
2003       }
2004       SemaRef.Diag(Field->getLocation(),
2005                    diag::note_constexpr_ctor_missing_init);
2006     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2007       return false;
2008     }
2009   } else if (Field->isAnonymousStructOrUnion()) {
2010     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2011     for (auto *I : RD->fields())
2012       // If an anonymous union contains an anonymous struct of which any member
2013       // is initialized, all members must be initialized.
2014       if (!RD->isUnion() || Inits.count(I))
2015         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2016                                            Kind))
2017           return false;
2018   }
2019   return true;
2020 }
2021 
2022 /// Check the provided statement is allowed in a constexpr function
2023 /// definition.
2024 static bool
2025 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2026                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2027                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2028                            SourceLocation &Cxx2bLoc,
2029                            Sema::CheckConstexprKind Kind) {
2030   // - its function-body shall be [...] a compound-statement that contains only
2031   switch (S->getStmtClass()) {
2032   case Stmt::NullStmtClass:
2033     //   - null statements,
2034     return true;
2035 
2036   case Stmt::DeclStmtClass:
2037     //   - static_assert-declarations
2038     //   - using-declarations,
2039     //   - using-directives,
2040     //   - typedef declarations and alias-declarations that do not define
2041     //     classes or enumerations,
2042     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2043       return false;
2044     return true;
2045 
2046   case Stmt::ReturnStmtClass:
2047     //   - and exactly one return statement;
2048     if (isa<CXXConstructorDecl>(Dcl)) {
2049       // C++1y allows return statements in constexpr constructors.
2050       if (!Cxx1yLoc.isValid())
2051         Cxx1yLoc = S->getBeginLoc();
2052       return true;
2053     }
2054 
2055     ReturnStmts.push_back(S->getBeginLoc());
2056     return true;
2057 
2058   case Stmt::AttributedStmtClass:
2059     // Attributes on a statement don't affect its formal kind and hence don't
2060     // affect its validity in a constexpr function.
2061     return CheckConstexprFunctionStmt(
2062         SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2063         Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2064 
2065   case Stmt::CompoundStmtClass: {
2066     // C++1y allows compound-statements.
2067     if (!Cxx1yLoc.isValid())
2068       Cxx1yLoc = S->getBeginLoc();
2069 
2070     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2071     for (auto *BodyIt : CompStmt->body()) {
2072       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2073                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2074         return false;
2075     }
2076     return true;
2077   }
2078 
2079   case Stmt::IfStmtClass: {
2080     // C++1y allows if-statements.
2081     if (!Cxx1yLoc.isValid())
2082       Cxx1yLoc = S->getBeginLoc();
2083 
2084     IfStmt *If = cast<IfStmt>(S);
2085     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2086                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2087       return false;
2088     if (If->getElse() &&
2089         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2090                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2091       return false;
2092     return true;
2093   }
2094 
2095   case Stmt::WhileStmtClass:
2096   case Stmt::DoStmtClass:
2097   case Stmt::ForStmtClass:
2098   case Stmt::CXXForRangeStmtClass:
2099   case Stmt::ContinueStmtClass:
2100     // C++1y allows all of these. We don't allow them as extensions in C++11,
2101     // because they don't make sense without variable mutation.
2102     if (!SemaRef.getLangOpts().CPlusPlus14)
2103       break;
2104     if (!Cxx1yLoc.isValid())
2105       Cxx1yLoc = S->getBeginLoc();
2106     for (Stmt *SubStmt : S->children()) {
2107       if (SubStmt &&
2108           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2109                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2110         return false;
2111     }
2112     return true;
2113 
2114   case Stmt::SwitchStmtClass:
2115   case Stmt::CaseStmtClass:
2116   case Stmt::DefaultStmtClass:
2117   case Stmt::BreakStmtClass:
2118     // C++1y allows switch-statements, and since they don't need variable
2119     // mutation, we can reasonably allow them in C++11 as an extension.
2120     if (!Cxx1yLoc.isValid())
2121       Cxx1yLoc = S->getBeginLoc();
2122     for (Stmt *SubStmt : S->children()) {
2123       if (SubStmt &&
2124           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2125                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2126         return false;
2127     }
2128     return true;
2129 
2130   case Stmt::LabelStmtClass:
2131   case Stmt::GotoStmtClass:
2132     if (Cxx2bLoc.isInvalid())
2133       Cxx2bLoc = S->getBeginLoc();
2134     for (Stmt *SubStmt : S->children()) {
2135       if (SubStmt &&
2136           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2137                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2138         return false;
2139     }
2140     return true;
2141 
2142   case Stmt::GCCAsmStmtClass:
2143   case Stmt::MSAsmStmtClass:
2144     // C++2a allows inline assembly statements.
2145   case Stmt::CXXTryStmtClass:
2146     if (Cxx2aLoc.isInvalid())
2147       Cxx2aLoc = S->getBeginLoc();
2148     for (Stmt *SubStmt : S->children()) {
2149       if (SubStmt &&
2150           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2151                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2152         return false;
2153     }
2154     return true;
2155 
2156   case Stmt::CXXCatchStmtClass:
2157     // Do not bother checking the language mode (already covered by the
2158     // try block check).
2159     if (!CheckConstexprFunctionStmt(
2160             SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2161             Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2162       return false;
2163     return true;
2164 
2165   default:
2166     if (!isa<Expr>(S))
2167       break;
2168 
2169     // C++1y allows expression-statements.
2170     if (!Cxx1yLoc.isValid())
2171       Cxx1yLoc = S->getBeginLoc();
2172     return true;
2173   }
2174 
2175   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2176     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2177         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2178   }
2179   return false;
2180 }
2181 
2182 /// Check the body for the given constexpr function declaration only contains
2183 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2184 ///
2185 /// \return true if the body is OK, false if we have found or diagnosed a
2186 /// problem.
2187 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2188                                        Stmt *Body,
2189                                        Sema::CheckConstexprKind Kind) {
2190   SmallVector<SourceLocation, 4> ReturnStmts;
2191 
2192   if (isa<CXXTryStmt>(Body)) {
2193     // C++11 [dcl.constexpr]p3:
2194     //  The definition of a constexpr function shall satisfy the following
2195     //  constraints: [...]
2196     // - its function-body shall be = delete, = default, or a
2197     //   compound-statement
2198     //
2199     // C++11 [dcl.constexpr]p4:
2200     //  In the definition of a constexpr constructor, [...]
2201     // - its function-body shall not be a function-try-block;
2202     //
2203     // This restriction is lifted in C++2a, as long as inner statements also
2204     // apply the general constexpr rules.
2205     switch (Kind) {
2206     case Sema::CheckConstexprKind::CheckValid:
2207       if (!SemaRef.getLangOpts().CPlusPlus20)
2208         return false;
2209       break;
2210 
2211     case Sema::CheckConstexprKind::Diagnose:
2212       SemaRef.Diag(Body->getBeginLoc(),
2213            !SemaRef.getLangOpts().CPlusPlus20
2214                ? diag::ext_constexpr_function_try_block_cxx20
2215                : diag::warn_cxx17_compat_constexpr_function_try_block)
2216           << isa<CXXConstructorDecl>(Dcl);
2217       break;
2218     }
2219   }
2220 
2221   // - its function-body shall be [...] a compound-statement that contains only
2222   //   [... list of cases ...]
2223   //
2224   // Note that walking the children here is enough to properly check for
2225   // CompoundStmt and CXXTryStmt body.
2226   SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2227   for (Stmt *SubStmt : Body->children()) {
2228     if (SubStmt &&
2229         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2230                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2231       return false;
2232   }
2233 
2234   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2235     // If this is only valid as an extension, report that we don't satisfy the
2236     // constraints of the current language.
2237     if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) ||
2238         (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2239         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2240       return false;
2241   } else if (Cxx2bLoc.isValid()) {
2242     SemaRef.Diag(Cxx2bLoc,
2243                  SemaRef.getLangOpts().CPlusPlus2b
2244                      ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2245                      : diag::ext_constexpr_body_invalid_stmt_cxx2b)
2246         << isa<CXXConstructorDecl>(Dcl);
2247   } else if (Cxx2aLoc.isValid()) {
2248     SemaRef.Diag(Cxx2aLoc,
2249          SemaRef.getLangOpts().CPlusPlus20
2250            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2251            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2252       << isa<CXXConstructorDecl>(Dcl);
2253   } else if (Cxx1yLoc.isValid()) {
2254     SemaRef.Diag(Cxx1yLoc,
2255          SemaRef.getLangOpts().CPlusPlus14
2256            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2257            : diag::ext_constexpr_body_invalid_stmt)
2258       << isa<CXXConstructorDecl>(Dcl);
2259   }
2260 
2261   if (const CXXConstructorDecl *Constructor
2262         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2263     const CXXRecordDecl *RD = Constructor->getParent();
2264     // DR1359:
2265     // - every non-variant non-static data member and base class sub-object
2266     //   shall be initialized;
2267     // DR1460:
2268     // - if the class is a union having variant members, exactly one of them
2269     //   shall be initialized;
2270     if (RD->isUnion()) {
2271       if (Constructor->getNumCtorInitializers() == 0 &&
2272           RD->hasVariantMembers()) {
2273         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2274           SemaRef.Diag(
2275               Dcl->getLocation(),
2276               SemaRef.getLangOpts().CPlusPlus20
2277                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2278                   : diag::ext_constexpr_union_ctor_no_init);
2279         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2280           return false;
2281         }
2282       }
2283     } else if (!Constructor->isDependentContext() &&
2284                !Constructor->isDelegatingConstructor()) {
2285       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2286 
2287       // Skip detailed checking if we have enough initializers, and we would
2288       // allow at most one initializer per member.
2289       bool AnyAnonStructUnionMembers = false;
2290       unsigned Fields = 0;
2291       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2292            E = RD->field_end(); I != E; ++I, ++Fields) {
2293         if (I->isAnonymousStructOrUnion()) {
2294           AnyAnonStructUnionMembers = true;
2295           break;
2296         }
2297       }
2298       // DR1460:
2299       // - if the class is a union-like class, but is not a union, for each of
2300       //   its anonymous union members having variant members, exactly one of
2301       //   them shall be initialized;
2302       if (AnyAnonStructUnionMembers ||
2303           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2304         // Check initialization of non-static data members. Base classes are
2305         // always initialized so do not need to be checked. Dependent bases
2306         // might not have initializers in the member initializer list.
2307         llvm::SmallSet<Decl*, 16> Inits;
2308         for (const auto *I: Constructor->inits()) {
2309           if (FieldDecl *FD = I->getMember())
2310             Inits.insert(FD);
2311           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2312             Inits.insert(ID->chain_begin(), ID->chain_end());
2313         }
2314 
2315         bool Diagnosed = false;
2316         for (auto *I : RD->fields())
2317           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2318                                              Kind))
2319             return false;
2320       }
2321     }
2322   } else {
2323     if (ReturnStmts.empty()) {
2324       // C++1y doesn't require constexpr functions to contain a 'return'
2325       // statement. We still do, unless the return type might be void, because
2326       // otherwise if there's no return statement, the function cannot
2327       // be used in a core constant expression.
2328       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2329                 (Dcl->getReturnType()->isVoidType() ||
2330                  Dcl->getReturnType()->isDependentType());
2331       switch (Kind) {
2332       case Sema::CheckConstexprKind::Diagnose:
2333         SemaRef.Diag(Dcl->getLocation(),
2334                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2335                         : diag::err_constexpr_body_no_return)
2336             << Dcl->isConsteval();
2337         if (!OK)
2338           return false;
2339         break;
2340 
2341       case Sema::CheckConstexprKind::CheckValid:
2342         // The formal requirements don't include this rule in C++14, even
2343         // though the "must be able to produce a constant expression" rules
2344         // still imply it in some cases.
2345         if (!SemaRef.getLangOpts().CPlusPlus14)
2346           return false;
2347         break;
2348       }
2349     } else if (ReturnStmts.size() > 1) {
2350       switch (Kind) {
2351       case Sema::CheckConstexprKind::Diagnose:
2352         SemaRef.Diag(
2353             ReturnStmts.back(),
2354             SemaRef.getLangOpts().CPlusPlus14
2355                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2356                 : diag::ext_constexpr_body_multiple_return);
2357         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2358           SemaRef.Diag(ReturnStmts[I],
2359                        diag::note_constexpr_body_previous_return);
2360         break;
2361 
2362       case Sema::CheckConstexprKind::CheckValid:
2363         if (!SemaRef.getLangOpts().CPlusPlus14)
2364           return false;
2365         break;
2366       }
2367     }
2368   }
2369 
2370   // C++11 [dcl.constexpr]p5:
2371   //   if no function argument values exist such that the function invocation
2372   //   substitution would produce a constant expression, the program is
2373   //   ill-formed; no diagnostic required.
2374   // C++11 [dcl.constexpr]p3:
2375   //   - every constructor call and implicit conversion used in initializing the
2376   //     return value shall be one of those allowed in a constant expression.
2377   // C++11 [dcl.constexpr]p4:
2378   //   - every constructor involved in initializing non-static data members and
2379   //     base class sub-objects shall be a constexpr constructor.
2380   //
2381   // Note that this rule is distinct from the "requirements for a constexpr
2382   // function", so is not checked in CheckValid mode.
2383   SmallVector<PartialDiagnosticAt, 8> Diags;
2384   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2385       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2386     SemaRef.Diag(Dcl->getLocation(),
2387                  diag::ext_constexpr_function_never_constant_expr)
2388         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2389     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2390       SemaRef.Diag(Diags[I].first, Diags[I].second);
2391     // Don't return false here: we allow this for compatibility in
2392     // system headers.
2393   }
2394 
2395   return true;
2396 }
2397 
2398 /// Get the class that is directly named by the current context. This is the
2399 /// class for which an unqualified-id in this scope could name a constructor
2400 /// or destructor.
2401 ///
2402 /// If the scope specifier denotes a class, this will be that class.
2403 /// If the scope specifier is empty, this will be the class whose
2404 /// member-specification we are currently within. Otherwise, there
2405 /// is no such class.
2406 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2407   assert(getLangOpts().CPlusPlus && "No class names in C!");
2408 
2409   if (SS && SS->isInvalid())
2410     return nullptr;
2411 
2412   if (SS && SS->isNotEmpty()) {
2413     DeclContext *DC = computeDeclContext(*SS, true);
2414     return dyn_cast_or_null<CXXRecordDecl>(DC);
2415   }
2416 
2417   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2418 }
2419 
2420 /// isCurrentClassName - Determine whether the identifier II is the
2421 /// name of the class type currently being defined. In the case of
2422 /// nested classes, this will only return true if II is the name of
2423 /// the innermost class.
2424 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2425                               const CXXScopeSpec *SS) {
2426   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2427   return CurDecl && &II == CurDecl->getIdentifier();
2428 }
2429 
2430 /// Determine whether the identifier II is a typo for the name of
2431 /// the class type currently being defined. If so, update it to the identifier
2432 /// that should have been used.
2433 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2434   assert(getLangOpts().CPlusPlus && "No class names in C!");
2435 
2436   if (!getLangOpts().SpellChecking)
2437     return false;
2438 
2439   CXXRecordDecl *CurDecl;
2440   if (SS && SS->isSet() && !SS->isInvalid()) {
2441     DeclContext *DC = computeDeclContext(*SS, true);
2442     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2443   } else
2444     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2445 
2446   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2447       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2448           < II->getLength()) {
2449     II = CurDecl->getIdentifier();
2450     return true;
2451   }
2452 
2453   return false;
2454 }
2455 
2456 /// Determine whether the given class is a base class of the given
2457 /// class, including looking at dependent bases.
2458 static bool findCircularInheritance(const CXXRecordDecl *Class,
2459                                     const CXXRecordDecl *Current) {
2460   SmallVector<const CXXRecordDecl*, 8> Queue;
2461 
2462   Class = Class->getCanonicalDecl();
2463   while (true) {
2464     for (const auto &I : Current->bases()) {
2465       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2466       if (!Base)
2467         continue;
2468 
2469       Base = Base->getDefinition();
2470       if (!Base)
2471         continue;
2472 
2473       if (Base->getCanonicalDecl() == Class)
2474         return true;
2475 
2476       Queue.push_back(Base);
2477     }
2478 
2479     if (Queue.empty())
2480       return false;
2481 
2482     Current = Queue.pop_back_val();
2483   }
2484 
2485   return false;
2486 }
2487 
2488 /// Check the validity of a C++ base class specifier.
2489 ///
2490 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2491 /// and returns NULL otherwise.
2492 CXXBaseSpecifier *
2493 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2494                          SourceRange SpecifierRange,
2495                          bool Virtual, AccessSpecifier Access,
2496                          TypeSourceInfo *TInfo,
2497                          SourceLocation EllipsisLoc) {
2498   QualType BaseType = TInfo->getType();
2499   if (BaseType->containsErrors()) {
2500     // Already emitted a diagnostic when parsing the error type.
2501     return nullptr;
2502   }
2503   // C++ [class.union]p1:
2504   //   A union shall not have base classes.
2505   if (Class->isUnion()) {
2506     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2507       << SpecifierRange;
2508     return nullptr;
2509   }
2510 
2511   if (EllipsisLoc.isValid() &&
2512       !TInfo->getType()->containsUnexpandedParameterPack()) {
2513     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2514       << TInfo->getTypeLoc().getSourceRange();
2515     EllipsisLoc = SourceLocation();
2516   }
2517 
2518   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2519 
2520   if (BaseType->isDependentType()) {
2521     // Make sure that we don't have circular inheritance among our dependent
2522     // bases. For non-dependent bases, the check for completeness below handles
2523     // this.
2524     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2525       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2526           ((BaseDecl = BaseDecl->getDefinition()) &&
2527            findCircularInheritance(Class, BaseDecl))) {
2528         Diag(BaseLoc, diag::err_circular_inheritance)
2529           << BaseType << Context.getTypeDeclType(Class);
2530 
2531         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2532           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2533             << BaseType;
2534 
2535         return nullptr;
2536       }
2537     }
2538 
2539     // Make sure that we don't make an ill-formed AST where the type of the
2540     // Class is non-dependent and its attached base class specifier is an
2541     // dependent type, which violates invariants in many clang code paths (e.g.
2542     // constexpr evaluator). If this case happens (in errory-recovery mode), we
2543     // explicitly mark the Class decl invalid. The diagnostic was already
2544     // emitted.
2545     if (!Class->getTypeForDecl()->isDependentType())
2546       Class->setInvalidDecl();
2547     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2548                                           Class->getTagKind() == TTK_Class,
2549                                           Access, TInfo, EllipsisLoc);
2550   }
2551 
2552   // Base specifiers must be record types.
2553   if (!BaseType->isRecordType()) {
2554     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2555     return nullptr;
2556   }
2557 
2558   // C++ [class.union]p1:
2559   //   A union shall not be used as a base class.
2560   if (BaseType->isUnionType()) {
2561     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2562     return nullptr;
2563   }
2564 
2565   // For the MS ABI, propagate DLL attributes to base class templates.
2566   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2567     if (Attr *ClassAttr = getDLLAttr(Class)) {
2568       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2569               BaseType->getAsCXXRecordDecl())) {
2570         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2571                                             BaseLoc);
2572       }
2573     }
2574   }
2575 
2576   // C++ [class.derived]p2:
2577   //   The class-name in a base-specifier shall not be an incompletely
2578   //   defined class.
2579   if (RequireCompleteType(BaseLoc, BaseType,
2580                           diag::err_incomplete_base_class, SpecifierRange)) {
2581     Class->setInvalidDecl();
2582     return nullptr;
2583   }
2584 
2585   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2586   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2587   assert(BaseDecl && "Record type has no declaration");
2588   BaseDecl = BaseDecl->getDefinition();
2589   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2590   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2591   assert(CXXBaseDecl && "Base type is not a C++ type");
2592 
2593   // Microsoft docs say:
2594   // "If a base-class has a code_seg attribute, derived classes must have the
2595   // same attribute."
2596   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2597   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2598   if ((DerivedCSA || BaseCSA) &&
2599       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2600     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2601     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2602       << CXXBaseDecl;
2603     return nullptr;
2604   }
2605 
2606   // A class which contains a flexible array member is not suitable for use as a
2607   // base class:
2608   //   - If the layout determines that a base comes before another base,
2609   //     the flexible array member would index into the subsequent base.
2610   //   - If the layout determines that base comes before the derived class,
2611   //     the flexible array member would index into the derived class.
2612   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2613     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2614       << CXXBaseDecl->getDeclName();
2615     return nullptr;
2616   }
2617 
2618   // C++ [class]p3:
2619   //   If a class is marked final and it appears as a base-type-specifier in
2620   //   base-clause, the program is ill-formed.
2621   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2622     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2623       << CXXBaseDecl->getDeclName()
2624       << FA->isSpelledAsSealed();
2625     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2626         << CXXBaseDecl->getDeclName() << FA->getRange();
2627     return nullptr;
2628   }
2629 
2630   if (BaseDecl->isInvalidDecl())
2631     Class->setInvalidDecl();
2632 
2633   // Create the base specifier.
2634   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2635                                         Class->getTagKind() == TTK_Class,
2636                                         Access, TInfo, EllipsisLoc);
2637 }
2638 
2639 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2640 /// one entry in the base class list of a class specifier, for
2641 /// example:
2642 ///    class foo : public bar, virtual private baz {
2643 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2644 BaseResult
2645 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2646                          ParsedAttributes &Attributes,
2647                          bool Virtual, AccessSpecifier Access,
2648                          ParsedType basetype, SourceLocation BaseLoc,
2649                          SourceLocation EllipsisLoc) {
2650   if (!classdecl)
2651     return true;
2652 
2653   AdjustDeclIfTemplate(classdecl);
2654   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2655   if (!Class)
2656     return true;
2657 
2658   // We haven't yet attached the base specifiers.
2659   Class->setIsParsingBaseSpecifiers();
2660 
2661   // We do not support any C++11 attributes on base-specifiers yet.
2662   // Diagnose any attributes we see.
2663   for (const ParsedAttr &AL : Attributes) {
2664     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2665       continue;
2666     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2667                           ? (unsigned)diag::warn_unknown_attribute_ignored
2668                           : (unsigned)diag::err_base_specifier_attribute)
2669         << AL << AL.getRange();
2670   }
2671 
2672   TypeSourceInfo *TInfo = nullptr;
2673   GetTypeFromParser(basetype, &TInfo);
2674 
2675   if (EllipsisLoc.isInvalid() &&
2676       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2677                                       UPPC_BaseType))
2678     return true;
2679 
2680   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2681                                                       Virtual, Access, TInfo,
2682                                                       EllipsisLoc))
2683     return BaseSpec;
2684   else
2685     Class->setInvalidDecl();
2686 
2687   return true;
2688 }
2689 
2690 /// Use small set to collect indirect bases.  As this is only used
2691 /// locally, there's no need to abstract the small size parameter.
2692 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2693 
2694 /// Recursively add the bases of Type.  Don't add Type itself.
2695 static void
2696 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2697                   const QualType &Type)
2698 {
2699   // Even though the incoming type is a base, it might not be
2700   // a class -- it could be a template parm, for instance.
2701   if (auto Rec = Type->getAs<RecordType>()) {
2702     auto Decl = Rec->getAsCXXRecordDecl();
2703 
2704     // Iterate over its bases.
2705     for (const auto &BaseSpec : Decl->bases()) {
2706       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2707         .getUnqualifiedType();
2708       if (Set.insert(Base).second)
2709         // If we've not already seen it, recurse.
2710         NoteIndirectBases(Context, Set, Base);
2711     }
2712   }
2713 }
2714 
2715 /// Performs the actual work of attaching the given base class
2716 /// specifiers to a C++ class.
2717 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2718                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2719  if (Bases.empty())
2720     return false;
2721 
2722   // Used to keep track of which base types we have already seen, so
2723   // that we can properly diagnose redundant direct base types. Note
2724   // that the key is always the unqualified canonical type of the base
2725   // class.
2726   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2727 
2728   // Used to track indirect bases so we can see if a direct base is
2729   // ambiguous.
2730   IndirectBaseSet IndirectBaseTypes;
2731 
2732   // Copy non-redundant base specifiers into permanent storage.
2733   unsigned NumGoodBases = 0;
2734   bool Invalid = false;
2735   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2736     QualType NewBaseType
2737       = Context.getCanonicalType(Bases[idx]->getType());
2738     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2739 
2740     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2741     if (KnownBase) {
2742       // C++ [class.mi]p3:
2743       //   A class shall not be specified as a direct base class of a
2744       //   derived class more than once.
2745       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2746           << KnownBase->getType() << Bases[idx]->getSourceRange();
2747 
2748       // Delete the duplicate base class specifier; we're going to
2749       // overwrite its pointer later.
2750       Context.Deallocate(Bases[idx]);
2751 
2752       Invalid = true;
2753     } else {
2754       // Okay, add this new base class.
2755       KnownBase = Bases[idx];
2756       Bases[NumGoodBases++] = Bases[idx];
2757 
2758       if (NewBaseType->isDependentType())
2759         continue;
2760       // Note this base's direct & indirect bases, if there could be ambiguity.
2761       if (Bases.size() > 1)
2762         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2763 
2764       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2765         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2766         if (Class->isInterface() &&
2767               (!RD->isInterfaceLike() ||
2768                KnownBase->getAccessSpecifier() != AS_public)) {
2769           // The Microsoft extension __interface does not permit bases that
2770           // are not themselves public interfaces.
2771           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2772               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2773               << RD->getSourceRange();
2774           Invalid = true;
2775         }
2776         if (RD->hasAttr<WeakAttr>())
2777           Class->addAttr(WeakAttr::CreateImplicit(Context));
2778       }
2779     }
2780   }
2781 
2782   // Attach the remaining base class specifiers to the derived class.
2783   Class->setBases(Bases.data(), NumGoodBases);
2784 
2785   // Check that the only base classes that are duplicate are virtual.
2786   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2787     // Check whether this direct base is inaccessible due to ambiguity.
2788     QualType BaseType = Bases[idx]->getType();
2789 
2790     // Skip all dependent types in templates being used as base specifiers.
2791     // Checks below assume that the base specifier is a CXXRecord.
2792     if (BaseType->isDependentType())
2793       continue;
2794 
2795     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2796       .getUnqualifiedType();
2797 
2798     if (IndirectBaseTypes.count(CanonicalBase)) {
2799       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2800                          /*DetectVirtual=*/true);
2801       bool found
2802         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2803       assert(found);
2804       (void)found;
2805 
2806       if (Paths.isAmbiguous(CanonicalBase))
2807         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2808             << BaseType << getAmbiguousPathsDisplayString(Paths)
2809             << Bases[idx]->getSourceRange();
2810       else
2811         assert(Bases[idx]->isVirtual());
2812     }
2813 
2814     // Delete the base class specifier, since its data has been copied
2815     // into the CXXRecordDecl.
2816     Context.Deallocate(Bases[idx]);
2817   }
2818 
2819   return Invalid;
2820 }
2821 
2822 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2823 /// class, after checking whether there are any duplicate base
2824 /// classes.
2825 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2826                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2827   if (!ClassDecl || Bases.empty())
2828     return;
2829 
2830   AdjustDeclIfTemplate(ClassDecl);
2831   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2832 }
2833 
2834 /// Determine whether the type \p Derived is a C++ class that is
2835 /// derived from the type \p Base.
2836 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2837   if (!getLangOpts().CPlusPlus)
2838     return false;
2839 
2840   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2841   if (!DerivedRD)
2842     return false;
2843 
2844   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2845   if (!BaseRD)
2846     return false;
2847 
2848   // If either the base or the derived type is invalid, don't try to
2849   // check whether one is derived from the other.
2850   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2851     return false;
2852 
2853   // FIXME: In a modules build, do we need the entire path to be visible for us
2854   // to be able to use the inheritance relationship?
2855   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2856     return false;
2857 
2858   return DerivedRD->isDerivedFrom(BaseRD);
2859 }
2860 
2861 /// Determine whether the type \p Derived is a C++ class that is
2862 /// derived from the type \p Base.
2863 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2864                          CXXBasePaths &Paths) {
2865   if (!getLangOpts().CPlusPlus)
2866     return false;
2867 
2868   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2869   if (!DerivedRD)
2870     return false;
2871 
2872   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2873   if (!BaseRD)
2874     return false;
2875 
2876   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2877     return false;
2878 
2879   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2880 }
2881 
2882 static void BuildBasePathArray(const CXXBasePath &Path,
2883                                CXXCastPath &BasePathArray) {
2884   // We first go backward and check if we have a virtual base.
2885   // FIXME: It would be better if CXXBasePath had the base specifier for
2886   // the nearest virtual base.
2887   unsigned Start = 0;
2888   for (unsigned I = Path.size(); I != 0; --I) {
2889     if (Path[I - 1].Base->isVirtual()) {
2890       Start = I - 1;
2891       break;
2892     }
2893   }
2894 
2895   // Now add all bases.
2896   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2897     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2898 }
2899 
2900 
2901 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2902                               CXXCastPath &BasePathArray) {
2903   assert(BasePathArray.empty() && "Base path array must be empty!");
2904   assert(Paths.isRecordingPaths() && "Must record paths!");
2905   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2906 }
2907 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2908 /// conversion (where Derived and Base are class types) is
2909 /// well-formed, meaning that the conversion is unambiguous (and
2910 /// that all of the base classes are accessible). Returns true
2911 /// and emits a diagnostic if the code is ill-formed, returns false
2912 /// otherwise. Loc is the location where this routine should point to
2913 /// if there is an error, and Range is the source range to highlight
2914 /// if there is an error.
2915 ///
2916 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2917 /// diagnostic for the respective type of error will be suppressed, but the
2918 /// check for ill-formed code will still be performed.
2919 bool
2920 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2921                                    unsigned InaccessibleBaseID,
2922                                    unsigned AmbiguousBaseConvID,
2923                                    SourceLocation Loc, SourceRange Range,
2924                                    DeclarationName Name,
2925                                    CXXCastPath *BasePath,
2926                                    bool IgnoreAccess) {
2927   // First, determine whether the path from Derived to Base is
2928   // ambiguous. This is slightly more expensive than checking whether
2929   // the Derived to Base conversion exists, because here we need to
2930   // explore multiple paths to determine if there is an ambiguity.
2931   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2932                      /*DetectVirtual=*/false);
2933   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2934   if (!DerivationOkay)
2935     return true;
2936 
2937   const CXXBasePath *Path = nullptr;
2938   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2939     Path = &Paths.front();
2940 
2941   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2942   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2943   // user to access such bases.
2944   if (!Path && getLangOpts().MSVCCompat) {
2945     for (const CXXBasePath &PossiblePath : Paths) {
2946       if (PossiblePath.size() == 1) {
2947         Path = &PossiblePath;
2948         if (AmbiguousBaseConvID)
2949           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2950               << Base << Derived << Range;
2951         break;
2952       }
2953     }
2954   }
2955 
2956   if (Path) {
2957     if (!IgnoreAccess) {
2958       // Check that the base class can be accessed.
2959       switch (
2960           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2961       case AR_inaccessible:
2962         return true;
2963       case AR_accessible:
2964       case AR_dependent:
2965       case AR_delayed:
2966         break;
2967       }
2968     }
2969 
2970     // Build a base path if necessary.
2971     if (BasePath)
2972       ::BuildBasePathArray(*Path, *BasePath);
2973     return false;
2974   }
2975 
2976   if (AmbiguousBaseConvID) {
2977     // We know that the derived-to-base conversion is ambiguous, and
2978     // we're going to produce a diagnostic. Perform the derived-to-base
2979     // search just one more time to compute all of the possible paths so
2980     // that we can print them out. This is more expensive than any of
2981     // the previous derived-to-base checks we've done, but at this point
2982     // performance isn't as much of an issue.
2983     Paths.clear();
2984     Paths.setRecordingPaths(true);
2985     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2986     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2987     (void)StillOkay;
2988 
2989     // Build up a textual representation of the ambiguous paths, e.g.,
2990     // D -> B -> A, that will be used to illustrate the ambiguous
2991     // conversions in the diagnostic. We only print one of the paths
2992     // to each base class subobject.
2993     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2994 
2995     Diag(Loc, AmbiguousBaseConvID)
2996     << Derived << Base << PathDisplayStr << Range << Name;
2997   }
2998   return true;
2999 }
3000 
3001 bool
3002 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3003                                    SourceLocation Loc, SourceRange Range,
3004                                    CXXCastPath *BasePath,
3005                                    bool IgnoreAccess) {
3006   return CheckDerivedToBaseConversion(
3007       Derived, Base, diag::err_upcast_to_inaccessible_base,
3008       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3009       BasePath, IgnoreAccess);
3010 }
3011 
3012 
3013 /// Builds a string representing ambiguous paths from a
3014 /// specific derived class to different subobjects of the same base
3015 /// class.
3016 ///
3017 /// This function builds a string that can be used in error messages
3018 /// to show the different paths that one can take through the
3019 /// inheritance hierarchy to go from the derived class to different
3020 /// subobjects of a base class. The result looks something like this:
3021 /// @code
3022 /// struct D -> struct B -> struct A
3023 /// struct D -> struct C -> struct A
3024 /// @endcode
3025 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3026   std::string PathDisplayStr;
3027   std::set<unsigned> DisplayedPaths;
3028   for (CXXBasePaths::paths_iterator Path = Paths.begin();
3029        Path != Paths.end(); ++Path) {
3030     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3031       // We haven't displayed a path to this particular base
3032       // class subobject yet.
3033       PathDisplayStr += "\n    ";
3034       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3035       for (CXXBasePath::const_iterator Element = Path->begin();
3036            Element != Path->end(); ++Element)
3037         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3038     }
3039   }
3040 
3041   return PathDisplayStr;
3042 }
3043 
3044 //===----------------------------------------------------------------------===//
3045 // C++ class member Handling
3046 //===----------------------------------------------------------------------===//
3047 
3048 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3049 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3050                                 SourceLocation ColonLoc,
3051                                 const ParsedAttributesView &Attrs) {
3052   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3053   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3054                                                   ASLoc, ColonLoc);
3055   CurContext->addHiddenDecl(ASDecl);
3056   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3057 }
3058 
3059 /// CheckOverrideControl - Check C++11 override control semantics.
3060 void Sema::CheckOverrideControl(NamedDecl *D) {
3061   if (D->isInvalidDecl())
3062     return;
3063 
3064   // We only care about "override" and "final" declarations.
3065   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3066     return;
3067 
3068   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3069 
3070   // We can't check dependent instance methods.
3071   if (MD && MD->isInstance() &&
3072       (MD->getParent()->hasAnyDependentBases() ||
3073        MD->getType()->isDependentType()))
3074     return;
3075 
3076   if (MD && !MD->isVirtual()) {
3077     // If we have a non-virtual method, check if if hides a virtual method.
3078     // (In that case, it's most likely the method has the wrong type.)
3079     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3080     FindHiddenVirtualMethods(MD, OverloadedMethods);
3081 
3082     if (!OverloadedMethods.empty()) {
3083       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3084         Diag(OA->getLocation(),
3085              diag::override_keyword_hides_virtual_member_function)
3086           << "override" << (OverloadedMethods.size() > 1);
3087       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3088         Diag(FA->getLocation(),
3089              diag::override_keyword_hides_virtual_member_function)
3090           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3091           << (OverloadedMethods.size() > 1);
3092       }
3093       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3094       MD->setInvalidDecl();
3095       return;
3096     }
3097     // Fall through into the general case diagnostic.
3098     // FIXME: We might want to attempt typo correction here.
3099   }
3100 
3101   if (!MD || !MD->isVirtual()) {
3102     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3103       Diag(OA->getLocation(),
3104            diag::override_keyword_only_allowed_on_virtual_member_functions)
3105         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3106       D->dropAttr<OverrideAttr>();
3107     }
3108     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3109       Diag(FA->getLocation(),
3110            diag::override_keyword_only_allowed_on_virtual_member_functions)
3111         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3112         << FixItHint::CreateRemoval(FA->getLocation());
3113       D->dropAttr<FinalAttr>();
3114     }
3115     return;
3116   }
3117 
3118   // C++11 [class.virtual]p5:
3119   //   If a function is marked with the virt-specifier override and
3120   //   does not override a member function of a base class, the program is
3121   //   ill-formed.
3122   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3123   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3124     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3125       << MD->getDeclName();
3126 }
3127 
3128 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3129   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3130     return;
3131   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3132   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3133     return;
3134 
3135   SourceLocation Loc = MD->getLocation();
3136   SourceLocation SpellingLoc = Loc;
3137   if (getSourceManager().isMacroArgExpansion(Loc))
3138     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3139   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3140   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3141       return;
3142 
3143   if (MD->size_overridden_methods() > 0) {
3144     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3145       unsigned DiagID =
3146           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3147               ? DiagInconsistent
3148               : DiagSuggest;
3149       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3150       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3151       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3152     };
3153     if (isa<CXXDestructorDecl>(MD))
3154       EmitDiag(
3155           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3156           diag::warn_suggest_destructor_marked_not_override_overriding);
3157     else
3158       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3159                diag::warn_suggest_function_marked_not_override_overriding);
3160   }
3161 }
3162 
3163 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3164 /// function overrides a virtual member function marked 'final', according to
3165 /// C++11 [class.virtual]p4.
3166 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3167                                                   const CXXMethodDecl *Old) {
3168   FinalAttr *FA = Old->getAttr<FinalAttr>();
3169   if (!FA)
3170     return false;
3171 
3172   Diag(New->getLocation(), diag::err_final_function_overridden)
3173     << New->getDeclName()
3174     << FA->isSpelledAsSealed();
3175   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3176   return true;
3177 }
3178 
3179 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3180   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3181   // FIXME: Destruction of ObjC lifetime types has side-effects.
3182   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3183     return !RD->isCompleteDefinition() ||
3184            !RD->hasTrivialDefaultConstructor() ||
3185            !RD->hasTrivialDestructor();
3186   return false;
3187 }
3188 
3189 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3190   ParsedAttributesView::const_iterator Itr =
3191       llvm::find_if(list, [](const ParsedAttr &AL) {
3192         return AL.isDeclspecPropertyAttribute();
3193       });
3194   if (Itr != list.end())
3195     return &*Itr;
3196   return nullptr;
3197 }
3198 
3199 // Check if there is a field shadowing.
3200 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3201                                       DeclarationName FieldName,
3202                                       const CXXRecordDecl *RD,
3203                                       bool DeclIsField) {
3204   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3205     return;
3206 
3207   // To record a shadowed field in a base
3208   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3209   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3210                            CXXBasePath &Path) {
3211     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3212     // Record an ambiguous path directly
3213     if (Bases.find(Base) != Bases.end())
3214       return true;
3215     for (const auto Field : Base->lookup(FieldName)) {
3216       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3217           Field->getAccess() != AS_private) {
3218         assert(Field->getAccess() != AS_none);
3219         assert(Bases.find(Base) == Bases.end());
3220         Bases[Base] = Field;
3221         return true;
3222       }
3223     }
3224     return false;
3225   };
3226 
3227   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3228                      /*DetectVirtual=*/true);
3229   if (!RD->lookupInBases(FieldShadowed, Paths))
3230     return;
3231 
3232   for (const auto &P : Paths) {
3233     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3234     auto It = Bases.find(Base);
3235     // Skip duplicated bases
3236     if (It == Bases.end())
3237       continue;
3238     auto BaseField = It->second;
3239     assert(BaseField->getAccess() != AS_private);
3240     if (AS_none !=
3241         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3242       Diag(Loc, diag::warn_shadow_field)
3243         << FieldName << RD << Base << DeclIsField;
3244       Diag(BaseField->getLocation(), diag::note_shadow_field);
3245       Bases.erase(It);
3246     }
3247   }
3248 }
3249 
3250 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3251 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3252 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3253 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3254 /// present (but parsing it has been deferred).
3255 NamedDecl *
3256 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3257                                MultiTemplateParamsArg TemplateParameterLists,
3258                                Expr *BW, const VirtSpecifiers &VS,
3259                                InClassInitStyle InitStyle) {
3260   const DeclSpec &DS = D.getDeclSpec();
3261   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3262   DeclarationName Name = NameInfo.getName();
3263   SourceLocation Loc = NameInfo.getLoc();
3264 
3265   // For anonymous bitfields, the location should point to the type.
3266   if (Loc.isInvalid())
3267     Loc = D.getBeginLoc();
3268 
3269   Expr *BitWidth = static_cast<Expr*>(BW);
3270 
3271   assert(isa<CXXRecordDecl>(CurContext));
3272   assert(!DS.isFriendSpecified());
3273 
3274   bool isFunc = D.isDeclarationOfFunction();
3275   const ParsedAttr *MSPropertyAttr =
3276       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3277 
3278   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3279     // The Microsoft extension __interface only permits public member functions
3280     // and prohibits constructors, destructors, operators, non-public member
3281     // functions, static methods and data members.
3282     unsigned InvalidDecl;
3283     bool ShowDeclName = true;
3284     if (!isFunc &&
3285         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3286       InvalidDecl = 0;
3287     else if (!isFunc)
3288       InvalidDecl = 1;
3289     else if (AS != AS_public)
3290       InvalidDecl = 2;
3291     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3292       InvalidDecl = 3;
3293     else switch (Name.getNameKind()) {
3294       case DeclarationName::CXXConstructorName:
3295         InvalidDecl = 4;
3296         ShowDeclName = false;
3297         break;
3298 
3299       case DeclarationName::CXXDestructorName:
3300         InvalidDecl = 5;
3301         ShowDeclName = false;
3302         break;
3303 
3304       case DeclarationName::CXXOperatorName:
3305       case DeclarationName::CXXConversionFunctionName:
3306         InvalidDecl = 6;
3307         break;
3308 
3309       default:
3310         InvalidDecl = 0;
3311         break;
3312     }
3313 
3314     if (InvalidDecl) {
3315       if (ShowDeclName)
3316         Diag(Loc, diag::err_invalid_member_in_interface)
3317           << (InvalidDecl-1) << Name;
3318       else
3319         Diag(Loc, diag::err_invalid_member_in_interface)
3320           << (InvalidDecl-1) << "";
3321       return nullptr;
3322     }
3323   }
3324 
3325   // C++ 9.2p6: A member shall not be declared to have automatic storage
3326   // duration (auto, register) or with the extern storage-class-specifier.
3327   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3328   // data members and cannot be applied to names declared const or static,
3329   // and cannot be applied to reference members.
3330   switch (DS.getStorageClassSpec()) {
3331   case DeclSpec::SCS_unspecified:
3332   case DeclSpec::SCS_typedef:
3333   case DeclSpec::SCS_static:
3334     break;
3335   case DeclSpec::SCS_mutable:
3336     if (isFunc) {
3337       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3338 
3339       // FIXME: It would be nicer if the keyword was ignored only for this
3340       // declarator. Otherwise we could get follow-up errors.
3341       D.getMutableDeclSpec().ClearStorageClassSpecs();
3342     }
3343     break;
3344   default:
3345     Diag(DS.getStorageClassSpecLoc(),
3346          diag::err_storageclass_invalid_for_member);
3347     D.getMutableDeclSpec().ClearStorageClassSpecs();
3348     break;
3349   }
3350 
3351   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3352                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3353                       !isFunc);
3354 
3355   if (DS.hasConstexprSpecifier() && isInstField) {
3356     SemaDiagnosticBuilder B =
3357         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3358     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3359     if (InitStyle == ICIS_NoInit) {
3360       B << 0 << 0;
3361       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3362         B << FixItHint::CreateRemoval(ConstexprLoc);
3363       else {
3364         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3365         D.getMutableDeclSpec().ClearConstexprSpec();
3366         const char *PrevSpec;
3367         unsigned DiagID;
3368         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3369             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3370         (void)Failed;
3371         assert(!Failed && "Making a constexpr member const shouldn't fail");
3372       }
3373     } else {
3374       B << 1;
3375       const char *PrevSpec;
3376       unsigned DiagID;
3377       if (D.getMutableDeclSpec().SetStorageClassSpec(
3378           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3379           Context.getPrintingPolicy())) {
3380         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3381                "This is the only DeclSpec that should fail to be applied");
3382         B << 1;
3383       } else {
3384         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3385         isInstField = false;
3386       }
3387     }
3388   }
3389 
3390   NamedDecl *Member;
3391   if (isInstField) {
3392     CXXScopeSpec &SS = D.getCXXScopeSpec();
3393 
3394     // Data members must have identifiers for names.
3395     if (!Name.isIdentifier()) {
3396       Diag(Loc, diag::err_bad_variable_name)
3397         << Name;
3398       return nullptr;
3399     }
3400 
3401     IdentifierInfo *II = Name.getAsIdentifierInfo();
3402 
3403     // Member field could not be with "template" keyword.
3404     // So TemplateParameterLists should be empty in this case.
3405     if (TemplateParameterLists.size()) {
3406       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3407       if (TemplateParams->size()) {
3408         // There is no such thing as a member field template.
3409         Diag(D.getIdentifierLoc(), diag::err_template_member)
3410             << II
3411             << SourceRange(TemplateParams->getTemplateLoc(),
3412                 TemplateParams->getRAngleLoc());
3413       } else {
3414         // There is an extraneous 'template<>' for this member.
3415         Diag(TemplateParams->getTemplateLoc(),
3416             diag::err_template_member_noparams)
3417             << II
3418             << SourceRange(TemplateParams->getTemplateLoc(),
3419                 TemplateParams->getRAngleLoc());
3420       }
3421       return nullptr;
3422     }
3423 
3424     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3425       Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3426           << II
3427           << SourceRange(D.getName().TemplateId->LAngleLoc,
3428                          D.getName().TemplateId->RAngleLoc)
3429           << D.getName().TemplateId->LAngleLoc;
3430       D.SetIdentifier(Name.getAsIdentifierInfo(), Loc);
3431     }
3432 
3433     if (SS.isSet() && !SS.isInvalid()) {
3434       // The user provided a superfluous scope specifier inside a class
3435       // definition:
3436       //
3437       // class X {
3438       //   int X::member;
3439       // };
3440       if (DeclContext *DC = computeDeclContext(SS, false))
3441         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3442                                      D.getName().getKind() ==
3443                                          UnqualifiedIdKind::IK_TemplateId);
3444       else
3445         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3446           << Name << SS.getRange();
3447 
3448       SS.clear();
3449     }
3450 
3451     if (MSPropertyAttr) {
3452       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3453                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3454       if (!Member)
3455         return nullptr;
3456       isInstField = false;
3457     } else {
3458       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3459                                 BitWidth, InitStyle, AS);
3460       if (!Member)
3461         return nullptr;
3462     }
3463 
3464     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3465   } else {
3466     Member = HandleDeclarator(S, D, TemplateParameterLists);
3467     if (!Member)
3468       return nullptr;
3469 
3470     // Non-instance-fields can't have a bitfield.
3471     if (BitWidth) {
3472       if (Member->isInvalidDecl()) {
3473         // don't emit another diagnostic.
3474       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3475         // C++ 9.6p3: A bit-field shall not be a static member.
3476         // "static member 'A' cannot be a bit-field"
3477         Diag(Loc, diag::err_static_not_bitfield)
3478           << Name << BitWidth->getSourceRange();
3479       } else if (isa<TypedefDecl>(Member)) {
3480         // "typedef member 'x' cannot be a bit-field"
3481         Diag(Loc, diag::err_typedef_not_bitfield)
3482           << Name << BitWidth->getSourceRange();
3483       } else {
3484         // A function typedef ("typedef int f(); f a;").
3485         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3486         Diag(Loc, diag::err_not_integral_type_bitfield)
3487           << Name << cast<ValueDecl>(Member)->getType()
3488           << BitWidth->getSourceRange();
3489       }
3490 
3491       BitWidth = nullptr;
3492       Member->setInvalidDecl();
3493     }
3494 
3495     NamedDecl *NonTemplateMember = Member;
3496     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3497       NonTemplateMember = FunTmpl->getTemplatedDecl();
3498     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3499       NonTemplateMember = VarTmpl->getTemplatedDecl();
3500 
3501     Member->setAccess(AS);
3502 
3503     // If we have declared a member function template or static data member
3504     // template, set the access of the templated declaration as well.
3505     if (NonTemplateMember != Member)
3506       NonTemplateMember->setAccess(AS);
3507 
3508     // C++ [temp.deduct.guide]p3:
3509     //   A deduction guide [...] for a member class template [shall be
3510     //   declared] with the same access [as the template].
3511     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3512       auto *TD = DG->getDeducedTemplate();
3513       // Access specifiers are only meaningful if both the template and the
3514       // deduction guide are from the same scope.
3515       if (AS != TD->getAccess() &&
3516           TD->getDeclContext()->getRedeclContext()->Equals(
3517               DG->getDeclContext()->getRedeclContext())) {
3518         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3519         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3520             << TD->getAccess();
3521         const AccessSpecDecl *LastAccessSpec = nullptr;
3522         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3523           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3524             LastAccessSpec = AccessSpec;
3525         }
3526         assert(LastAccessSpec && "differing access with no access specifier");
3527         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3528             << AS;
3529       }
3530     }
3531   }
3532 
3533   if (VS.isOverrideSpecified())
3534     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3535                                          AttributeCommonInfo::AS_Keyword));
3536   if (VS.isFinalSpecified())
3537     Member->addAttr(FinalAttr::Create(
3538         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3539         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3540 
3541   if (VS.getLastLocation().isValid()) {
3542     // Update the end location of a method that has a virt-specifiers.
3543     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3544       MD->setRangeEnd(VS.getLastLocation());
3545   }
3546 
3547   CheckOverrideControl(Member);
3548 
3549   assert((Name || isInstField) && "No identifier for non-field ?");
3550 
3551   if (isInstField) {
3552     FieldDecl *FD = cast<FieldDecl>(Member);
3553     FieldCollector->Add(FD);
3554 
3555     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3556       // Remember all explicit private FieldDecls that have a name, no side
3557       // effects and are not part of a dependent type declaration.
3558       if (!FD->isImplicit() && FD->getDeclName() &&
3559           FD->getAccess() == AS_private &&
3560           !FD->hasAttr<UnusedAttr>() &&
3561           !FD->getParent()->isDependentContext() &&
3562           !InitializationHasSideEffects(*FD))
3563         UnusedPrivateFields.insert(FD);
3564     }
3565   }
3566 
3567   return Member;
3568 }
3569 
3570 namespace {
3571   class UninitializedFieldVisitor
3572       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3573     Sema &S;
3574     // List of Decls to generate a warning on.  Also remove Decls that become
3575     // initialized.
3576     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3577     // List of base classes of the record.  Classes are removed after their
3578     // initializers.
3579     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3580     // Vector of decls to be removed from the Decl set prior to visiting the
3581     // nodes.  These Decls may have been initialized in the prior initializer.
3582     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3583     // If non-null, add a note to the warning pointing back to the constructor.
3584     const CXXConstructorDecl *Constructor;
3585     // Variables to hold state when processing an initializer list.  When
3586     // InitList is true, special case initialization of FieldDecls matching
3587     // InitListFieldDecl.
3588     bool InitList;
3589     FieldDecl *InitListFieldDecl;
3590     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3591 
3592   public:
3593     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3594     UninitializedFieldVisitor(Sema &S,
3595                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3596                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3597       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3598         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3599 
3600     // Returns true if the use of ME is not an uninitialized use.
3601     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3602                                          bool CheckReferenceOnly) {
3603       llvm::SmallVector<FieldDecl*, 4> Fields;
3604       bool ReferenceField = false;
3605       while (ME) {
3606         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3607         if (!FD)
3608           return false;
3609         Fields.push_back(FD);
3610         if (FD->getType()->isReferenceType())
3611           ReferenceField = true;
3612         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3613       }
3614 
3615       // Binding a reference to an uninitialized field is not an
3616       // uninitialized use.
3617       if (CheckReferenceOnly && !ReferenceField)
3618         return true;
3619 
3620       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3621       // Discard the first field since it is the field decl that is being
3622       // initialized.
3623       for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3624         UsedFieldIndex.push_back(FD->getFieldIndex());
3625 
3626       for (auto UsedIter = UsedFieldIndex.begin(),
3627                 UsedEnd = UsedFieldIndex.end(),
3628                 OrigIter = InitFieldIndex.begin(),
3629                 OrigEnd = InitFieldIndex.end();
3630            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3631         if (*UsedIter < *OrigIter)
3632           return true;
3633         if (*UsedIter > *OrigIter)
3634           break;
3635       }
3636 
3637       return false;
3638     }
3639 
3640     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3641                           bool AddressOf) {
3642       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3643         return;
3644 
3645       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3646       // or union.
3647       MemberExpr *FieldME = ME;
3648 
3649       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3650 
3651       Expr *Base = ME;
3652       while (MemberExpr *SubME =
3653                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3654 
3655         if (isa<VarDecl>(SubME->getMemberDecl()))
3656           return;
3657 
3658         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3659           if (!FD->isAnonymousStructOrUnion())
3660             FieldME = SubME;
3661 
3662         if (!FieldME->getType().isPODType(S.Context))
3663           AllPODFields = false;
3664 
3665         Base = SubME->getBase();
3666       }
3667 
3668       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3669         Visit(Base);
3670         return;
3671       }
3672 
3673       if (AddressOf && AllPODFields)
3674         return;
3675 
3676       ValueDecl* FoundVD = FieldME->getMemberDecl();
3677 
3678       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3679         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3680           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3681         }
3682 
3683         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3684           QualType T = BaseCast->getType();
3685           if (T->isPointerType() &&
3686               BaseClasses.count(T->getPointeeType())) {
3687             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3688                 << T->getPointeeType() << FoundVD;
3689           }
3690         }
3691       }
3692 
3693       if (!Decls.count(FoundVD))
3694         return;
3695 
3696       const bool IsReference = FoundVD->getType()->isReferenceType();
3697 
3698       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3699         // Special checking for initializer lists.
3700         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3701           return;
3702         }
3703       } else {
3704         // Prevent double warnings on use of unbounded references.
3705         if (CheckReferenceOnly && !IsReference)
3706           return;
3707       }
3708 
3709       unsigned diag = IsReference
3710           ? diag::warn_reference_field_is_uninit
3711           : diag::warn_field_is_uninit;
3712       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3713       if (Constructor)
3714         S.Diag(Constructor->getLocation(),
3715                diag::note_uninit_in_this_constructor)
3716           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3717 
3718     }
3719 
3720     void HandleValue(Expr *E, bool AddressOf) {
3721       E = E->IgnoreParens();
3722 
3723       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3724         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3725                          AddressOf /*AddressOf*/);
3726         return;
3727       }
3728 
3729       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3730         Visit(CO->getCond());
3731         HandleValue(CO->getTrueExpr(), AddressOf);
3732         HandleValue(CO->getFalseExpr(), AddressOf);
3733         return;
3734       }
3735 
3736       if (BinaryConditionalOperator *BCO =
3737               dyn_cast<BinaryConditionalOperator>(E)) {
3738         Visit(BCO->getCond());
3739         HandleValue(BCO->getFalseExpr(), AddressOf);
3740         return;
3741       }
3742 
3743       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3744         HandleValue(OVE->getSourceExpr(), AddressOf);
3745         return;
3746       }
3747 
3748       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3749         switch (BO->getOpcode()) {
3750         default:
3751           break;
3752         case(BO_PtrMemD):
3753         case(BO_PtrMemI):
3754           HandleValue(BO->getLHS(), AddressOf);
3755           Visit(BO->getRHS());
3756           return;
3757         case(BO_Comma):
3758           Visit(BO->getLHS());
3759           HandleValue(BO->getRHS(), AddressOf);
3760           return;
3761         }
3762       }
3763 
3764       Visit(E);
3765     }
3766 
3767     void CheckInitListExpr(InitListExpr *ILE) {
3768       InitFieldIndex.push_back(0);
3769       for (auto Child : ILE->children()) {
3770         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3771           CheckInitListExpr(SubList);
3772         } else {
3773           Visit(Child);
3774         }
3775         ++InitFieldIndex.back();
3776       }
3777       InitFieldIndex.pop_back();
3778     }
3779 
3780     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3781                           FieldDecl *Field, const Type *BaseClass) {
3782       // Remove Decls that may have been initialized in the previous
3783       // initializer.
3784       for (ValueDecl* VD : DeclsToRemove)
3785         Decls.erase(VD);
3786       DeclsToRemove.clear();
3787 
3788       Constructor = FieldConstructor;
3789       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3790 
3791       if (ILE && Field) {
3792         InitList = true;
3793         InitListFieldDecl = Field;
3794         InitFieldIndex.clear();
3795         CheckInitListExpr(ILE);
3796       } else {
3797         InitList = false;
3798         Visit(E);
3799       }
3800 
3801       if (Field)
3802         Decls.erase(Field);
3803       if (BaseClass)
3804         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3805     }
3806 
3807     void VisitMemberExpr(MemberExpr *ME) {
3808       // All uses of unbounded reference fields will warn.
3809       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3810     }
3811 
3812     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3813       if (E->getCastKind() == CK_LValueToRValue) {
3814         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3815         return;
3816       }
3817 
3818       Inherited::VisitImplicitCastExpr(E);
3819     }
3820 
3821     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3822       if (E->getConstructor()->isCopyConstructor()) {
3823         Expr *ArgExpr = E->getArg(0);
3824         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3825           if (ILE->getNumInits() == 1)
3826             ArgExpr = ILE->getInit(0);
3827         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3828           if (ICE->getCastKind() == CK_NoOp)
3829             ArgExpr = ICE->getSubExpr();
3830         HandleValue(ArgExpr, false /*AddressOf*/);
3831         return;
3832       }
3833       Inherited::VisitCXXConstructExpr(E);
3834     }
3835 
3836     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3837       Expr *Callee = E->getCallee();
3838       if (isa<MemberExpr>(Callee)) {
3839         HandleValue(Callee, false /*AddressOf*/);
3840         for (auto Arg : E->arguments())
3841           Visit(Arg);
3842         return;
3843       }
3844 
3845       Inherited::VisitCXXMemberCallExpr(E);
3846     }
3847 
3848     void VisitCallExpr(CallExpr *E) {
3849       // Treat std::move as a use.
3850       if (E->isCallToStdMove()) {
3851         HandleValue(E->getArg(0), /*AddressOf=*/false);
3852         return;
3853       }
3854 
3855       Inherited::VisitCallExpr(E);
3856     }
3857 
3858     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3859       Expr *Callee = E->getCallee();
3860 
3861       if (isa<UnresolvedLookupExpr>(Callee))
3862         return Inherited::VisitCXXOperatorCallExpr(E);
3863 
3864       Visit(Callee);
3865       for (auto Arg : E->arguments())
3866         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3867     }
3868 
3869     void VisitBinaryOperator(BinaryOperator *E) {
3870       // If a field assignment is detected, remove the field from the
3871       // uninitiailized field set.
3872       if (E->getOpcode() == BO_Assign)
3873         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3874           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3875             if (!FD->getType()->isReferenceType())
3876               DeclsToRemove.push_back(FD);
3877 
3878       if (E->isCompoundAssignmentOp()) {
3879         HandleValue(E->getLHS(), false /*AddressOf*/);
3880         Visit(E->getRHS());
3881         return;
3882       }
3883 
3884       Inherited::VisitBinaryOperator(E);
3885     }
3886 
3887     void VisitUnaryOperator(UnaryOperator *E) {
3888       if (E->isIncrementDecrementOp()) {
3889         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3890         return;
3891       }
3892       if (E->getOpcode() == UO_AddrOf) {
3893         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3894           HandleValue(ME->getBase(), true /*AddressOf*/);
3895           return;
3896         }
3897       }
3898 
3899       Inherited::VisitUnaryOperator(E);
3900     }
3901   };
3902 
3903   // Diagnose value-uses of fields to initialize themselves, e.g.
3904   //   foo(foo)
3905   // where foo is not also a parameter to the constructor.
3906   // Also diagnose across field uninitialized use such as
3907   //   x(y), y(x)
3908   // TODO: implement -Wuninitialized and fold this into that framework.
3909   static void DiagnoseUninitializedFields(
3910       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3911 
3912     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3913                                            Constructor->getLocation())) {
3914       return;
3915     }
3916 
3917     if (Constructor->isInvalidDecl())
3918       return;
3919 
3920     const CXXRecordDecl *RD = Constructor->getParent();
3921 
3922     if (RD->isDependentContext())
3923       return;
3924 
3925     // Holds fields that are uninitialized.
3926     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3927 
3928     // At the beginning, all fields are uninitialized.
3929     for (auto *I : RD->decls()) {
3930       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3931         UninitializedFields.insert(FD);
3932       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3933         UninitializedFields.insert(IFD->getAnonField());
3934       }
3935     }
3936 
3937     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3938     for (auto I : RD->bases())
3939       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3940 
3941     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3942       return;
3943 
3944     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3945                                                    UninitializedFields,
3946                                                    UninitializedBaseClasses);
3947 
3948     for (const auto *FieldInit : Constructor->inits()) {
3949       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3950         break;
3951 
3952       Expr *InitExpr = FieldInit->getInit();
3953       if (!InitExpr)
3954         continue;
3955 
3956       if (CXXDefaultInitExpr *Default =
3957               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3958         InitExpr = Default->getExpr();
3959         if (!InitExpr)
3960           continue;
3961         // In class initializers will point to the constructor.
3962         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3963                                               FieldInit->getAnyMember(),
3964                                               FieldInit->getBaseClass());
3965       } else {
3966         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3967                                               FieldInit->getAnyMember(),
3968                                               FieldInit->getBaseClass());
3969       }
3970     }
3971   }
3972 } // namespace
3973 
3974 /// Enter a new C++ default initializer scope. After calling this, the
3975 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3976 /// parsing or instantiating the initializer failed.
3977 void Sema::ActOnStartCXXInClassMemberInitializer() {
3978   // Create a synthetic function scope to represent the call to the constructor
3979   // that notionally surrounds a use of this initializer.
3980   PushFunctionScope();
3981 }
3982 
3983 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3984   if (!D.isFunctionDeclarator())
3985     return;
3986   auto &FTI = D.getFunctionTypeInfo();
3987   if (!FTI.Params)
3988     return;
3989   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3990                                                           FTI.NumParams)) {
3991     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3992     if (ParamDecl->getDeclName())
3993       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3994   }
3995 }
3996 
3997 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3998   return ActOnRequiresClause(ConstraintExpr);
3999 }
4000 
4001 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4002   if (ConstraintExpr.isInvalid())
4003     return ExprError();
4004 
4005   ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4006   if (ConstraintExpr.isInvalid())
4007     return ExprError();
4008 
4009   if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4010                                       UPPC_RequiresClause))
4011     return ExprError();
4012 
4013   return ConstraintExpr;
4014 }
4015 
4016 /// This is invoked after parsing an in-class initializer for a
4017 /// non-static C++ class member, and after instantiating an in-class initializer
4018 /// in a class template. Such actions are deferred until the class is complete.
4019 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4020                                                   SourceLocation InitLoc,
4021                                                   Expr *InitExpr) {
4022   // Pop the notional constructor scope we created earlier.
4023   PopFunctionScopeInfo(nullptr, D);
4024 
4025   FieldDecl *FD = dyn_cast<FieldDecl>(D);
4026   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4027          "must set init style when field is created");
4028 
4029   if (!InitExpr) {
4030     D->setInvalidDecl();
4031     if (FD)
4032       FD->removeInClassInitializer();
4033     return;
4034   }
4035 
4036   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4037     FD->setInvalidDecl();
4038     FD->removeInClassInitializer();
4039     return;
4040   }
4041 
4042   ExprResult Init = InitExpr;
4043   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
4044     InitializedEntity Entity =
4045         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4046     InitializationKind Kind =
4047         FD->getInClassInitStyle() == ICIS_ListInit
4048             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4049                                                    InitExpr->getBeginLoc(),
4050                                                    InitExpr->getEndLoc())
4051             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4052     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4053     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4054     if (Init.isInvalid()) {
4055       FD->setInvalidDecl();
4056       return;
4057     }
4058   }
4059 
4060   // C++11 [class.base.init]p7:
4061   //   The initialization of each base and member constitutes a
4062   //   full-expression.
4063   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4064   if (Init.isInvalid()) {
4065     FD->setInvalidDecl();
4066     return;
4067   }
4068 
4069   InitExpr = Init.get();
4070 
4071   FD->setInClassInitializer(InitExpr);
4072 }
4073 
4074 /// Find the direct and/or virtual base specifiers that
4075 /// correspond to the given base type, for use in base initialization
4076 /// within a constructor.
4077 static bool FindBaseInitializer(Sema &SemaRef,
4078                                 CXXRecordDecl *ClassDecl,
4079                                 QualType BaseType,
4080                                 const CXXBaseSpecifier *&DirectBaseSpec,
4081                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4082   // First, check for a direct base class.
4083   DirectBaseSpec = nullptr;
4084   for (const auto &Base : ClassDecl->bases()) {
4085     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4086       // We found a direct base of this type. That's what we're
4087       // initializing.
4088       DirectBaseSpec = &Base;
4089       break;
4090     }
4091   }
4092 
4093   // Check for a virtual base class.
4094   // FIXME: We might be able to short-circuit this if we know in advance that
4095   // there are no virtual bases.
4096   VirtualBaseSpec = nullptr;
4097   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4098     // We haven't found a base yet; search the class hierarchy for a
4099     // virtual base class.
4100     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4101                        /*DetectVirtual=*/false);
4102     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4103                               SemaRef.Context.getTypeDeclType(ClassDecl),
4104                               BaseType, Paths)) {
4105       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4106            Path != Paths.end(); ++Path) {
4107         if (Path->back().Base->isVirtual()) {
4108           VirtualBaseSpec = Path->back().Base;
4109           break;
4110         }
4111       }
4112     }
4113   }
4114 
4115   return DirectBaseSpec || VirtualBaseSpec;
4116 }
4117 
4118 /// Handle a C++ member initializer using braced-init-list syntax.
4119 MemInitResult
4120 Sema::ActOnMemInitializer(Decl *ConstructorD,
4121                           Scope *S,
4122                           CXXScopeSpec &SS,
4123                           IdentifierInfo *MemberOrBase,
4124                           ParsedType TemplateTypeTy,
4125                           const DeclSpec &DS,
4126                           SourceLocation IdLoc,
4127                           Expr *InitList,
4128                           SourceLocation EllipsisLoc) {
4129   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4130                              DS, IdLoc, InitList,
4131                              EllipsisLoc);
4132 }
4133 
4134 /// Handle a C++ member initializer using parentheses syntax.
4135 MemInitResult
4136 Sema::ActOnMemInitializer(Decl *ConstructorD,
4137                           Scope *S,
4138                           CXXScopeSpec &SS,
4139                           IdentifierInfo *MemberOrBase,
4140                           ParsedType TemplateTypeTy,
4141                           const DeclSpec &DS,
4142                           SourceLocation IdLoc,
4143                           SourceLocation LParenLoc,
4144                           ArrayRef<Expr *> Args,
4145                           SourceLocation RParenLoc,
4146                           SourceLocation EllipsisLoc) {
4147   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4148   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4149                              DS, IdLoc, List, EllipsisLoc);
4150 }
4151 
4152 namespace {
4153 
4154 // Callback to only accept typo corrections that can be a valid C++ member
4155 // initializer: either a non-static field member or a base class.
4156 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4157 public:
4158   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4159       : ClassDecl(ClassDecl) {}
4160 
4161   bool ValidateCandidate(const TypoCorrection &candidate) override {
4162     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4163       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4164         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4165       return isa<TypeDecl>(ND);
4166     }
4167     return false;
4168   }
4169 
4170   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4171     return std::make_unique<MemInitializerValidatorCCC>(*this);
4172   }
4173 
4174 private:
4175   CXXRecordDecl *ClassDecl;
4176 };
4177 
4178 }
4179 
4180 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4181                                              CXXScopeSpec &SS,
4182                                              ParsedType TemplateTypeTy,
4183                                              IdentifierInfo *MemberOrBase) {
4184   if (SS.getScopeRep() || TemplateTypeTy)
4185     return nullptr;
4186   for (auto *D : ClassDecl->lookup(MemberOrBase))
4187     if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4188       return cast<ValueDecl>(D);
4189   return nullptr;
4190 }
4191 
4192 /// Handle a C++ member initializer.
4193 MemInitResult
4194 Sema::BuildMemInitializer(Decl *ConstructorD,
4195                           Scope *S,
4196                           CXXScopeSpec &SS,
4197                           IdentifierInfo *MemberOrBase,
4198                           ParsedType TemplateTypeTy,
4199                           const DeclSpec &DS,
4200                           SourceLocation IdLoc,
4201                           Expr *Init,
4202                           SourceLocation EllipsisLoc) {
4203   ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4204                                              /*RecoverUncorrectedTypos=*/true);
4205   if (!Res.isUsable())
4206     return true;
4207   Init = Res.get();
4208 
4209   if (!ConstructorD)
4210     return true;
4211 
4212   AdjustDeclIfTemplate(ConstructorD);
4213 
4214   CXXConstructorDecl *Constructor
4215     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4216   if (!Constructor) {
4217     // The user wrote a constructor initializer on a function that is
4218     // not a C++ constructor. Ignore the error for now, because we may
4219     // have more member initializers coming; we'll diagnose it just
4220     // once in ActOnMemInitializers.
4221     return true;
4222   }
4223 
4224   CXXRecordDecl *ClassDecl = Constructor->getParent();
4225 
4226   // C++ [class.base.init]p2:
4227   //   Names in a mem-initializer-id are looked up in the scope of the
4228   //   constructor's class and, if not found in that scope, are looked
4229   //   up in the scope containing the constructor's definition.
4230   //   [Note: if the constructor's class contains a member with the
4231   //   same name as a direct or virtual base class of the class, a
4232   //   mem-initializer-id naming the member or base class and composed
4233   //   of a single identifier refers to the class member. A
4234   //   mem-initializer-id for the hidden base class may be specified
4235   //   using a qualified name. ]
4236 
4237   // Look for a member, first.
4238   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4239           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4240     if (EllipsisLoc.isValid())
4241       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4242           << MemberOrBase
4243           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4244 
4245     return BuildMemberInitializer(Member, Init, IdLoc);
4246   }
4247   // It didn't name a member, so see if it names a class.
4248   QualType BaseType;
4249   TypeSourceInfo *TInfo = nullptr;
4250 
4251   if (TemplateTypeTy) {
4252     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4253     if (BaseType.isNull())
4254       return true;
4255   } else if (DS.getTypeSpecType() == TST_decltype) {
4256     BaseType = BuildDecltypeType(DS.getRepAsExpr());
4257   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4258     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4259     return true;
4260   } else {
4261     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4262     LookupParsedName(R, S, &SS);
4263 
4264     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4265     if (!TyD) {
4266       if (R.isAmbiguous()) return true;
4267 
4268       // We don't want access-control diagnostics here.
4269       R.suppressDiagnostics();
4270 
4271       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4272         bool NotUnknownSpecialization = false;
4273         DeclContext *DC = computeDeclContext(SS, false);
4274         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4275           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4276 
4277         if (!NotUnknownSpecialization) {
4278           // When the scope specifier can refer to a member of an unknown
4279           // specialization, we take it as a type name.
4280           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4281                                        SS.getWithLocInContext(Context),
4282                                        *MemberOrBase, IdLoc);
4283           if (BaseType.isNull())
4284             return true;
4285 
4286           TInfo = Context.CreateTypeSourceInfo(BaseType);
4287           DependentNameTypeLoc TL =
4288               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4289           if (!TL.isNull()) {
4290             TL.setNameLoc(IdLoc);
4291             TL.setElaboratedKeywordLoc(SourceLocation());
4292             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4293           }
4294 
4295           R.clear();
4296           R.setLookupName(MemberOrBase);
4297         }
4298       }
4299 
4300       // If no results were found, try to correct typos.
4301       TypoCorrection Corr;
4302       MemInitializerValidatorCCC CCC(ClassDecl);
4303       if (R.empty() && BaseType.isNull() &&
4304           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4305                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4306         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4307           // We have found a non-static data member with a similar
4308           // name to what was typed; complain and initialize that
4309           // member.
4310           diagnoseTypo(Corr,
4311                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4312                          << MemberOrBase << true);
4313           return BuildMemberInitializer(Member, Init, IdLoc);
4314         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4315           const CXXBaseSpecifier *DirectBaseSpec;
4316           const CXXBaseSpecifier *VirtualBaseSpec;
4317           if (FindBaseInitializer(*this, ClassDecl,
4318                                   Context.getTypeDeclType(Type),
4319                                   DirectBaseSpec, VirtualBaseSpec)) {
4320             // We have found a direct or virtual base class with a
4321             // similar name to what was typed; complain and initialize
4322             // that base class.
4323             diagnoseTypo(Corr,
4324                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4325                            << MemberOrBase << false,
4326                          PDiag() /*Suppress note, we provide our own.*/);
4327 
4328             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4329                                                               : VirtualBaseSpec;
4330             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4331                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4332 
4333             TyD = Type;
4334           }
4335         }
4336       }
4337 
4338       if (!TyD && BaseType.isNull()) {
4339         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4340           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4341         return true;
4342       }
4343     }
4344 
4345     if (BaseType.isNull()) {
4346       BaseType = Context.getTypeDeclType(TyD);
4347       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4348       if (SS.isSet()) {
4349         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4350                                              BaseType);
4351         TInfo = Context.CreateTypeSourceInfo(BaseType);
4352         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4353         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4354         TL.setElaboratedKeywordLoc(SourceLocation());
4355         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4356       }
4357     }
4358   }
4359 
4360   if (!TInfo)
4361     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4362 
4363   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4364 }
4365 
4366 MemInitResult
4367 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4368                              SourceLocation IdLoc) {
4369   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4370   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4371   assert((DirectMember || IndirectMember) &&
4372          "Member must be a FieldDecl or IndirectFieldDecl");
4373 
4374   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4375     return true;
4376 
4377   if (Member->isInvalidDecl())
4378     return true;
4379 
4380   MultiExprArg Args;
4381   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4382     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4383   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4384     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4385   } else {
4386     // Template instantiation doesn't reconstruct ParenListExprs for us.
4387     Args = Init;
4388   }
4389 
4390   SourceRange InitRange = Init->getSourceRange();
4391 
4392   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4393     // Can't check initialization for a member of dependent type or when
4394     // any of the arguments are type-dependent expressions.
4395     DiscardCleanupsInEvaluationContext();
4396   } else {
4397     bool InitList = false;
4398     if (isa<InitListExpr>(Init)) {
4399       InitList = true;
4400       Args = Init;
4401     }
4402 
4403     // Initialize the member.
4404     InitializedEntity MemberEntity =
4405       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4406                    : InitializedEntity::InitializeMember(IndirectMember,
4407                                                          nullptr);
4408     InitializationKind Kind =
4409         InitList ? InitializationKind::CreateDirectList(
4410                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4411                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4412                                                     InitRange.getEnd());
4413 
4414     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4415     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4416                                             nullptr);
4417     if (!MemberInit.isInvalid()) {
4418       // C++11 [class.base.init]p7:
4419       //   The initialization of each base and member constitutes a
4420       //   full-expression.
4421       MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4422                                        /*DiscardedValue*/ false);
4423     }
4424 
4425     if (MemberInit.isInvalid()) {
4426       // Args were sensible expressions but we couldn't initialize the member
4427       // from them. Preserve them in a RecoveryExpr instead.
4428       Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4429                                 Member->getType())
4430                  .get();
4431       if (!Init)
4432         return true;
4433     } else {
4434       Init = MemberInit.get();
4435     }
4436   }
4437 
4438   if (DirectMember) {
4439     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4440                                             InitRange.getBegin(), Init,
4441                                             InitRange.getEnd());
4442   } else {
4443     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4444                                             InitRange.getBegin(), Init,
4445                                             InitRange.getEnd());
4446   }
4447 }
4448 
4449 MemInitResult
4450 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4451                                  CXXRecordDecl *ClassDecl) {
4452   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4453   if (!LangOpts.CPlusPlus11)
4454     return Diag(NameLoc, diag::err_delegating_ctor)
4455       << TInfo->getTypeLoc().getLocalSourceRange();
4456   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4457 
4458   bool InitList = true;
4459   MultiExprArg Args = Init;
4460   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4461     InitList = false;
4462     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4463   }
4464 
4465   SourceRange InitRange = Init->getSourceRange();
4466   // Initialize the object.
4467   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4468                                      QualType(ClassDecl->getTypeForDecl(), 0));
4469   InitializationKind Kind =
4470       InitList ? InitializationKind::CreateDirectList(
4471                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4472                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4473                                                   InitRange.getEnd());
4474   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4475   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4476                                               Args, nullptr);
4477   if (!DelegationInit.isInvalid()) {
4478     assert((DelegationInit.get()->containsErrors() ||
4479             cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4480            "Delegating constructor with no target?");
4481 
4482     // C++11 [class.base.init]p7:
4483     //   The initialization of each base and member constitutes a
4484     //   full-expression.
4485     DelegationInit = ActOnFinishFullExpr(
4486         DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4487   }
4488 
4489   if (DelegationInit.isInvalid()) {
4490     DelegationInit =
4491         CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4492                            QualType(ClassDecl->getTypeForDecl(), 0));
4493     if (DelegationInit.isInvalid())
4494       return true;
4495   } else {
4496     // If we are in a dependent context, template instantiation will
4497     // perform this type-checking again. Just save the arguments that we
4498     // received in a ParenListExpr.
4499     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4500     // of the information that we have about the base
4501     // initializer. However, deconstructing the ASTs is a dicey process,
4502     // and this approach is far more likely to get the corner cases right.
4503     if (CurContext->isDependentContext())
4504       DelegationInit = Init;
4505   }
4506 
4507   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4508                                           DelegationInit.getAs<Expr>(),
4509                                           InitRange.getEnd());
4510 }
4511 
4512 MemInitResult
4513 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4514                            Expr *Init, CXXRecordDecl *ClassDecl,
4515                            SourceLocation EllipsisLoc) {
4516   SourceLocation BaseLoc
4517     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4518 
4519   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4520     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4521              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4522 
4523   // C++ [class.base.init]p2:
4524   //   [...] Unless the mem-initializer-id names a nonstatic data
4525   //   member of the constructor's class or a direct or virtual base
4526   //   of that class, the mem-initializer is ill-formed. A
4527   //   mem-initializer-list can initialize a base class using any
4528   //   name that denotes that base class type.
4529 
4530   // We can store the initializers in "as-written" form and delay analysis until
4531   // instantiation if the constructor is dependent. But not for dependent
4532   // (broken) code in a non-template! SetCtorInitializers does not expect this.
4533   bool Dependent = CurContext->isDependentContext() &&
4534                    (BaseType->isDependentType() || Init->isTypeDependent());
4535 
4536   SourceRange InitRange = Init->getSourceRange();
4537   if (EllipsisLoc.isValid()) {
4538     // This is a pack expansion.
4539     if (!BaseType->containsUnexpandedParameterPack())  {
4540       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4541         << SourceRange(BaseLoc, InitRange.getEnd());
4542 
4543       EllipsisLoc = SourceLocation();
4544     }
4545   } else {
4546     // Check for any unexpanded parameter packs.
4547     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4548       return true;
4549 
4550     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4551       return true;
4552   }
4553 
4554   // Check for direct and virtual base classes.
4555   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4556   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4557   if (!Dependent) {
4558     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4559                                        BaseType))
4560       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4561 
4562     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4563                         VirtualBaseSpec);
4564 
4565     // C++ [base.class.init]p2:
4566     // Unless the mem-initializer-id names a nonstatic data member of the
4567     // constructor's class or a direct or virtual base of that class, the
4568     // mem-initializer is ill-formed.
4569     if (!DirectBaseSpec && !VirtualBaseSpec) {
4570       // If the class has any dependent bases, then it's possible that
4571       // one of those types will resolve to the same type as
4572       // BaseType. Therefore, just treat this as a dependent base
4573       // class initialization.  FIXME: Should we try to check the
4574       // initialization anyway? It seems odd.
4575       if (ClassDecl->hasAnyDependentBases())
4576         Dependent = true;
4577       else
4578         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4579           << BaseType << Context.getTypeDeclType(ClassDecl)
4580           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4581     }
4582   }
4583 
4584   if (Dependent) {
4585     DiscardCleanupsInEvaluationContext();
4586 
4587     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4588                                             /*IsVirtual=*/false,
4589                                             InitRange.getBegin(), Init,
4590                                             InitRange.getEnd(), EllipsisLoc);
4591   }
4592 
4593   // C++ [base.class.init]p2:
4594   //   If a mem-initializer-id is ambiguous because it designates both
4595   //   a direct non-virtual base class and an inherited virtual base
4596   //   class, the mem-initializer is ill-formed.
4597   if (DirectBaseSpec && VirtualBaseSpec)
4598     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4599       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4600 
4601   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4602   if (!BaseSpec)
4603     BaseSpec = VirtualBaseSpec;
4604 
4605   // Initialize the base.
4606   bool InitList = true;
4607   MultiExprArg Args = Init;
4608   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4609     InitList = false;
4610     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4611   }
4612 
4613   InitializedEntity BaseEntity =
4614     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4615   InitializationKind Kind =
4616       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4617                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4618                                                   InitRange.getEnd());
4619   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4620   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4621   if (!BaseInit.isInvalid()) {
4622     // C++11 [class.base.init]p7:
4623     //   The initialization of each base and member constitutes a
4624     //   full-expression.
4625     BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4626                                    /*DiscardedValue*/ false);
4627   }
4628 
4629   if (BaseInit.isInvalid()) {
4630     BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4631                                   Args, BaseType);
4632     if (BaseInit.isInvalid())
4633       return true;
4634   } else {
4635     // If we are in a dependent context, template instantiation will
4636     // perform this type-checking again. Just save the arguments that we
4637     // received in a ParenListExpr.
4638     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4639     // of the information that we have about the base
4640     // initializer. However, deconstructing the ASTs is a dicey process,
4641     // and this approach is far more likely to get the corner cases right.
4642     if (CurContext->isDependentContext())
4643       BaseInit = Init;
4644   }
4645 
4646   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4647                                           BaseSpec->isVirtual(),
4648                                           InitRange.getBegin(),
4649                                           BaseInit.getAs<Expr>(),
4650                                           InitRange.getEnd(), EllipsisLoc);
4651 }
4652 
4653 // Create a static_cast\<T&&>(expr).
4654 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4655   if (T.isNull()) T = E->getType();
4656   QualType TargetType = SemaRef.BuildReferenceType(
4657       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4658   SourceLocation ExprLoc = E->getBeginLoc();
4659   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4660       TargetType, ExprLoc);
4661 
4662   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4663                                    SourceRange(ExprLoc, ExprLoc),
4664                                    E->getSourceRange()).get();
4665 }
4666 
4667 /// ImplicitInitializerKind - How an implicit base or member initializer should
4668 /// initialize its base or member.
4669 enum ImplicitInitializerKind {
4670   IIK_Default,
4671   IIK_Copy,
4672   IIK_Move,
4673   IIK_Inherit
4674 };
4675 
4676 static bool
4677 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4678                              ImplicitInitializerKind ImplicitInitKind,
4679                              CXXBaseSpecifier *BaseSpec,
4680                              bool IsInheritedVirtualBase,
4681                              CXXCtorInitializer *&CXXBaseInit) {
4682   InitializedEntity InitEntity
4683     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4684                                         IsInheritedVirtualBase);
4685 
4686   ExprResult BaseInit;
4687 
4688   switch (ImplicitInitKind) {
4689   case IIK_Inherit:
4690   case IIK_Default: {
4691     InitializationKind InitKind
4692       = InitializationKind::CreateDefault(Constructor->getLocation());
4693     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4694     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4695     break;
4696   }
4697 
4698   case IIK_Move:
4699   case IIK_Copy: {
4700     bool Moving = ImplicitInitKind == IIK_Move;
4701     ParmVarDecl *Param = Constructor->getParamDecl(0);
4702     QualType ParamType = Param->getType().getNonReferenceType();
4703 
4704     Expr *CopyCtorArg =
4705       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4706                           SourceLocation(), Param, false,
4707                           Constructor->getLocation(), ParamType,
4708                           VK_LValue, nullptr);
4709 
4710     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4711 
4712     // Cast to the base class to avoid ambiguities.
4713     QualType ArgTy =
4714       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4715                                        ParamType.getQualifiers());
4716 
4717     if (Moving) {
4718       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4719     }
4720 
4721     CXXCastPath BasePath;
4722     BasePath.push_back(BaseSpec);
4723     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4724                                             CK_UncheckedDerivedToBase,
4725                                             Moving ? VK_XValue : VK_LValue,
4726                                             &BasePath).get();
4727 
4728     InitializationKind InitKind
4729       = InitializationKind::CreateDirect(Constructor->getLocation(),
4730                                          SourceLocation(), SourceLocation());
4731     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4732     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4733     break;
4734   }
4735   }
4736 
4737   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4738   if (BaseInit.isInvalid())
4739     return true;
4740 
4741   CXXBaseInit =
4742     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4743                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4744                                                         SourceLocation()),
4745                                              BaseSpec->isVirtual(),
4746                                              SourceLocation(),
4747                                              BaseInit.getAs<Expr>(),
4748                                              SourceLocation(),
4749                                              SourceLocation());
4750 
4751   return false;
4752 }
4753 
4754 static bool RefersToRValueRef(Expr *MemRef) {
4755   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4756   return Referenced->getType()->isRValueReferenceType();
4757 }
4758 
4759 static bool
4760 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4761                                ImplicitInitializerKind ImplicitInitKind,
4762                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4763                                CXXCtorInitializer *&CXXMemberInit) {
4764   if (Field->isInvalidDecl())
4765     return true;
4766 
4767   SourceLocation Loc = Constructor->getLocation();
4768 
4769   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4770     bool Moving = ImplicitInitKind == IIK_Move;
4771     ParmVarDecl *Param = Constructor->getParamDecl(0);
4772     QualType ParamType = Param->getType().getNonReferenceType();
4773 
4774     // Suppress copying zero-width bitfields.
4775     if (Field->isZeroLengthBitField(SemaRef.Context))
4776       return false;
4777 
4778     Expr *MemberExprBase =
4779       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4780                           SourceLocation(), Param, false,
4781                           Loc, ParamType, VK_LValue, nullptr);
4782 
4783     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4784 
4785     if (Moving) {
4786       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4787     }
4788 
4789     // Build a reference to this field within the parameter.
4790     CXXScopeSpec SS;
4791     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4792                               Sema::LookupMemberName);
4793     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4794                                   : cast<ValueDecl>(Field), AS_public);
4795     MemberLookup.resolveKind();
4796     ExprResult CtorArg
4797       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4798                                          ParamType, Loc,
4799                                          /*IsArrow=*/false,
4800                                          SS,
4801                                          /*TemplateKWLoc=*/SourceLocation(),
4802                                          /*FirstQualifierInScope=*/nullptr,
4803                                          MemberLookup,
4804                                          /*TemplateArgs=*/nullptr,
4805                                          /*S*/nullptr);
4806     if (CtorArg.isInvalid())
4807       return true;
4808 
4809     // C++11 [class.copy]p15:
4810     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4811     //     with static_cast<T&&>(x.m);
4812     if (RefersToRValueRef(CtorArg.get())) {
4813       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4814     }
4815 
4816     InitializedEntity Entity =
4817         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4818                                                        /*Implicit*/ true)
4819                  : InitializedEntity::InitializeMember(Field, nullptr,
4820                                                        /*Implicit*/ true);
4821 
4822     // Direct-initialize to use the copy constructor.
4823     InitializationKind InitKind =
4824       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4825 
4826     Expr *CtorArgE = CtorArg.getAs<Expr>();
4827     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4828     ExprResult MemberInit =
4829         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4830     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4831     if (MemberInit.isInvalid())
4832       return true;
4833 
4834     if (Indirect)
4835       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4836           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4837     else
4838       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4839           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4840     return false;
4841   }
4842 
4843   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4844          "Unhandled implicit init kind!");
4845 
4846   QualType FieldBaseElementType =
4847     SemaRef.Context.getBaseElementType(Field->getType());
4848 
4849   if (FieldBaseElementType->isRecordType()) {
4850     InitializedEntity InitEntity =
4851         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4852                                                        /*Implicit*/ true)
4853                  : InitializedEntity::InitializeMember(Field, nullptr,
4854                                                        /*Implicit*/ true);
4855     InitializationKind InitKind =
4856       InitializationKind::CreateDefault(Loc);
4857 
4858     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4859     ExprResult MemberInit =
4860       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4861 
4862     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4863     if (MemberInit.isInvalid())
4864       return true;
4865 
4866     if (Indirect)
4867       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4868                                                                Indirect, Loc,
4869                                                                Loc,
4870                                                                MemberInit.get(),
4871                                                                Loc);
4872     else
4873       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4874                                                                Field, Loc, Loc,
4875                                                                MemberInit.get(),
4876                                                                Loc);
4877     return false;
4878   }
4879 
4880   if (!Field->getParent()->isUnion()) {
4881     if (FieldBaseElementType->isReferenceType()) {
4882       SemaRef.Diag(Constructor->getLocation(),
4883                    diag::err_uninitialized_member_in_ctor)
4884       << (int)Constructor->isImplicit()
4885       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4886       << 0 << Field->getDeclName();
4887       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4888       return true;
4889     }
4890 
4891     if (FieldBaseElementType.isConstQualified()) {
4892       SemaRef.Diag(Constructor->getLocation(),
4893                    diag::err_uninitialized_member_in_ctor)
4894       << (int)Constructor->isImplicit()
4895       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4896       << 1 << Field->getDeclName();
4897       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4898       return true;
4899     }
4900   }
4901 
4902   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4903     // ARC and Weak:
4904     //   Default-initialize Objective-C pointers to NULL.
4905     CXXMemberInit
4906       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4907                                                  Loc, Loc,
4908                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4909                                                  Loc);
4910     return false;
4911   }
4912 
4913   // Nothing to initialize.
4914   CXXMemberInit = nullptr;
4915   return false;
4916 }
4917 
4918 namespace {
4919 struct BaseAndFieldInfo {
4920   Sema &S;
4921   CXXConstructorDecl *Ctor;
4922   bool AnyErrorsInInits;
4923   ImplicitInitializerKind IIK;
4924   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4925   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4926   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4927 
4928   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4929     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4930     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4931     if (Ctor->getInheritedConstructor())
4932       IIK = IIK_Inherit;
4933     else if (Generated && Ctor->isCopyConstructor())
4934       IIK = IIK_Copy;
4935     else if (Generated && Ctor->isMoveConstructor())
4936       IIK = IIK_Move;
4937     else
4938       IIK = IIK_Default;
4939   }
4940 
4941   bool isImplicitCopyOrMove() const {
4942     switch (IIK) {
4943     case IIK_Copy:
4944     case IIK_Move:
4945       return true;
4946 
4947     case IIK_Default:
4948     case IIK_Inherit:
4949       return false;
4950     }
4951 
4952     llvm_unreachable("Invalid ImplicitInitializerKind!");
4953   }
4954 
4955   bool addFieldInitializer(CXXCtorInitializer *Init) {
4956     AllToInit.push_back(Init);
4957 
4958     // Check whether this initializer makes the field "used".
4959     if (Init->getInit()->HasSideEffects(S.Context))
4960       S.UnusedPrivateFields.remove(Init->getAnyMember());
4961 
4962     return false;
4963   }
4964 
4965   bool isInactiveUnionMember(FieldDecl *Field) {
4966     RecordDecl *Record = Field->getParent();
4967     if (!Record->isUnion())
4968       return false;
4969 
4970     if (FieldDecl *Active =
4971             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4972       return Active != Field->getCanonicalDecl();
4973 
4974     // In an implicit copy or move constructor, ignore any in-class initializer.
4975     if (isImplicitCopyOrMove())
4976       return true;
4977 
4978     // If there's no explicit initialization, the field is active only if it
4979     // has an in-class initializer...
4980     if (Field->hasInClassInitializer())
4981       return false;
4982     // ... or it's an anonymous struct or union whose class has an in-class
4983     // initializer.
4984     if (!Field->isAnonymousStructOrUnion())
4985       return true;
4986     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4987     return !FieldRD->hasInClassInitializer();
4988   }
4989 
4990   /// Determine whether the given field is, or is within, a union member
4991   /// that is inactive (because there was an initializer given for a different
4992   /// member of the union, or because the union was not initialized at all).
4993   bool isWithinInactiveUnionMember(FieldDecl *Field,
4994                                    IndirectFieldDecl *Indirect) {
4995     if (!Indirect)
4996       return isInactiveUnionMember(Field);
4997 
4998     for (auto *C : Indirect->chain()) {
4999       FieldDecl *Field = dyn_cast<FieldDecl>(C);
5000       if (Field && isInactiveUnionMember(Field))
5001         return true;
5002     }
5003     return false;
5004   }
5005 };
5006 }
5007 
5008 /// Determine whether the given type is an incomplete or zero-lenfgth
5009 /// array type.
5010 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5011   if (T->isIncompleteArrayType())
5012     return true;
5013 
5014   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5015     if (!ArrayT->getSize())
5016       return true;
5017 
5018     T = ArrayT->getElementType();
5019   }
5020 
5021   return false;
5022 }
5023 
5024 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5025                                     FieldDecl *Field,
5026                                     IndirectFieldDecl *Indirect = nullptr) {
5027   if (Field->isInvalidDecl())
5028     return false;
5029 
5030   // Overwhelmingly common case: we have a direct initializer for this field.
5031   if (CXXCtorInitializer *Init =
5032           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5033     return Info.addFieldInitializer(Init);
5034 
5035   // C++11 [class.base.init]p8:
5036   //   if the entity is a non-static data member that has a
5037   //   brace-or-equal-initializer and either
5038   //   -- the constructor's class is a union and no other variant member of that
5039   //      union is designated by a mem-initializer-id or
5040   //   -- the constructor's class is not a union, and, if the entity is a member
5041   //      of an anonymous union, no other member of that union is designated by
5042   //      a mem-initializer-id,
5043   //   the entity is initialized as specified in [dcl.init].
5044   //
5045   // We also apply the same rules to handle anonymous structs within anonymous
5046   // unions.
5047   if (Info.isWithinInactiveUnionMember(Field, Indirect))
5048     return false;
5049 
5050   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5051     ExprResult DIE =
5052         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5053     if (DIE.isInvalid())
5054       return true;
5055 
5056     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5057     SemaRef.checkInitializerLifetime(Entity, DIE.get());
5058 
5059     CXXCtorInitializer *Init;
5060     if (Indirect)
5061       Init = new (SemaRef.Context)
5062           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5063                              SourceLocation(), DIE.get(), SourceLocation());
5064     else
5065       Init = new (SemaRef.Context)
5066           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5067                              SourceLocation(), DIE.get(), SourceLocation());
5068     return Info.addFieldInitializer(Init);
5069   }
5070 
5071   // Don't initialize incomplete or zero-length arrays.
5072   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5073     return false;
5074 
5075   // Don't try to build an implicit initializer if there were semantic
5076   // errors in any of the initializers (and therefore we might be
5077   // missing some that the user actually wrote).
5078   if (Info.AnyErrorsInInits)
5079     return false;
5080 
5081   CXXCtorInitializer *Init = nullptr;
5082   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5083                                      Indirect, Init))
5084     return true;
5085 
5086   if (!Init)
5087     return false;
5088 
5089   return Info.addFieldInitializer(Init);
5090 }
5091 
5092 bool
5093 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5094                                CXXCtorInitializer *Initializer) {
5095   assert(Initializer->isDelegatingInitializer());
5096   Constructor->setNumCtorInitializers(1);
5097   CXXCtorInitializer **initializer =
5098     new (Context) CXXCtorInitializer*[1];
5099   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5100   Constructor->setCtorInitializers(initializer);
5101 
5102   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5103     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5104     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5105   }
5106 
5107   DelegatingCtorDecls.push_back(Constructor);
5108 
5109   DiagnoseUninitializedFields(*this, Constructor);
5110 
5111   return false;
5112 }
5113 
5114 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5115                                ArrayRef<CXXCtorInitializer *> Initializers) {
5116   if (Constructor->isDependentContext()) {
5117     // Just store the initializers as written, they will be checked during
5118     // instantiation.
5119     if (!Initializers.empty()) {
5120       Constructor->setNumCtorInitializers(Initializers.size());
5121       CXXCtorInitializer **baseOrMemberInitializers =
5122         new (Context) CXXCtorInitializer*[Initializers.size()];
5123       memcpy(baseOrMemberInitializers, Initializers.data(),
5124              Initializers.size() * sizeof(CXXCtorInitializer*));
5125       Constructor->setCtorInitializers(baseOrMemberInitializers);
5126     }
5127 
5128     // Let template instantiation know whether we had errors.
5129     if (AnyErrors)
5130       Constructor->setInvalidDecl();
5131 
5132     return false;
5133   }
5134 
5135   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5136 
5137   // We need to build the initializer AST according to order of construction
5138   // and not what user specified in the Initializers list.
5139   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5140   if (!ClassDecl)
5141     return true;
5142 
5143   bool HadError = false;
5144 
5145   for (unsigned i = 0; i < Initializers.size(); i++) {
5146     CXXCtorInitializer *Member = Initializers[i];
5147 
5148     if (Member->isBaseInitializer())
5149       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5150     else {
5151       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5152 
5153       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5154         for (auto *C : F->chain()) {
5155           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5156           if (FD && FD->getParent()->isUnion())
5157             Info.ActiveUnionMember.insert(std::make_pair(
5158                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5159         }
5160       } else if (FieldDecl *FD = Member->getMember()) {
5161         if (FD->getParent()->isUnion())
5162           Info.ActiveUnionMember.insert(std::make_pair(
5163               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5164       }
5165     }
5166   }
5167 
5168   // Keep track of the direct virtual bases.
5169   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5170   for (auto &I : ClassDecl->bases()) {
5171     if (I.isVirtual())
5172       DirectVBases.insert(&I);
5173   }
5174 
5175   // Push virtual bases before others.
5176   for (auto &VBase : ClassDecl->vbases()) {
5177     if (CXXCtorInitializer *Value
5178         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5179       // [class.base.init]p7, per DR257:
5180       //   A mem-initializer where the mem-initializer-id names a virtual base
5181       //   class is ignored during execution of a constructor of any class that
5182       //   is not the most derived class.
5183       if (ClassDecl->isAbstract()) {
5184         // FIXME: Provide a fixit to remove the base specifier. This requires
5185         // tracking the location of the associated comma for a base specifier.
5186         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5187           << VBase.getType() << ClassDecl;
5188         DiagnoseAbstractType(ClassDecl);
5189       }
5190 
5191       Info.AllToInit.push_back(Value);
5192     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5193       // [class.base.init]p8, per DR257:
5194       //   If a given [...] base class is not named by a mem-initializer-id
5195       //   [...] and the entity is not a virtual base class of an abstract
5196       //   class, then [...] the entity is default-initialized.
5197       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5198       CXXCtorInitializer *CXXBaseInit;
5199       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5200                                        &VBase, IsInheritedVirtualBase,
5201                                        CXXBaseInit)) {
5202         HadError = true;
5203         continue;
5204       }
5205 
5206       Info.AllToInit.push_back(CXXBaseInit);
5207     }
5208   }
5209 
5210   // Non-virtual bases.
5211   for (auto &Base : ClassDecl->bases()) {
5212     // Virtuals are in the virtual base list and already constructed.
5213     if (Base.isVirtual())
5214       continue;
5215 
5216     if (CXXCtorInitializer *Value
5217           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5218       Info.AllToInit.push_back(Value);
5219     } else if (!AnyErrors) {
5220       CXXCtorInitializer *CXXBaseInit;
5221       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5222                                        &Base, /*IsInheritedVirtualBase=*/false,
5223                                        CXXBaseInit)) {
5224         HadError = true;
5225         continue;
5226       }
5227 
5228       Info.AllToInit.push_back(CXXBaseInit);
5229     }
5230   }
5231 
5232   // Fields.
5233   for (auto *Mem : ClassDecl->decls()) {
5234     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5235       // C++ [class.bit]p2:
5236       //   A declaration for a bit-field that omits the identifier declares an
5237       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5238       //   initialized.
5239       if (F->isUnnamedBitfield())
5240         continue;
5241 
5242       // If we're not generating the implicit copy/move constructor, then we'll
5243       // handle anonymous struct/union fields based on their individual
5244       // indirect fields.
5245       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5246         continue;
5247 
5248       if (CollectFieldInitializer(*this, Info, F))
5249         HadError = true;
5250       continue;
5251     }
5252 
5253     // Beyond this point, we only consider default initialization.
5254     if (Info.isImplicitCopyOrMove())
5255       continue;
5256 
5257     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5258       if (F->getType()->isIncompleteArrayType()) {
5259         assert(ClassDecl->hasFlexibleArrayMember() &&
5260                "Incomplete array type is not valid");
5261         continue;
5262       }
5263 
5264       // Initialize each field of an anonymous struct individually.
5265       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5266         HadError = true;
5267 
5268       continue;
5269     }
5270   }
5271 
5272   unsigned NumInitializers = Info.AllToInit.size();
5273   if (NumInitializers > 0) {
5274     Constructor->setNumCtorInitializers(NumInitializers);
5275     CXXCtorInitializer **baseOrMemberInitializers =
5276       new (Context) CXXCtorInitializer*[NumInitializers];
5277     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5278            NumInitializers * sizeof(CXXCtorInitializer*));
5279     Constructor->setCtorInitializers(baseOrMemberInitializers);
5280 
5281     // Constructors implicitly reference the base and member
5282     // destructors.
5283     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5284                                            Constructor->getParent());
5285   }
5286 
5287   return HadError;
5288 }
5289 
5290 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5291   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5292     const RecordDecl *RD = RT->getDecl();
5293     if (RD->isAnonymousStructOrUnion()) {
5294       for (auto *Field : RD->fields())
5295         PopulateKeysForFields(Field, IdealInits);
5296       return;
5297     }
5298   }
5299   IdealInits.push_back(Field->getCanonicalDecl());
5300 }
5301 
5302 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5303   return Context.getCanonicalType(BaseType).getTypePtr();
5304 }
5305 
5306 static const void *GetKeyForMember(ASTContext &Context,
5307                                    CXXCtorInitializer *Member) {
5308   if (!Member->isAnyMemberInitializer())
5309     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5310 
5311   return Member->getAnyMember()->getCanonicalDecl();
5312 }
5313 
5314 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5315                                  const CXXCtorInitializer *Previous,
5316                                  const CXXCtorInitializer *Current) {
5317   if (Previous->isAnyMemberInitializer())
5318     Diag << 0 << Previous->getAnyMember();
5319   else
5320     Diag << 1 << Previous->getTypeSourceInfo()->getType();
5321 
5322   if (Current->isAnyMemberInitializer())
5323     Diag << 0 << Current->getAnyMember();
5324   else
5325     Diag << 1 << Current->getTypeSourceInfo()->getType();
5326 }
5327 
5328 static void DiagnoseBaseOrMemInitializerOrder(
5329     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5330     ArrayRef<CXXCtorInitializer *> Inits) {
5331   if (Constructor->getDeclContext()->isDependentContext())
5332     return;
5333 
5334   // Don't check initializers order unless the warning is enabled at the
5335   // location of at least one initializer.
5336   bool ShouldCheckOrder = false;
5337   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5338     CXXCtorInitializer *Init = Inits[InitIndex];
5339     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5340                                  Init->getSourceLocation())) {
5341       ShouldCheckOrder = true;
5342       break;
5343     }
5344   }
5345   if (!ShouldCheckOrder)
5346     return;
5347 
5348   // Build the list of bases and members in the order that they'll
5349   // actually be initialized.  The explicit initializers should be in
5350   // this same order but may be missing things.
5351   SmallVector<const void*, 32> IdealInitKeys;
5352 
5353   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5354 
5355   // 1. Virtual bases.
5356   for (const auto &VBase : ClassDecl->vbases())
5357     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5358 
5359   // 2. Non-virtual bases.
5360   for (const auto &Base : ClassDecl->bases()) {
5361     if (Base.isVirtual())
5362       continue;
5363     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5364   }
5365 
5366   // 3. Direct fields.
5367   for (auto *Field : ClassDecl->fields()) {
5368     if (Field->isUnnamedBitfield())
5369       continue;
5370 
5371     PopulateKeysForFields(Field, IdealInitKeys);
5372   }
5373 
5374   unsigned NumIdealInits = IdealInitKeys.size();
5375   unsigned IdealIndex = 0;
5376 
5377   // Track initializers that are in an incorrect order for either a warning or
5378   // note if multiple ones occur.
5379   SmallVector<unsigned> WarnIndexes;
5380   // Correlates the index of an initializer in the init-list to the index of
5381   // the field/base in the class.
5382   SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5383 
5384   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5385     const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5386 
5387     // Scan forward to try to find this initializer in the idealized
5388     // initializers list.
5389     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5390       if (InitKey == IdealInitKeys[IdealIndex])
5391         break;
5392 
5393     // If we didn't find this initializer, it must be because we
5394     // scanned past it on a previous iteration.  That can only
5395     // happen if we're out of order;  emit a warning.
5396     if (IdealIndex == NumIdealInits && InitIndex) {
5397       WarnIndexes.push_back(InitIndex);
5398 
5399       // Move back to the initializer's location in the ideal list.
5400       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5401         if (InitKey == IdealInitKeys[IdealIndex])
5402           break;
5403 
5404       assert(IdealIndex < NumIdealInits &&
5405              "initializer not found in initializer list");
5406     }
5407     CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5408   }
5409 
5410   if (WarnIndexes.empty())
5411     return;
5412 
5413   // Sort based on the ideal order, first in the pair.
5414   llvm::sort(CorrelatedInitOrder,
5415              [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; });
5416 
5417   // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5418   // emit the diagnostic before we can try adding notes.
5419   {
5420     Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5421         Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5422         WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5423                                 : diag::warn_some_initializers_out_of_order);
5424 
5425     for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5426       if (CorrelatedInitOrder[I].second == I)
5427         continue;
5428       // Ideally we would be using InsertFromRange here, but clang doesn't
5429       // appear to handle InsertFromRange correctly when the source range is
5430       // modified by another fix-it.
5431       D << FixItHint::CreateReplacement(
5432           Inits[I]->getSourceRange(),
5433           Lexer::getSourceText(
5434               CharSourceRange::getTokenRange(
5435                   Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5436               SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5437     }
5438 
5439     // If there is only 1 item out of order, the warning expects the name and
5440     // type of each being added to it.
5441     if (WarnIndexes.size() == 1) {
5442       AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5443                            Inits[WarnIndexes.front()]);
5444       return;
5445     }
5446   }
5447   // More than 1 item to warn, create notes letting the user know which ones
5448   // are bad.
5449   for (unsigned WarnIndex : WarnIndexes) {
5450     const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5451     auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5452                           diag::note_initializer_out_of_order);
5453     AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5454     D << PrevInit->getSourceRange();
5455   }
5456 }
5457 
5458 namespace {
5459 bool CheckRedundantInit(Sema &S,
5460                         CXXCtorInitializer *Init,
5461                         CXXCtorInitializer *&PrevInit) {
5462   if (!PrevInit) {
5463     PrevInit = Init;
5464     return false;
5465   }
5466 
5467   if (FieldDecl *Field = Init->getAnyMember())
5468     S.Diag(Init->getSourceLocation(),
5469            diag::err_multiple_mem_initialization)
5470       << Field->getDeclName()
5471       << Init->getSourceRange();
5472   else {
5473     const Type *BaseClass = Init->getBaseClass();
5474     assert(BaseClass && "neither field nor base");
5475     S.Diag(Init->getSourceLocation(),
5476            diag::err_multiple_base_initialization)
5477       << QualType(BaseClass, 0)
5478       << Init->getSourceRange();
5479   }
5480   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5481     << 0 << PrevInit->getSourceRange();
5482 
5483   return true;
5484 }
5485 
5486 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5487 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5488 
5489 bool CheckRedundantUnionInit(Sema &S,
5490                              CXXCtorInitializer *Init,
5491                              RedundantUnionMap &Unions) {
5492   FieldDecl *Field = Init->getAnyMember();
5493   RecordDecl *Parent = Field->getParent();
5494   NamedDecl *Child = Field;
5495 
5496   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5497     if (Parent->isUnion()) {
5498       UnionEntry &En = Unions[Parent];
5499       if (En.first && En.first != Child) {
5500         S.Diag(Init->getSourceLocation(),
5501                diag::err_multiple_mem_union_initialization)
5502           << Field->getDeclName()
5503           << Init->getSourceRange();
5504         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5505           << 0 << En.second->getSourceRange();
5506         return true;
5507       }
5508       if (!En.first) {
5509         En.first = Child;
5510         En.second = Init;
5511       }
5512       if (!Parent->isAnonymousStructOrUnion())
5513         return false;
5514     }
5515 
5516     Child = Parent;
5517     Parent = cast<RecordDecl>(Parent->getDeclContext());
5518   }
5519 
5520   return false;
5521 }
5522 } // namespace
5523 
5524 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5525 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5526                                 SourceLocation ColonLoc,
5527                                 ArrayRef<CXXCtorInitializer*> MemInits,
5528                                 bool AnyErrors) {
5529   if (!ConstructorDecl)
5530     return;
5531 
5532   AdjustDeclIfTemplate(ConstructorDecl);
5533 
5534   CXXConstructorDecl *Constructor
5535     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5536 
5537   if (!Constructor) {
5538     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5539     return;
5540   }
5541 
5542   // Mapping for the duplicate initializers check.
5543   // For member initializers, this is keyed with a FieldDecl*.
5544   // For base initializers, this is keyed with a Type*.
5545   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5546 
5547   // Mapping for the inconsistent anonymous-union initializers check.
5548   RedundantUnionMap MemberUnions;
5549 
5550   bool HadError = false;
5551   for (unsigned i = 0; i < MemInits.size(); i++) {
5552     CXXCtorInitializer *Init = MemInits[i];
5553 
5554     // Set the source order index.
5555     Init->setSourceOrder(i);
5556 
5557     if (Init->isAnyMemberInitializer()) {
5558       const void *Key = GetKeyForMember(Context, Init);
5559       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5560           CheckRedundantUnionInit(*this, Init, MemberUnions))
5561         HadError = true;
5562     } else if (Init->isBaseInitializer()) {
5563       const void *Key = GetKeyForMember(Context, Init);
5564       if (CheckRedundantInit(*this, Init, Members[Key]))
5565         HadError = true;
5566     } else {
5567       assert(Init->isDelegatingInitializer());
5568       // This must be the only initializer
5569       if (MemInits.size() != 1) {
5570         Diag(Init->getSourceLocation(),
5571              diag::err_delegating_initializer_alone)
5572           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5573         // We will treat this as being the only initializer.
5574       }
5575       SetDelegatingInitializer(Constructor, MemInits[i]);
5576       // Return immediately as the initializer is set.
5577       return;
5578     }
5579   }
5580 
5581   if (HadError)
5582     return;
5583 
5584   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5585 
5586   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5587 
5588   DiagnoseUninitializedFields(*this, Constructor);
5589 }
5590 
5591 void
5592 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5593                                              CXXRecordDecl *ClassDecl) {
5594   // Ignore dependent contexts. Also ignore unions, since their members never
5595   // have destructors implicitly called.
5596   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5597     return;
5598 
5599   // FIXME: all the access-control diagnostics are positioned on the
5600   // field/base declaration.  That's probably good; that said, the
5601   // user might reasonably want to know why the destructor is being
5602   // emitted, and we currently don't say.
5603 
5604   // Non-static data members.
5605   for (auto *Field : ClassDecl->fields()) {
5606     if (Field->isInvalidDecl())
5607       continue;
5608 
5609     // Don't destroy incomplete or zero-length arrays.
5610     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5611       continue;
5612 
5613     QualType FieldType = Context.getBaseElementType(Field->getType());
5614 
5615     const RecordType* RT = FieldType->getAs<RecordType>();
5616     if (!RT)
5617       continue;
5618 
5619     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5620     if (FieldClassDecl->isInvalidDecl())
5621       continue;
5622     if (FieldClassDecl->hasIrrelevantDestructor())
5623       continue;
5624     // The destructor for an implicit anonymous union member is never invoked.
5625     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5626       continue;
5627 
5628     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5629     assert(Dtor && "No dtor found for FieldClassDecl!");
5630     CheckDestructorAccess(Field->getLocation(), Dtor,
5631                           PDiag(diag::err_access_dtor_field)
5632                             << Field->getDeclName()
5633                             << FieldType);
5634 
5635     MarkFunctionReferenced(Location, Dtor);
5636     DiagnoseUseOfDecl(Dtor, Location);
5637   }
5638 
5639   // We only potentially invoke the destructors of potentially constructed
5640   // subobjects.
5641   bool VisitVirtualBases = !ClassDecl->isAbstract();
5642 
5643   // If the destructor exists and has already been marked used in the MS ABI,
5644   // then virtual base destructors have already been checked and marked used.
5645   // Skip checking them again to avoid duplicate diagnostics.
5646   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5647     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5648     if (Dtor && Dtor->isUsed())
5649       VisitVirtualBases = false;
5650   }
5651 
5652   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5653 
5654   // Bases.
5655   for (const auto &Base : ClassDecl->bases()) {
5656     const RecordType *RT = Base.getType()->getAs<RecordType>();
5657     if (!RT)
5658       continue;
5659 
5660     // Remember direct virtual bases.
5661     if (Base.isVirtual()) {
5662       if (!VisitVirtualBases)
5663         continue;
5664       DirectVirtualBases.insert(RT);
5665     }
5666 
5667     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5668     // If our base class is invalid, we probably can't get its dtor anyway.
5669     if (BaseClassDecl->isInvalidDecl())
5670       continue;
5671     if (BaseClassDecl->hasIrrelevantDestructor())
5672       continue;
5673 
5674     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5675     assert(Dtor && "No dtor found for BaseClassDecl!");
5676 
5677     // FIXME: caret should be on the start of the class name
5678     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5679                           PDiag(diag::err_access_dtor_base)
5680                               << Base.getType() << Base.getSourceRange(),
5681                           Context.getTypeDeclType(ClassDecl));
5682 
5683     MarkFunctionReferenced(Location, Dtor);
5684     DiagnoseUseOfDecl(Dtor, Location);
5685   }
5686 
5687   if (VisitVirtualBases)
5688     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5689                                          &DirectVirtualBases);
5690 }
5691 
5692 void Sema::MarkVirtualBaseDestructorsReferenced(
5693     SourceLocation Location, CXXRecordDecl *ClassDecl,
5694     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5695   // Virtual bases.
5696   for (const auto &VBase : ClassDecl->vbases()) {
5697     // Bases are always records in a well-formed non-dependent class.
5698     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5699 
5700     // Ignore already visited direct virtual bases.
5701     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5702       continue;
5703 
5704     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5705     // If our base class is invalid, we probably can't get its dtor anyway.
5706     if (BaseClassDecl->isInvalidDecl())
5707       continue;
5708     if (BaseClassDecl->hasIrrelevantDestructor())
5709       continue;
5710 
5711     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5712     assert(Dtor && "No dtor found for BaseClassDecl!");
5713     if (CheckDestructorAccess(
5714             ClassDecl->getLocation(), Dtor,
5715             PDiag(diag::err_access_dtor_vbase)
5716                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5717             Context.getTypeDeclType(ClassDecl)) ==
5718         AR_accessible) {
5719       CheckDerivedToBaseConversion(
5720           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5721           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5722           SourceRange(), DeclarationName(), nullptr);
5723     }
5724 
5725     MarkFunctionReferenced(Location, Dtor);
5726     DiagnoseUseOfDecl(Dtor, Location);
5727   }
5728 }
5729 
5730 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5731   if (!CDtorDecl)
5732     return;
5733 
5734   if (CXXConstructorDecl *Constructor
5735       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5736     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5737     DiagnoseUninitializedFields(*this, Constructor);
5738   }
5739 }
5740 
5741 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5742   if (!getLangOpts().CPlusPlus)
5743     return false;
5744 
5745   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5746   if (!RD)
5747     return false;
5748 
5749   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5750   // class template specialization here, but doing so breaks a lot of code.
5751 
5752   // We can't answer whether something is abstract until it has a
5753   // definition. If it's currently being defined, we'll walk back
5754   // over all the declarations when we have a full definition.
5755   const CXXRecordDecl *Def = RD->getDefinition();
5756   if (!Def || Def->isBeingDefined())
5757     return false;
5758 
5759   return RD->isAbstract();
5760 }
5761 
5762 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5763                                   TypeDiagnoser &Diagnoser) {
5764   if (!isAbstractType(Loc, T))
5765     return false;
5766 
5767   T = Context.getBaseElementType(T);
5768   Diagnoser.diagnose(*this, Loc, T);
5769   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5770   return true;
5771 }
5772 
5773 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5774   // Check if we've already emitted the list of pure virtual functions
5775   // for this class.
5776   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5777     return;
5778 
5779   // If the diagnostic is suppressed, don't emit the notes. We're only
5780   // going to emit them once, so try to attach them to a diagnostic we're
5781   // actually going to show.
5782   if (Diags.isLastDiagnosticIgnored())
5783     return;
5784 
5785   CXXFinalOverriderMap FinalOverriders;
5786   RD->getFinalOverriders(FinalOverriders);
5787 
5788   // Keep a set of seen pure methods so we won't diagnose the same method
5789   // more than once.
5790   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5791 
5792   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5793                                    MEnd = FinalOverriders.end();
5794        M != MEnd;
5795        ++M) {
5796     for (OverridingMethods::iterator SO = M->second.begin(),
5797                                   SOEnd = M->second.end();
5798          SO != SOEnd; ++SO) {
5799       // C++ [class.abstract]p4:
5800       //   A class is abstract if it contains or inherits at least one
5801       //   pure virtual function for which the final overrider is pure
5802       //   virtual.
5803 
5804       //
5805       if (SO->second.size() != 1)
5806         continue;
5807 
5808       if (!SO->second.front().Method->isPure())
5809         continue;
5810 
5811       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5812         continue;
5813 
5814       Diag(SO->second.front().Method->getLocation(),
5815            diag::note_pure_virtual_function)
5816         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5817     }
5818   }
5819 
5820   if (!PureVirtualClassDiagSet)
5821     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5822   PureVirtualClassDiagSet->insert(RD);
5823 }
5824 
5825 namespace {
5826 struct AbstractUsageInfo {
5827   Sema &S;
5828   CXXRecordDecl *Record;
5829   CanQualType AbstractType;
5830   bool Invalid;
5831 
5832   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5833     : S(S), Record(Record),
5834       AbstractType(S.Context.getCanonicalType(
5835                    S.Context.getTypeDeclType(Record))),
5836       Invalid(false) {}
5837 
5838   void DiagnoseAbstractType() {
5839     if (Invalid) return;
5840     S.DiagnoseAbstractType(Record);
5841     Invalid = true;
5842   }
5843 
5844   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5845 };
5846 
5847 struct CheckAbstractUsage {
5848   AbstractUsageInfo &Info;
5849   const NamedDecl *Ctx;
5850 
5851   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5852     : Info(Info), Ctx(Ctx) {}
5853 
5854   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5855     switch (TL.getTypeLocClass()) {
5856 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5857 #define TYPELOC(CLASS, PARENT) \
5858     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5859 #include "clang/AST/TypeLocNodes.def"
5860     }
5861   }
5862 
5863   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5864     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5865     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5866       if (!TL.getParam(I))
5867         continue;
5868 
5869       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5870       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5871     }
5872   }
5873 
5874   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5875     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5876   }
5877 
5878   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5879     // Visit the type parameters from a permissive context.
5880     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5881       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5882       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5883         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5884           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5885       // TODO: other template argument types?
5886     }
5887   }
5888 
5889   // Visit pointee types from a permissive context.
5890 #define CheckPolymorphic(Type) \
5891   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5892     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5893   }
5894   CheckPolymorphic(PointerTypeLoc)
5895   CheckPolymorphic(ReferenceTypeLoc)
5896   CheckPolymorphic(MemberPointerTypeLoc)
5897   CheckPolymorphic(BlockPointerTypeLoc)
5898   CheckPolymorphic(AtomicTypeLoc)
5899 
5900   /// Handle all the types we haven't given a more specific
5901   /// implementation for above.
5902   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5903     // Every other kind of type that we haven't called out already
5904     // that has an inner type is either (1) sugar or (2) contains that
5905     // inner type in some way as a subobject.
5906     if (TypeLoc Next = TL.getNextTypeLoc())
5907       return Visit(Next, Sel);
5908 
5909     // If there's no inner type and we're in a permissive context,
5910     // don't diagnose.
5911     if (Sel == Sema::AbstractNone) return;
5912 
5913     // Check whether the type matches the abstract type.
5914     QualType T = TL.getType();
5915     if (T->isArrayType()) {
5916       Sel = Sema::AbstractArrayType;
5917       T = Info.S.Context.getBaseElementType(T);
5918     }
5919     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5920     if (CT != Info.AbstractType) return;
5921 
5922     // It matched; do some magic.
5923     // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
5924     if (Sel == Sema::AbstractArrayType) {
5925       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5926         << T << TL.getSourceRange();
5927     } else {
5928       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5929         << Sel << T << TL.getSourceRange();
5930     }
5931     Info.DiagnoseAbstractType();
5932   }
5933 };
5934 
5935 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5936                                   Sema::AbstractDiagSelID Sel) {
5937   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5938 }
5939 
5940 }
5941 
5942 /// Check for invalid uses of an abstract type in a function declaration.
5943 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5944                                     FunctionDecl *FD) {
5945   // No need to do the check on definitions, which require that
5946   // the return/param types be complete.
5947   if (FD->doesThisDeclarationHaveABody())
5948     return;
5949 
5950   // For safety's sake, just ignore it if we don't have type source
5951   // information.  This should never happen for non-implicit methods,
5952   // but...
5953   if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5954     Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
5955 }
5956 
5957 /// Check for invalid uses of an abstract type in a variable0 declaration.
5958 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5959                                     VarDecl *VD) {
5960   // No need to do the check on definitions, which require that
5961   // the type is complete.
5962   if (VD->isThisDeclarationADefinition())
5963     return;
5964 
5965   Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
5966                  Sema::AbstractVariableType);
5967 }
5968 
5969 /// Check for invalid uses of an abstract type within a class definition.
5970 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5971                                     CXXRecordDecl *RD) {
5972   for (auto *D : RD->decls()) {
5973     if (D->isImplicit()) continue;
5974 
5975     // Step through friends to the befriended declaration.
5976     if (auto *FD = dyn_cast<FriendDecl>(D)) {
5977       D = FD->getFriendDecl();
5978       if (!D) continue;
5979     }
5980 
5981     // Functions and function templates.
5982     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5983       CheckAbstractClassUsage(Info, FD);
5984     } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
5985       CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
5986 
5987     // Fields and static variables.
5988     } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
5989       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5990         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5991     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
5992       CheckAbstractClassUsage(Info, VD);
5993     } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
5994       CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
5995 
5996     // Nested classes and class templates.
5997     } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5998       CheckAbstractClassUsage(Info, RD);
5999     } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6000       CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6001     }
6002   }
6003 }
6004 
6005 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6006   Attr *ClassAttr = getDLLAttr(Class);
6007   if (!ClassAttr)
6008     return;
6009 
6010   assert(ClassAttr->getKind() == attr::DLLExport);
6011 
6012   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6013 
6014   if (TSK == TSK_ExplicitInstantiationDeclaration)
6015     // Don't go any further if this is just an explicit instantiation
6016     // declaration.
6017     return;
6018 
6019   // Add a context note to explain how we got to any diagnostics produced below.
6020   struct MarkingClassDllexported {
6021     Sema &S;
6022     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6023                             SourceLocation AttrLoc)
6024         : S(S) {
6025       Sema::CodeSynthesisContext Ctx;
6026       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6027       Ctx.PointOfInstantiation = AttrLoc;
6028       Ctx.Entity = Class;
6029       S.pushCodeSynthesisContext(Ctx);
6030     }
6031     ~MarkingClassDllexported() {
6032       S.popCodeSynthesisContext();
6033     }
6034   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6035 
6036   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6037     S.MarkVTableUsed(Class->getLocation(), Class, true);
6038 
6039   for (Decl *Member : Class->decls()) {
6040     // Skip members that were not marked exported.
6041     if (!Member->hasAttr<DLLExportAttr>())
6042       continue;
6043 
6044     // Defined static variables that are members of an exported base
6045     // class must be marked export too.
6046     auto *VD = dyn_cast<VarDecl>(Member);
6047     if (VD && VD->getStorageClass() == SC_Static &&
6048         TSK == TSK_ImplicitInstantiation)
6049       S.MarkVariableReferenced(VD->getLocation(), VD);
6050 
6051     auto *MD = dyn_cast<CXXMethodDecl>(Member);
6052     if (!MD)
6053       continue;
6054 
6055     if (MD->isUserProvided()) {
6056       // Instantiate non-default class member functions ...
6057 
6058       // .. except for certain kinds of template specializations.
6059       if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6060         continue;
6061 
6062       // If this is an MS ABI dllexport default constructor, instantiate any
6063       // default arguments.
6064       if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6065         auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6066         if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6067           S.InstantiateDefaultCtorDefaultArgs(CD);
6068         }
6069       }
6070 
6071       S.MarkFunctionReferenced(Class->getLocation(), MD);
6072 
6073       // The function will be passed to the consumer when its definition is
6074       // encountered.
6075     } else if (MD->isExplicitlyDefaulted()) {
6076       // Synthesize and instantiate explicitly defaulted methods.
6077       S.MarkFunctionReferenced(Class->getLocation(), MD);
6078 
6079       if (TSK != TSK_ExplicitInstantiationDefinition) {
6080         // Except for explicit instantiation defs, we will not see the
6081         // definition again later, so pass it to the consumer now.
6082         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6083       }
6084     } else if (!MD->isTrivial() ||
6085                MD->isCopyAssignmentOperator() ||
6086                MD->isMoveAssignmentOperator()) {
6087       // Synthesize and instantiate non-trivial implicit methods, and the copy
6088       // and move assignment operators. The latter are exported even if they
6089       // are trivial, because the address of an operator can be taken and
6090       // should compare equal across libraries.
6091       S.MarkFunctionReferenced(Class->getLocation(), MD);
6092 
6093       // There is no later point when we will see the definition of this
6094       // function, so pass it to the consumer now.
6095       S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6096     }
6097   }
6098 }
6099 
6100 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6101                                                         CXXRecordDecl *Class) {
6102   // Only the MS ABI has default constructor closures, so we don't need to do
6103   // this semantic checking anywhere else.
6104   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6105     return;
6106 
6107   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6108   for (Decl *Member : Class->decls()) {
6109     // Look for exported default constructors.
6110     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6111     if (!CD || !CD->isDefaultConstructor())
6112       continue;
6113     auto *Attr = CD->getAttr<DLLExportAttr>();
6114     if (!Attr)
6115       continue;
6116 
6117     // If the class is non-dependent, mark the default arguments as ODR-used so
6118     // that we can properly codegen the constructor closure.
6119     if (!Class->isDependentContext()) {
6120       for (ParmVarDecl *PD : CD->parameters()) {
6121         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6122         S.DiscardCleanupsInEvaluationContext();
6123       }
6124     }
6125 
6126     if (LastExportedDefaultCtor) {
6127       S.Diag(LastExportedDefaultCtor->getLocation(),
6128              diag::err_attribute_dll_ambiguous_default_ctor)
6129           << Class;
6130       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6131           << CD->getDeclName();
6132       return;
6133     }
6134     LastExportedDefaultCtor = CD;
6135   }
6136 }
6137 
6138 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6139                                                        CXXRecordDecl *Class) {
6140   bool ErrorReported = false;
6141   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6142                                                      ClassTemplateDecl *TD) {
6143     if (ErrorReported)
6144       return;
6145     S.Diag(TD->getLocation(),
6146            diag::err_cuda_device_builtin_surftex_cls_template)
6147         << /*surface*/ 0 << TD;
6148     ErrorReported = true;
6149   };
6150 
6151   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6152   if (!TD) {
6153     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6154     if (!SD) {
6155       S.Diag(Class->getLocation(),
6156              diag::err_cuda_device_builtin_surftex_ref_decl)
6157           << /*surface*/ 0 << Class;
6158       S.Diag(Class->getLocation(),
6159              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6160           << Class;
6161       return;
6162     }
6163     TD = SD->getSpecializedTemplate();
6164   }
6165 
6166   TemplateParameterList *Params = TD->getTemplateParameters();
6167   unsigned N = Params->size();
6168 
6169   if (N != 2) {
6170     reportIllegalClassTemplate(S, TD);
6171     S.Diag(TD->getLocation(),
6172            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6173         << TD << 2;
6174   }
6175   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6176     reportIllegalClassTemplate(S, TD);
6177     S.Diag(TD->getLocation(),
6178            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6179         << TD << /*1st*/ 0 << /*type*/ 0;
6180   }
6181   if (N > 1) {
6182     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6183     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6184       reportIllegalClassTemplate(S, TD);
6185       S.Diag(TD->getLocation(),
6186              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6187           << TD << /*2nd*/ 1 << /*integer*/ 1;
6188     }
6189   }
6190 }
6191 
6192 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6193                                                        CXXRecordDecl *Class) {
6194   bool ErrorReported = false;
6195   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6196                                                      ClassTemplateDecl *TD) {
6197     if (ErrorReported)
6198       return;
6199     S.Diag(TD->getLocation(),
6200            diag::err_cuda_device_builtin_surftex_cls_template)
6201         << /*texture*/ 1 << TD;
6202     ErrorReported = true;
6203   };
6204 
6205   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6206   if (!TD) {
6207     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6208     if (!SD) {
6209       S.Diag(Class->getLocation(),
6210              diag::err_cuda_device_builtin_surftex_ref_decl)
6211           << /*texture*/ 1 << Class;
6212       S.Diag(Class->getLocation(),
6213              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6214           << Class;
6215       return;
6216     }
6217     TD = SD->getSpecializedTemplate();
6218   }
6219 
6220   TemplateParameterList *Params = TD->getTemplateParameters();
6221   unsigned N = Params->size();
6222 
6223   if (N != 3) {
6224     reportIllegalClassTemplate(S, TD);
6225     S.Diag(TD->getLocation(),
6226            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6227         << TD << 3;
6228   }
6229   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6230     reportIllegalClassTemplate(S, TD);
6231     S.Diag(TD->getLocation(),
6232            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6233         << TD << /*1st*/ 0 << /*type*/ 0;
6234   }
6235   if (N > 1) {
6236     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6237     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6238       reportIllegalClassTemplate(S, TD);
6239       S.Diag(TD->getLocation(),
6240              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6241           << TD << /*2nd*/ 1 << /*integer*/ 1;
6242     }
6243   }
6244   if (N > 2) {
6245     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6246     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6247       reportIllegalClassTemplate(S, TD);
6248       S.Diag(TD->getLocation(),
6249              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6250           << TD << /*3rd*/ 2 << /*integer*/ 1;
6251     }
6252   }
6253 }
6254 
6255 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6256   // Mark any compiler-generated routines with the implicit code_seg attribute.
6257   for (auto *Method : Class->methods()) {
6258     if (Method->isUserProvided())
6259       continue;
6260     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6261       Method->addAttr(A);
6262   }
6263 }
6264 
6265 /// Check class-level dllimport/dllexport attribute.
6266 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6267   Attr *ClassAttr = getDLLAttr(Class);
6268 
6269   // MSVC inherits DLL attributes to partial class template specializations.
6270   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6271     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6272       if (Attr *TemplateAttr =
6273               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6274         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6275         A->setInherited(true);
6276         ClassAttr = A;
6277       }
6278     }
6279   }
6280 
6281   if (!ClassAttr)
6282     return;
6283 
6284   if (!Class->isExternallyVisible()) {
6285     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6286         << Class << ClassAttr;
6287     return;
6288   }
6289 
6290   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6291       !ClassAttr->isInherited()) {
6292     // Diagnose dll attributes on members of class with dll attribute.
6293     for (Decl *Member : Class->decls()) {
6294       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6295         continue;
6296       InheritableAttr *MemberAttr = getDLLAttr(Member);
6297       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6298         continue;
6299 
6300       Diag(MemberAttr->getLocation(),
6301              diag::err_attribute_dll_member_of_dll_class)
6302           << MemberAttr << ClassAttr;
6303       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6304       Member->setInvalidDecl();
6305     }
6306   }
6307 
6308   if (Class->getDescribedClassTemplate())
6309     // Don't inherit dll attribute until the template is instantiated.
6310     return;
6311 
6312   // The class is either imported or exported.
6313   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6314 
6315   // Check if this was a dllimport attribute propagated from a derived class to
6316   // a base class template specialization. We don't apply these attributes to
6317   // static data members.
6318   const bool PropagatedImport =
6319       !ClassExported &&
6320       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6321 
6322   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6323 
6324   // Ignore explicit dllexport on explicit class template instantiation
6325   // declarations, except in MinGW mode.
6326   if (ClassExported && !ClassAttr->isInherited() &&
6327       TSK == TSK_ExplicitInstantiationDeclaration &&
6328       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6329     Class->dropAttr<DLLExportAttr>();
6330     return;
6331   }
6332 
6333   // Force declaration of implicit members so they can inherit the attribute.
6334   ForceDeclarationOfImplicitMembers(Class);
6335 
6336   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6337   // seem to be true in practice?
6338 
6339   for (Decl *Member : Class->decls()) {
6340     VarDecl *VD = dyn_cast<VarDecl>(Member);
6341     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6342 
6343     // Only methods and static fields inherit the attributes.
6344     if (!VD && !MD)
6345       continue;
6346 
6347     if (MD) {
6348       // Don't process deleted methods.
6349       if (MD->isDeleted())
6350         continue;
6351 
6352       if (MD->isInlined()) {
6353         // MinGW does not import or export inline methods. But do it for
6354         // template instantiations.
6355         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6356             TSK != TSK_ExplicitInstantiationDeclaration &&
6357             TSK != TSK_ExplicitInstantiationDefinition)
6358           continue;
6359 
6360         // MSVC versions before 2015 don't export the move assignment operators
6361         // and move constructor, so don't attempt to import/export them if
6362         // we have a definition.
6363         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6364         if ((MD->isMoveAssignmentOperator() ||
6365              (Ctor && Ctor->isMoveConstructor())) &&
6366             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6367           continue;
6368 
6369         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6370         // operator is exported anyway.
6371         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6372             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6373           continue;
6374       }
6375     }
6376 
6377     // Don't apply dllimport attributes to static data members of class template
6378     // instantiations when the attribute is propagated from a derived class.
6379     if (VD && PropagatedImport)
6380       continue;
6381 
6382     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6383       continue;
6384 
6385     if (!getDLLAttr(Member)) {
6386       InheritableAttr *NewAttr = nullptr;
6387 
6388       // Do not export/import inline function when -fno-dllexport-inlines is
6389       // passed. But add attribute for later local static var check.
6390       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6391           TSK != TSK_ExplicitInstantiationDeclaration &&
6392           TSK != TSK_ExplicitInstantiationDefinition) {
6393         if (ClassExported) {
6394           NewAttr = ::new (getASTContext())
6395               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6396         } else {
6397           NewAttr = ::new (getASTContext())
6398               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6399         }
6400       } else {
6401         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6402       }
6403 
6404       NewAttr->setInherited(true);
6405       Member->addAttr(NewAttr);
6406 
6407       if (MD) {
6408         // Propagate DLLAttr to friend re-declarations of MD that have already
6409         // been constructed.
6410         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6411              FD = FD->getPreviousDecl()) {
6412           if (FD->getFriendObjectKind() == Decl::FOK_None)
6413             continue;
6414           assert(!getDLLAttr(FD) &&
6415                  "friend re-decl should not already have a DLLAttr");
6416           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6417           NewAttr->setInherited(true);
6418           FD->addAttr(NewAttr);
6419         }
6420       }
6421     }
6422   }
6423 
6424   if (ClassExported)
6425     DelayedDllExportClasses.push_back(Class);
6426 }
6427 
6428 /// Perform propagation of DLL attributes from a derived class to a
6429 /// templated base class for MS compatibility.
6430 void Sema::propagateDLLAttrToBaseClassTemplate(
6431     CXXRecordDecl *Class, Attr *ClassAttr,
6432     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6433   if (getDLLAttr(
6434           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6435     // If the base class template has a DLL attribute, don't try to change it.
6436     return;
6437   }
6438 
6439   auto TSK = BaseTemplateSpec->getSpecializationKind();
6440   if (!getDLLAttr(BaseTemplateSpec) &&
6441       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6442        TSK == TSK_ImplicitInstantiation)) {
6443     // The template hasn't been instantiated yet (or it has, but only as an
6444     // explicit instantiation declaration or implicit instantiation, which means
6445     // we haven't codegenned any members yet), so propagate the attribute.
6446     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6447     NewAttr->setInherited(true);
6448     BaseTemplateSpec->addAttr(NewAttr);
6449 
6450     // If this was an import, mark that we propagated it from a derived class to
6451     // a base class template specialization.
6452     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6453       ImportAttr->setPropagatedToBaseTemplate();
6454 
6455     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6456     // needs to be run again to work see the new attribute. Otherwise this will
6457     // get run whenever the template is instantiated.
6458     if (TSK != TSK_Undeclared)
6459       checkClassLevelDLLAttribute(BaseTemplateSpec);
6460 
6461     return;
6462   }
6463 
6464   if (getDLLAttr(BaseTemplateSpec)) {
6465     // The template has already been specialized or instantiated with an
6466     // attribute, explicitly or through propagation. We should not try to change
6467     // it.
6468     return;
6469   }
6470 
6471   // The template was previously instantiated or explicitly specialized without
6472   // a dll attribute, It's too late for us to add an attribute, so warn that
6473   // this is unsupported.
6474   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6475       << BaseTemplateSpec->isExplicitSpecialization();
6476   Diag(ClassAttr->getLocation(), diag::note_attribute);
6477   if (BaseTemplateSpec->isExplicitSpecialization()) {
6478     Diag(BaseTemplateSpec->getLocation(),
6479            diag::note_template_class_explicit_specialization_was_here)
6480         << BaseTemplateSpec;
6481   } else {
6482     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6483            diag::note_template_class_instantiation_was_here)
6484         << BaseTemplateSpec;
6485   }
6486 }
6487 
6488 /// Determine the kind of defaulting that would be done for a given function.
6489 ///
6490 /// If the function is both a default constructor and a copy / move constructor
6491 /// (due to having a default argument for the first parameter), this picks
6492 /// CXXDefaultConstructor.
6493 ///
6494 /// FIXME: Check that case is properly handled by all callers.
6495 Sema::DefaultedFunctionKind
6496 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6497   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6498     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6499       if (Ctor->isDefaultConstructor())
6500         return Sema::CXXDefaultConstructor;
6501 
6502       if (Ctor->isCopyConstructor())
6503         return Sema::CXXCopyConstructor;
6504 
6505       if (Ctor->isMoveConstructor())
6506         return Sema::CXXMoveConstructor;
6507     }
6508 
6509     if (MD->isCopyAssignmentOperator())
6510       return Sema::CXXCopyAssignment;
6511 
6512     if (MD->isMoveAssignmentOperator())
6513       return Sema::CXXMoveAssignment;
6514 
6515     if (isa<CXXDestructorDecl>(FD))
6516       return Sema::CXXDestructor;
6517   }
6518 
6519   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6520   case OO_EqualEqual:
6521     return DefaultedComparisonKind::Equal;
6522 
6523   case OO_ExclaimEqual:
6524     return DefaultedComparisonKind::NotEqual;
6525 
6526   case OO_Spaceship:
6527     // No point allowing this if <=> doesn't exist in the current language mode.
6528     if (!getLangOpts().CPlusPlus20)
6529       break;
6530     return DefaultedComparisonKind::ThreeWay;
6531 
6532   case OO_Less:
6533   case OO_LessEqual:
6534   case OO_Greater:
6535   case OO_GreaterEqual:
6536     // No point allowing this if <=> doesn't exist in the current language mode.
6537     if (!getLangOpts().CPlusPlus20)
6538       break;
6539     return DefaultedComparisonKind::Relational;
6540 
6541   default:
6542     break;
6543   }
6544 
6545   // Not defaultable.
6546   return DefaultedFunctionKind();
6547 }
6548 
6549 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6550                                     SourceLocation DefaultLoc) {
6551   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6552   if (DFK.isComparison())
6553     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6554 
6555   switch (DFK.asSpecialMember()) {
6556   case Sema::CXXDefaultConstructor:
6557     S.DefineImplicitDefaultConstructor(DefaultLoc,
6558                                        cast<CXXConstructorDecl>(FD));
6559     break;
6560   case Sema::CXXCopyConstructor:
6561     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6562     break;
6563   case Sema::CXXCopyAssignment:
6564     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6565     break;
6566   case Sema::CXXDestructor:
6567     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6568     break;
6569   case Sema::CXXMoveConstructor:
6570     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6571     break;
6572   case Sema::CXXMoveAssignment:
6573     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6574     break;
6575   case Sema::CXXInvalid:
6576     llvm_unreachable("Invalid special member.");
6577   }
6578 }
6579 
6580 /// Determine whether a type is permitted to be passed or returned in
6581 /// registers, per C++ [class.temporary]p3.
6582 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6583                                TargetInfo::CallingConvKind CCK) {
6584   if (D->isDependentType() || D->isInvalidDecl())
6585     return false;
6586 
6587   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6588   // The PS4 platform ABI follows the behavior of Clang 3.2.
6589   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6590     return !D->hasNonTrivialDestructorForCall() &&
6591            !D->hasNonTrivialCopyConstructorForCall();
6592 
6593   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6594     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6595     bool DtorIsTrivialForCall = false;
6596 
6597     // If a class has at least one non-deleted, trivial copy constructor, it
6598     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6599     //
6600     // Note: This permits classes with non-trivial copy or move ctors to be
6601     // passed in registers, so long as they *also* have a trivial copy ctor,
6602     // which is non-conforming.
6603     if (D->needsImplicitCopyConstructor()) {
6604       if (!D->defaultedCopyConstructorIsDeleted()) {
6605         if (D->hasTrivialCopyConstructor())
6606           CopyCtorIsTrivial = true;
6607         if (D->hasTrivialCopyConstructorForCall())
6608           CopyCtorIsTrivialForCall = true;
6609       }
6610     } else {
6611       for (const CXXConstructorDecl *CD : D->ctors()) {
6612         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6613           if (CD->isTrivial())
6614             CopyCtorIsTrivial = true;
6615           if (CD->isTrivialForCall())
6616             CopyCtorIsTrivialForCall = true;
6617         }
6618       }
6619     }
6620 
6621     if (D->needsImplicitDestructor()) {
6622       if (!D->defaultedDestructorIsDeleted() &&
6623           D->hasTrivialDestructorForCall())
6624         DtorIsTrivialForCall = true;
6625     } else if (const auto *DD = D->getDestructor()) {
6626       if (!DD->isDeleted() && DD->isTrivialForCall())
6627         DtorIsTrivialForCall = true;
6628     }
6629 
6630     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6631     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6632       return true;
6633 
6634     // If a class has a destructor, we'd really like to pass it indirectly
6635     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6636     // impossible for small types, which it will pass in a single register or
6637     // stack slot. Most objects with dtors are large-ish, so handle that early.
6638     // We can't call out all large objects as being indirect because there are
6639     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6640     // how we pass large POD types.
6641 
6642     // Note: This permits small classes with nontrivial destructors to be
6643     // passed in registers, which is non-conforming.
6644     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6645     uint64_t TypeSize = isAArch64 ? 128 : 64;
6646 
6647     if (CopyCtorIsTrivial &&
6648         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6649       return true;
6650     return false;
6651   }
6652 
6653   // Per C++ [class.temporary]p3, the relevant condition is:
6654   //   each copy constructor, move constructor, and destructor of X is
6655   //   either trivial or deleted, and X has at least one non-deleted copy
6656   //   or move constructor
6657   bool HasNonDeletedCopyOrMove = false;
6658 
6659   if (D->needsImplicitCopyConstructor() &&
6660       !D->defaultedCopyConstructorIsDeleted()) {
6661     if (!D->hasTrivialCopyConstructorForCall())
6662       return false;
6663     HasNonDeletedCopyOrMove = true;
6664   }
6665 
6666   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6667       !D->defaultedMoveConstructorIsDeleted()) {
6668     if (!D->hasTrivialMoveConstructorForCall())
6669       return false;
6670     HasNonDeletedCopyOrMove = true;
6671   }
6672 
6673   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6674       !D->hasTrivialDestructorForCall())
6675     return false;
6676 
6677   for (const CXXMethodDecl *MD : D->methods()) {
6678     if (MD->isDeleted())
6679       continue;
6680 
6681     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6682     if (CD && CD->isCopyOrMoveConstructor())
6683       HasNonDeletedCopyOrMove = true;
6684     else if (!isa<CXXDestructorDecl>(MD))
6685       continue;
6686 
6687     if (!MD->isTrivialForCall())
6688       return false;
6689   }
6690 
6691   return HasNonDeletedCopyOrMove;
6692 }
6693 
6694 /// Report an error regarding overriding, along with any relevant
6695 /// overridden methods.
6696 ///
6697 /// \param DiagID the primary error to report.
6698 /// \param MD the overriding method.
6699 static bool
6700 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6701                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6702   bool IssuedDiagnostic = false;
6703   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6704     if (Report(O)) {
6705       if (!IssuedDiagnostic) {
6706         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6707         IssuedDiagnostic = true;
6708       }
6709       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6710     }
6711   }
6712   return IssuedDiagnostic;
6713 }
6714 
6715 /// Perform semantic checks on a class definition that has been
6716 /// completing, introducing implicitly-declared members, checking for
6717 /// abstract types, etc.
6718 ///
6719 /// \param S The scope in which the class was parsed. Null if we didn't just
6720 ///        parse a class definition.
6721 /// \param Record The completed class.
6722 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6723   if (!Record)
6724     return;
6725 
6726   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6727     AbstractUsageInfo Info(*this, Record);
6728     CheckAbstractClassUsage(Info, Record);
6729   }
6730 
6731   // If this is not an aggregate type and has no user-declared constructor,
6732   // complain about any non-static data members of reference or const scalar
6733   // type, since they will never get initializers.
6734   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6735       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6736       !Record->isLambda()) {
6737     bool Complained = false;
6738     for (const auto *F : Record->fields()) {
6739       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6740         continue;
6741 
6742       if (F->getType()->isReferenceType() ||
6743           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6744         if (!Complained) {
6745           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6746             << Record->getTagKind() << Record;
6747           Complained = true;
6748         }
6749 
6750         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6751           << F->getType()->isReferenceType()
6752           << F->getDeclName();
6753       }
6754     }
6755   }
6756 
6757   if (Record->getIdentifier()) {
6758     // C++ [class.mem]p13:
6759     //   If T is the name of a class, then each of the following shall have a
6760     //   name different from T:
6761     //     - every member of every anonymous union that is a member of class T.
6762     //
6763     // C++ [class.mem]p14:
6764     //   In addition, if class T has a user-declared constructor (12.1), every
6765     //   non-static data member of class T shall have a name different from T.
6766     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6767     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6768          ++I) {
6769       NamedDecl *D = (*I)->getUnderlyingDecl();
6770       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6771            Record->hasUserDeclaredConstructor()) ||
6772           isa<IndirectFieldDecl>(D)) {
6773         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6774           << D->getDeclName();
6775         break;
6776       }
6777     }
6778   }
6779 
6780   // Warn if the class has virtual methods but non-virtual public destructor.
6781   if (Record->isPolymorphic() && !Record->isDependentType()) {
6782     CXXDestructorDecl *dtor = Record->getDestructor();
6783     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6784         !Record->hasAttr<FinalAttr>())
6785       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6786            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6787   }
6788 
6789   if (Record->isAbstract()) {
6790     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6791       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6792         << FA->isSpelledAsSealed();
6793       DiagnoseAbstractType(Record);
6794     }
6795   }
6796 
6797   // Warn if the class has a final destructor but is not itself marked final.
6798   if (!Record->hasAttr<FinalAttr>()) {
6799     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6800       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6801         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6802             << FA->isSpelledAsSealed()
6803             << FixItHint::CreateInsertion(
6804                    getLocForEndOfToken(Record->getLocation()),
6805                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6806         Diag(Record->getLocation(),
6807              diag::note_final_dtor_non_final_class_silence)
6808             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6809       }
6810     }
6811   }
6812 
6813   // See if trivial_abi has to be dropped.
6814   if (Record->hasAttr<TrivialABIAttr>())
6815     checkIllFormedTrivialABIStruct(*Record);
6816 
6817   // Set HasTrivialSpecialMemberForCall if the record has attribute
6818   // "trivial_abi".
6819   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6820 
6821   if (HasTrivialABI)
6822     Record->setHasTrivialSpecialMemberForCall();
6823 
6824   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6825   // We check these last because they can depend on the properties of the
6826   // primary comparison functions (==, <=>).
6827   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6828 
6829   // Perform checks that can't be done until we know all the properties of a
6830   // member function (whether it's defaulted, deleted, virtual, overriding,
6831   // ...).
6832   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6833     // A static function cannot override anything.
6834     if (MD->getStorageClass() == SC_Static) {
6835       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6836                           [](const CXXMethodDecl *) { return true; }))
6837         return;
6838     }
6839 
6840     // A deleted function cannot override a non-deleted function and vice
6841     // versa.
6842     if (ReportOverrides(*this,
6843                         MD->isDeleted() ? diag::err_deleted_override
6844                                         : diag::err_non_deleted_override,
6845                         MD, [&](const CXXMethodDecl *V) {
6846                           return MD->isDeleted() != V->isDeleted();
6847                         })) {
6848       if (MD->isDefaulted() && MD->isDeleted())
6849         // Explain why this defaulted function was deleted.
6850         DiagnoseDeletedDefaultedFunction(MD);
6851       return;
6852     }
6853 
6854     // A consteval function cannot override a non-consteval function and vice
6855     // versa.
6856     if (ReportOverrides(*this,
6857                         MD->isConsteval() ? diag::err_consteval_override
6858                                           : diag::err_non_consteval_override,
6859                         MD, [&](const CXXMethodDecl *V) {
6860                           return MD->isConsteval() != V->isConsteval();
6861                         })) {
6862       if (MD->isDefaulted() && MD->isDeleted())
6863         // Explain why this defaulted function was deleted.
6864         DiagnoseDeletedDefaultedFunction(MD);
6865       return;
6866     }
6867   };
6868 
6869   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6870     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6871       return false;
6872 
6873     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6874     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6875         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6876       DefaultedSecondaryComparisons.push_back(FD);
6877       return true;
6878     }
6879 
6880     CheckExplicitlyDefaultedFunction(S, FD);
6881     return false;
6882   };
6883 
6884   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6885     // Check whether the explicitly-defaulted members are valid.
6886     bool Incomplete = CheckForDefaultedFunction(M);
6887 
6888     // Skip the rest of the checks for a member of a dependent class.
6889     if (Record->isDependentType())
6890       return;
6891 
6892     // For an explicitly defaulted or deleted special member, we defer
6893     // determining triviality until the class is complete. That time is now!
6894     CXXSpecialMember CSM = getSpecialMember(M);
6895     if (!M->isImplicit() && !M->isUserProvided()) {
6896       if (CSM != CXXInvalid) {
6897         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6898         // Inform the class that we've finished declaring this member.
6899         Record->finishedDefaultedOrDeletedMember(M);
6900         M->setTrivialForCall(
6901             HasTrivialABI ||
6902             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6903         Record->setTrivialForCallFlags(M);
6904       }
6905     }
6906 
6907     // Set triviality for the purpose of calls if this is a user-provided
6908     // copy/move constructor or destructor.
6909     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6910          CSM == CXXDestructor) && M->isUserProvided()) {
6911       M->setTrivialForCall(HasTrivialABI);
6912       Record->setTrivialForCallFlags(M);
6913     }
6914 
6915     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6916         M->hasAttr<DLLExportAttr>()) {
6917       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6918           M->isTrivial() &&
6919           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6920            CSM == CXXDestructor))
6921         M->dropAttr<DLLExportAttr>();
6922 
6923       if (M->hasAttr<DLLExportAttr>()) {
6924         // Define after any fields with in-class initializers have been parsed.
6925         DelayedDllExportMemberFunctions.push_back(M);
6926       }
6927     }
6928 
6929     // Define defaulted constexpr virtual functions that override a base class
6930     // function right away.
6931     // FIXME: We can defer doing this until the vtable is marked as used.
6932     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6933       DefineDefaultedFunction(*this, M, M->getLocation());
6934 
6935     if (!Incomplete)
6936       CheckCompletedMemberFunction(M);
6937   };
6938 
6939   // Check the destructor before any other member function. We need to
6940   // determine whether it's trivial in order to determine whether the claas
6941   // type is a literal type, which is a prerequisite for determining whether
6942   // other special member functions are valid and whether they're implicitly
6943   // 'constexpr'.
6944   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6945     CompleteMemberFunction(Dtor);
6946 
6947   bool HasMethodWithOverrideControl = false,
6948        HasOverridingMethodWithoutOverrideControl = false;
6949   for (auto *D : Record->decls()) {
6950     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6951       // FIXME: We could do this check for dependent types with non-dependent
6952       // bases.
6953       if (!Record->isDependentType()) {
6954         // See if a method overloads virtual methods in a base
6955         // class without overriding any.
6956         if (!M->isStatic())
6957           DiagnoseHiddenVirtualMethods(M);
6958         if (M->hasAttr<OverrideAttr>())
6959           HasMethodWithOverrideControl = true;
6960         else if (M->size_overridden_methods() > 0)
6961           HasOverridingMethodWithoutOverrideControl = true;
6962       }
6963 
6964       if (!isa<CXXDestructorDecl>(M))
6965         CompleteMemberFunction(M);
6966     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6967       CheckForDefaultedFunction(
6968           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6969     }
6970   }
6971 
6972   if (HasOverridingMethodWithoutOverrideControl) {
6973     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6974     for (auto *M : Record->methods())
6975       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6976   }
6977 
6978   // Check the defaulted secondary comparisons after any other member functions.
6979   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6980     CheckExplicitlyDefaultedFunction(S, FD);
6981 
6982     // If this is a member function, we deferred checking it until now.
6983     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6984       CheckCompletedMemberFunction(MD);
6985   }
6986 
6987   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6988   // whether this class uses any C++ features that are implemented
6989   // completely differently in MSVC, and if so, emit a diagnostic.
6990   // That diagnostic defaults to an error, but we allow projects to
6991   // map it down to a warning (or ignore it).  It's a fairly common
6992   // practice among users of the ms_struct pragma to mass-annotate
6993   // headers, sweeping up a bunch of types that the project doesn't
6994   // really rely on MSVC-compatible layout for.  We must therefore
6995   // support "ms_struct except for C++ stuff" as a secondary ABI.
6996   // Don't emit this diagnostic if the feature was enabled as a
6997   // language option (as opposed to via a pragma or attribute), as
6998   // the option -mms-bitfields otherwise essentially makes it impossible
6999   // to build C++ code, unless this diagnostic is turned off.
7000   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7001       (Record->isPolymorphic() || Record->getNumBases())) {
7002     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7003   }
7004 
7005   checkClassLevelDLLAttribute(Record);
7006   checkClassLevelCodeSegAttribute(Record);
7007 
7008   bool ClangABICompat4 =
7009       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7010   TargetInfo::CallingConvKind CCK =
7011       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7012   bool CanPass = canPassInRegisters(*this, Record, CCK);
7013 
7014   // Do not change ArgPassingRestrictions if it has already been set to
7015   // APK_CanNeverPassInRegs.
7016   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
7017     Record->setArgPassingRestrictions(CanPass
7018                                           ? RecordDecl::APK_CanPassInRegs
7019                                           : RecordDecl::APK_CannotPassInRegs);
7020 
7021   // If canPassInRegisters returns true despite the record having a non-trivial
7022   // destructor, the record is destructed in the callee. This happens only when
7023   // the record or one of its subobjects has a field annotated with trivial_abi
7024   // or a field qualified with ObjC __strong/__weak.
7025   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7026     Record->setParamDestroyedInCallee(true);
7027   else if (Record->hasNonTrivialDestructor())
7028     Record->setParamDestroyedInCallee(CanPass);
7029 
7030   if (getLangOpts().ForceEmitVTables) {
7031     // If we want to emit all the vtables, we need to mark it as used.  This
7032     // is especially required for cases like vtable assumption loads.
7033     MarkVTableUsed(Record->getInnerLocStart(), Record);
7034   }
7035 
7036   if (getLangOpts().CUDA) {
7037     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7038       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7039     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7040       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7041   }
7042 }
7043 
7044 /// Look up the special member function that would be called by a special
7045 /// member function for a subobject of class type.
7046 ///
7047 /// \param Class The class type of the subobject.
7048 /// \param CSM The kind of special member function.
7049 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7050 /// \param ConstRHS True if this is a copy operation with a const object
7051 ///        on its RHS, that is, if the argument to the outer special member
7052 ///        function is 'const' and this is not a field marked 'mutable'.
7053 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7054     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7055     unsigned FieldQuals, bool ConstRHS) {
7056   unsigned LHSQuals = 0;
7057   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7058     LHSQuals = FieldQuals;
7059 
7060   unsigned RHSQuals = FieldQuals;
7061   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7062     RHSQuals = 0;
7063   else if (ConstRHS)
7064     RHSQuals |= Qualifiers::Const;
7065 
7066   return S.LookupSpecialMember(Class, CSM,
7067                                RHSQuals & Qualifiers::Const,
7068                                RHSQuals & Qualifiers::Volatile,
7069                                false,
7070                                LHSQuals & Qualifiers::Const,
7071                                LHSQuals & Qualifiers::Volatile);
7072 }
7073 
7074 class Sema::InheritedConstructorInfo {
7075   Sema &S;
7076   SourceLocation UseLoc;
7077 
7078   /// A mapping from the base classes through which the constructor was
7079   /// inherited to the using shadow declaration in that base class (or a null
7080   /// pointer if the constructor was declared in that base class).
7081   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7082       InheritedFromBases;
7083 
7084 public:
7085   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7086                            ConstructorUsingShadowDecl *Shadow)
7087       : S(S), UseLoc(UseLoc) {
7088     bool DiagnosedMultipleConstructedBases = false;
7089     CXXRecordDecl *ConstructedBase = nullptr;
7090     BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7091 
7092     // Find the set of such base class subobjects and check that there's a
7093     // unique constructed subobject.
7094     for (auto *D : Shadow->redecls()) {
7095       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7096       auto *DNominatedBase = DShadow->getNominatedBaseClass();
7097       auto *DConstructedBase = DShadow->getConstructedBaseClass();
7098 
7099       InheritedFromBases.insert(
7100           std::make_pair(DNominatedBase->getCanonicalDecl(),
7101                          DShadow->getNominatedBaseClassShadowDecl()));
7102       if (DShadow->constructsVirtualBase())
7103         InheritedFromBases.insert(
7104             std::make_pair(DConstructedBase->getCanonicalDecl(),
7105                            DShadow->getConstructedBaseClassShadowDecl()));
7106       else
7107         assert(DNominatedBase == DConstructedBase);
7108 
7109       // [class.inhctor.init]p2:
7110       //   If the constructor was inherited from multiple base class subobjects
7111       //   of type B, the program is ill-formed.
7112       if (!ConstructedBase) {
7113         ConstructedBase = DConstructedBase;
7114         ConstructedBaseIntroducer = D->getIntroducer();
7115       } else if (ConstructedBase != DConstructedBase &&
7116                  !Shadow->isInvalidDecl()) {
7117         if (!DiagnosedMultipleConstructedBases) {
7118           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7119               << Shadow->getTargetDecl();
7120           S.Diag(ConstructedBaseIntroducer->getLocation(),
7121                  diag::note_ambiguous_inherited_constructor_using)
7122               << ConstructedBase;
7123           DiagnosedMultipleConstructedBases = true;
7124         }
7125         S.Diag(D->getIntroducer()->getLocation(),
7126                diag::note_ambiguous_inherited_constructor_using)
7127             << DConstructedBase;
7128       }
7129     }
7130 
7131     if (DiagnosedMultipleConstructedBases)
7132       Shadow->setInvalidDecl();
7133   }
7134 
7135   /// Find the constructor to use for inherited construction of a base class,
7136   /// and whether that base class constructor inherits the constructor from a
7137   /// virtual base class (in which case it won't actually invoke it).
7138   std::pair<CXXConstructorDecl *, bool>
7139   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7140     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7141     if (It == InheritedFromBases.end())
7142       return std::make_pair(nullptr, false);
7143 
7144     // This is an intermediary class.
7145     if (It->second)
7146       return std::make_pair(
7147           S.findInheritingConstructor(UseLoc, Ctor, It->second),
7148           It->second->constructsVirtualBase());
7149 
7150     // This is the base class from which the constructor was inherited.
7151     return std::make_pair(Ctor, false);
7152   }
7153 };
7154 
7155 /// Is the special member function which would be selected to perform the
7156 /// specified operation on the specified class type a constexpr constructor?
7157 static bool
7158 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7159                          Sema::CXXSpecialMember CSM, unsigned Quals,
7160                          bool ConstRHS,
7161                          CXXConstructorDecl *InheritedCtor = nullptr,
7162                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7163   // If we're inheriting a constructor, see if we need to call it for this base
7164   // class.
7165   if (InheritedCtor) {
7166     assert(CSM == Sema::CXXDefaultConstructor);
7167     auto BaseCtor =
7168         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7169     if (BaseCtor)
7170       return BaseCtor->isConstexpr();
7171   }
7172 
7173   if (CSM == Sema::CXXDefaultConstructor)
7174     return ClassDecl->hasConstexprDefaultConstructor();
7175   if (CSM == Sema::CXXDestructor)
7176     return ClassDecl->hasConstexprDestructor();
7177 
7178   Sema::SpecialMemberOverloadResult SMOR =
7179       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7180   if (!SMOR.getMethod())
7181     // A constructor we wouldn't select can't be "involved in initializing"
7182     // anything.
7183     return true;
7184   return SMOR.getMethod()->isConstexpr();
7185 }
7186 
7187 /// Determine whether the specified special member function would be constexpr
7188 /// if it were implicitly defined.
7189 static bool defaultedSpecialMemberIsConstexpr(
7190     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7191     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7192     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7193   if (!S.getLangOpts().CPlusPlus11)
7194     return false;
7195 
7196   // C++11 [dcl.constexpr]p4:
7197   // In the definition of a constexpr constructor [...]
7198   bool Ctor = true;
7199   switch (CSM) {
7200   case Sema::CXXDefaultConstructor:
7201     if (Inherited)
7202       break;
7203     // Since default constructor lookup is essentially trivial (and cannot
7204     // involve, for instance, template instantiation), we compute whether a
7205     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7206     //
7207     // This is important for performance; we need to know whether the default
7208     // constructor is constexpr to determine whether the type is a literal type.
7209     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7210 
7211   case Sema::CXXCopyConstructor:
7212   case Sema::CXXMoveConstructor:
7213     // For copy or move constructors, we need to perform overload resolution.
7214     break;
7215 
7216   case Sema::CXXCopyAssignment:
7217   case Sema::CXXMoveAssignment:
7218     if (!S.getLangOpts().CPlusPlus14)
7219       return false;
7220     // In C++1y, we need to perform overload resolution.
7221     Ctor = false;
7222     break;
7223 
7224   case Sema::CXXDestructor:
7225     return ClassDecl->defaultedDestructorIsConstexpr();
7226 
7227   case Sema::CXXInvalid:
7228     return false;
7229   }
7230 
7231   //   -- if the class is a non-empty union, or for each non-empty anonymous
7232   //      union member of a non-union class, exactly one non-static data member
7233   //      shall be initialized; [DR1359]
7234   //
7235   // If we squint, this is guaranteed, since exactly one non-static data member
7236   // will be initialized (if the constructor isn't deleted), we just don't know
7237   // which one.
7238   if (Ctor && ClassDecl->isUnion())
7239     return CSM == Sema::CXXDefaultConstructor
7240                ? ClassDecl->hasInClassInitializer() ||
7241                      !ClassDecl->hasVariantMembers()
7242                : true;
7243 
7244   //   -- the class shall not have any virtual base classes;
7245   if (Ctor && ClassDecl->getNumVBases())
7246     return false;
7247 
7248   // C++1y [class.copy]p26:
7249   //   -- [the class] is a literal type, and
7250   if (!Ctor && !ClassDecl->isLiteral())
7251     return false;
7252 
7253   //   -- every constructor involved in initializing [...] base class
7254   //      sub-objects shall be a constexpr constructor;
7255   //   -- the assignment operator selected to copy/move each direct base
7256   //      class is a constexpr function, and
7257   for (const auto &B : ClassDecl->bases()) {
7258     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7259     if (!BaseType) continue;
7260 
7261     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7262     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7263                                   InheritedCtor, Inherited))
7264       return false;
7265   }
7266 
7267   //   -- every constructor involved in initializing non-static data members
7268   //      [...] shall be a constexpr constructor;
7269   //   -- every non-static data member and base class sub-object shall be
7270   //      initialized
7271   //   -- for each non-static data member of X that is of class type (or array
7272   //      thereof), the assignment operator selected to copy/move that member is
7273   //      a constexpr function
7274   for (const auto *F : ClassDecl->fields()) {
7275     if (F->isInvalidDecl())
7276       continue;
7277     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7278       continue;
7279     QualType BaseType = S.Context.getBaseElementType(F->getType());
7280     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7281       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7282       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7283                                     BaseType.getCVRQualifiers(),
7284                                     ConstArg && !F->isMutable()))
7285         return false;
7286     } else if (CSM == Sema::CXXDefaultConstructor) {
7287       return false;
7288     }
7289   }
7290 
7291   // All OK, it's constexpr!
7292   return true;
7293 }
7294 
7295 namespace {
7296 /// RAII object to register a defaulted function as having its exception
7297 /// specification computed.
7298 struct ComputingExceptionSpec {
7299   Sema &S;
7300 
7301   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7302       : S(S) {
7303     Sema::CodeSynthesisContext Ctx;
7304     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7305     Ctx.PointOfInstantiation = Loc;
7306     Ctx.Entity = FD;
7307     S.pushCodeSynthesisContext(Ctx);
7308   }
7309   ~ComputingExceptionSpec() {
7310     S.popCodeSynthesisContext();
7311   }
7312 };
7313 }
7314 
7315 static Sema::ImplicitExceptionSpecification
7316 ComputeDefaultedSpecialMemberExceptionSpec(
7317     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7318     Sema::InheritedConstructorInfo *ICI);
7319 
7320 static Sema::ImplicitExceptionSpecification
7321 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7322                                         FunctionDecl *FD,
7323                                         Sema::DefaultedComparisonKind DCK);
7324 
7325 static Sema::ImplicitExceptionSpecification
7326 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7327   auto DFK = S.getDefaultedFunctionKind(FD);
7328   if (DFK.isSpecialMember())
7329     return ComputeDefaultedSpecialMemberExceptionSpec(
7330         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7331   if (DFK.isComparison())
7332     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7333                                                    DFK.asComparison());
7334 
7335   auto *CD = cast<CXXConstructorDecl>(FD);
7336   assert(CD->getInheritedConstructor() &&
7337          "only defaulted functions and inherited constructors have implicit "
7338          "exception specs");
7339   Sema::InheritedConstructorInfo ICI(
7340       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7341   return ComputeDefaultedSpecialMemberExceptionSpec(
7342       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7343 }
7344 
7345 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7346                                                             CXXMethodDecl *MD) {
7347   FunctionProtoType::ExtProtoInfo EPI;
7348 
7349   // Build an exception specification pointing back at this member.
7350   EPI.ExceptionSpec.Type = EST_Unevaluated;
7351   EPI.ExceptionSpec.SourceDecl = MD;
7352 
7353   // Set the calling convention to the default for C++ instance methods.
7354   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7355       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7356                                             /*IsCXXMethod=*/true));
7357   return EPI;
7358 }
7359 
7360 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7361   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7362   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7363     return;
7364 
7365   // Evaluate the exception specification.
7366   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7367   auto ESI = IES.getExceptionSpec();
7368 
7369   // Update the type of the special member to use it.
7370   UpdateExceptionSpec(FD, ESI);
7371 }
7372 
7373 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7374   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7375 
7376   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7377   if (!DefKind) {
7378     assert(FD->getDeclContext()->isDependentContext());
7379     return;
7380   }
7381 
7382   if (DefKind.isComparison())
7383     UnusedPrivateFields.clear();
7384 
7385   if (DefKind.isSpecialMember()
7386           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7387                                                   DefKind.asSpecialMember())
7388           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7389     FD->setInvalidDecl();
7390 }
7391 
7392 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7393                                                  CXXSpecialMember CSM) {
7394   CXXRecordDecl *RD = MD->getParent();
7395 
7396   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7397          "not an explicitly-defaulted special member");
7398 
7399   // Defer all checking for special members of a dependent type.
7400   if (RD->isDependentType())
7401     return false;
7402 
7403   // Whether this was the first-declared instance of the constructor.
7404   // This affects whether we implicitly add an exception spec and constexpr.
7405   bool First = MD == MD->getCanonicalDecl();
7406 
7407   bool HadError = false;
7408 
7409   // C++11 [dcl.fct.def.default]p1:
7410   //   A function that is explicitly defaulted shall
7411   //     -- be a special member function [...] (checked elsewhere),
7412   //     -- have the same type (except for ref-qualifiers, and except that a
7413   //        copy operation can take a non-const reference) as an implicit
7414   //        declaration, and
7415   //     -- not have default arguments.
7416   // C++2a changes the second bullet to instead delete the function if it's
7417   // defaulted on its first declaration, unless it's "an assignment operator,
7418   // and its return type differs or its parameter type is not a reference".
7419   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7420   bool ShouldDeleteForTypeMismatch = false;
7421   unsigned ExpectedParams = 1;
7422   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7423     ExpectedParams = 0;
7424   if (MD->getNumParams() != ExpectedParams) {
7425     // This checks for default arguments: a copy or move constructor with a
7426     // default argument is classified as a default constructor, and assignment
7427     // operations and destructors can't have default arguments.
7428     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7429       << CSM << MD->getSourceRange();
7430     HadError = true;
7431   } else if (MD->isVariadic()) {
7432     if (DeleteOnTypeMismatch)
7433       ShouldDeleteForTypeMismatch = true;
7434     else {
7435       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7436         << CSM << MD->getSourceRange();
7437       HadError = true;
7438     }
7439   }
7440 
7441   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7442 
7443   bool CanHaveConstParam = false;
7444   if (CSM == CXXCopyConstructor)
7445     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7446   else if (CSM == CXXCopyAssignment)
7447     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7448 
7449   QualType ReturnType = Context.VoidTy;
7450   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7451     // Check for return type matching.
7452     ReturnType = Type->getReturnType();
7453 
7454     QualType DeclType = Context.getTypeDeclType(RD);
7455     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7456     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7457 
7458     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7459       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7460         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7461       HadError = true;
7462     }
7463 
7464     // A defaulted special member cannot have cv-qualifiers.
7465     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7466       if (DeleteOnTypeMismatch)
7467         ShouldDeleteForTypeMismatch = true;
7468       else {
7469         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7470           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7471         HadError = true;
7472       }
7473     }
7474   }
7475 
7476   // Check for parameter type matching.
7477   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7478   bool HasConstParam = false;
7479   if (ExpectedParams && ArgType->isReferenceType()) {
7480     // Argument must be reference to possibly-const T.
7481     QualType ReferentType = ArgType->getPointeeType();
7482     HasConstParam = ReferentType.isConstQualified();
7483 
7484     if (ReferentType.isVolatileQualified()) {
7485       if (DeleteOnTypeMismatch)
7486         ShouldDeleteForTypeMismatch = true;
7487       else {
7488         Diag(MD->getLocation(),
7489              diag::err_defaulted_special_member_volatile_param) << CSM;
7490         HadError = true;
7491       }
7492     }
7493 
7494     if (HasConstParam && !CanHaveConstParam) {
7495       if (DeleteOnTypeMismatch)
7496         ShouldDeleteForTypeMismatch = true;
7497       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7498         Diag(MD->getLocation(),
7499              diag::err_defaulted_special_member_copy_const_param)
7500           << (CSM == CXXCopyAssignment);
7501         // FIXME: Explain why this special member can't be const.
7502         HadError = true;
7503       } else {
7504         Diag(MD->getLocation(),
7505              diag::err_defaulted_special_member_move_const_param)
7506           << (CSM == CXXMoveAssignment);
7507         HadError = true;
7508       }
7509     }
7510   } else if (ExpectedParams) {
7511     // A copy assignment operator can take its argument by value, but a
7512     // defaulted one cannot.
7513     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7514     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7515     HadError = true;
7516   }
7517 
7518   // C++11 [dcl.fct.def.default]p2:
7519   //   An explicitly-defaulted function may be declared constexpr only if it
7520   //   would have been implicitly declared as constexpr,
7521   // Do not apply this rule to members of class templates, since core issue 1358
7522   // makes such functions always instantiate to constexpr functions. For
7523   // functions which cannot be constexpr (for non-constructors in C++11 and for
7524   // destructors in C++14 and C++17), this is checked elsewhere.
7525   //
7526   // FIXME: This should not apply if the member is deleted.
7527   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7528                                                      HasConstParam);
7529   if ((getLangOpts().CPlusPlus20 ||
7530        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7531                                   : isa<CXXConstructorDecl>(MD))) &&
7532       MD->isConstexpr() && !Constexpr &&
7533       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7534     Diag(MD->getBeginLoc(), MD->isConsteval()
7535                                 ? diag::err_incorrect_defaulted_consteval
7536                                 : diag::err_incorrect_defaulted_constexpr)
7537         << CSM;
7538     // FIXME: Explain why the special member can't be constexpr.
7539     HadError = true;
7540   }
7541 
7542   if (First) {
7543     // C++2a [dcl.fct.def.default]p3:
7544     //   If a function is explicitly defaulted on its first declaration, it is
7545     //   implicitly considered to be constexpr if the implicit declaration
7546     //   would be.
7547     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7548                                           ? ConstexprSpecKind::Consteval
7549                                           : ConstexprSpecKind::Constexpr)
7550                                    : ConstexprSpecKind::Unspecified);
7551 
7552     if (!Type->hasExceptionSpec()) {
7553       // C++2a [except.spec]p3:
7554       //   If a declaration of a function does not have a noexcept-specifier
7555       //   [and] is defaulted on its first declaration, [...] the exception
7556       //   specification is as specified below
7557       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7558       EPI.ExceptionSpec.Type = EST_Unevaluated;
7559       EPI.ExceptionSpec.SourceDecl = MD;
7560       MD->setType(Context.getFunctionType(ReturnType,
7561                                           llvm::makeArrayRef(&ArgType,
7562                                                              ExpectedParams),
7563                                           EPI));
7564     }
7565   }
7566 
7567   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7568     if (First) {
7569       SetDeclDeleted(MD, MD->getLocation());
7570       if (!inTemplateInstantiation() && !HadError) {
7571         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7572         if (ShouldDeleteForTypeMismatch) {
7573           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7574         } else {
7575           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7576         }
7577       }
7578       if (ShouldDeleteForTypeMismatch && !HadError) {
7579         Diag(MD->getLocation(),
7580              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7581       }
7582     } else {
7583       // C++11 [dcl.fct.def.default]p4:
7584       //   [For a] user-provided explicitly-defaulted function [...] if such a
7585       //   function is implicitly defined as deleted, the program is ill-formed.
7586       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7587       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7588       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7589       HadError = true;
7590     }
7591   }
7592 
7593   return HadError;
7594 }
7595 
7596 namespace {
7597 /// Helper class for building and checking a defaulted comparison.
7598 ///
7599 /// Defaulted functions are built in two phases:
7600 ///
7601 ///  * First, the set of operations that the function will perform are
7602 ///    identified, and some of them are checked. If any of the checked
7603 ///    operations is invalid in certain ways, the comparison function is
7604 ///    defined as deleted and no body is built.
7605 ///  * Then, if the function is not defined as deleted, the body is built.
7606 ///
7607 /// This is accomplished by performing two visitation steps over the eventual
7608 /// body of the function.
7609 template<typename Derived, typename ResultList, typename Result,
7610          typename Subobject>
7611 class DefaultedComparisonVisitor {
7612 public:
7613   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7614 
7615   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7616                              DefaultedComparisonKind DCK)
7617       : S(S), RD(RD), FD(FD), DCK(DCK) {
7618     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7619       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7620       // UnresolvedSet to avoid this copy.
7621       Fns.assign(Info->getUnqualifiedLookups().begin(),
7622                  Info->getUnqualifiedLookups().end());
7623     }
7624   }
7625 
7626   ResultList visit() {
7627     // The type of an lvalue naming a parameter of this function.
7628     QualType ParamLvalType =
7629         FD->getParamDecl(0)->getType().getNonReferenceType();
7630 
7631     ResultList Results;
7632 
7633     switch (DCK) {
7634     case DefaultedComparisonKind::None:
7635       llvm_unreachable("not a defaulted comparison");
7636 
7637     case DefaultedComparisonKind::Equal:
7638     case DefaultedComparisonKind::ThreeWay:
7639       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7640       return Results;
7641 
7642     case DefaultedComparisonKind::NotEqual:
7643     case DefaultedComparisonKind::Relational:
7644       Results.add(getDerived().visitExpandedSubobject(
7645           ParamLvalType, getDerived().getCompleteObject()));
7646       return Results;
7647     }
7648     llvm_unreachable("");
7649   }
7650 
7651 protected:
7652   Derived &getDerived() { return static_cast<Derived&>(*this); }
7653 
7654   /// Visit the expanded list of subobjects of the given type, as specified in
7655   /// C++2a [class.compare.default].
7656   ///
7657   /// \return \c true if the ResultList object said we're done, \c false if not.
7658   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7659                        Qualifiers Quals) {
7660     // C++2a [class.compare.default]p4:
7661     //   The direct base class subobjects of C
7662     for (CXXBaseSpecifier &Base : Record->bases())
7663       if (Results.add(getDerived().visitSubobject(
7664               S.Context.getQualifiedType(Base.getType(), Quals),
7665               getDerived().getBase(&Base))))
7666         return true;
7667 
7668     //   followed by the non-static data members of C
7669     for (FieldDecl *Field : Record->fields()) {
7670       // Recursively expand anonymous structs.
7671       if (Field->isAnonymousStructOrUnion()) {
7672         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7673                             Quals))
7674           return true;
7675         continue;
7676       }
7677 
7678       // Figure out the type of an lvalue denoting this field.
7679       Qualifiers FieldQuals = Quals;
7680       if (Field->isMutable())
7681         FieldQuals.removeConst();
7682       QualType FieldType =
7683           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7684 
7685       if (Results.add(getDerived().visitSubobject(
7686               FieldType, getDerived().getField(Field))))
7687         return true;
7688     }
7689 
7690     //   form a list of subobjects.
7691     return false;
7692   }
7693 
7694   Result visitSubobject(QualType Type, Subobject Subobj) {
7695     //   In that list, any subobject of array type is recursively expanded
7696     const ArrayType *AT = S.Context.getAsArrayType(Type);
7697     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7698       return getDerived().visitSubobjectArray(CAT->getElementType(),
7699                                               CAT->getSize(), Subobj);
7700     return getDerived().visitExpandedSubobject(Type, Subobj);
7701   }
7702 
7703   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7704                              Subobject Subobj) {
7705     return getDerived().visitSubobject(Type, Subobj);
7706   }
7707 
7708 protected:
7709   Sema &S;
7710   CXXRecordDecl *RD;
7711   FunctionDecl *FD;
7712   DefaultedComparisonKind DCK;
7713   UnresolvedSet<16> Fns;
7714 };
7715 
7716 /// Information about a defaulted comparison, as determined by
7717 /// DefaultedComparisonAnalyzer.
7718 struct DefaultedComparisonInfo {
7719   bool Deleted = false;
7720   bool Constexpr = true;
7721   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7722 
7723   static DefaultedComparisonInfo deleted() {
7724     DefaultedComparisonInfo Deleted;
7725     Deleted.Deleted = true;
7726     return Deleted;
7727   }
7728 
7729   bool add(const DefaultedComparisonInfo &R) {
7730     Deleted |= R.Deleted;
7731     Constexpr &= R.Constexpr;
7732     Category = commonComparisonType(Category, R.Category);
7733     return Deleted;
7734   }
7735 };
7736 
7737 /// An element in the expanded list of subobjects of a defaulted comparison, as
7738 /// specified in C++2a [class.compare.default]p4.
7739 struct DefaultedComparisonSubobject {
7740   enum { CompleteObject, Member, Base } Kind;
7741   NamedDecl *Decl;
7742   SourceLocation Loc;
7743 };
7744 
7745 /// A visitor over the notional body of a defaulted comparison that determines
7746 /// whether that body would be deleted or constexpr.
7747 class DefaultedComparisonAnalyzer
7748     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7749                                         DefaultedComparisonInfo,
7750                                         DefaultedComparisonInfo,
7751                                         DefaultedComparisonSubobject> {
7752 public:
7753   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7754 
7755 private:
7756   DiagnosticKind Diagnose;
7757 
7758 public:
7759   using Base = DefaultedComparisonVisitor;
7760   using Result = DefaultedComparisonInfo;
7761   using Subobject = DefaultedComparisonSubobject;
7762 
7763   friend Base;
7764 
7765   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7766                               DefaultedComparisonKind DCK,
7767                               DiagnosticKind Diagnose = NoDiagnostics)
7768       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7769 
7770   Result visit() {
7771     if ((DCK == DefaultedComparisonKind::Equal ||
7772          DCK == DefaultedComparisonKind::ThreeWay) &&
7773         RD->hasVariantMembers()) {
7774       // C++2a [class.compare.default]p2 [P2002R0]:
7775       //   A defaulted comparison operator function for class C is defined as
7776       //   deleted if [...] C has variant members.
7777       if (Diagnose == ExplainDeleted) {
7778         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7779           << FD << RD->isUnion() << RD;
7780       }
7781       return Result::deleted();
7782     }
7783 
7784     return Base::visit();
7785   }
7786 
7787 private:
7788   Subobject getCompleteObject() {
7789     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7790   }
7791 
7792   Subobject getBase(CXXBaseSpecifier *Base) {
7793     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7794                      Base->getBaseTypeLoc()};
7795   }
7796 
7797   Subobject getField(FieldDecl *Field) {
7798     return Subobject{Subobject::Member, Field, Field->getLocation()};
7799   }
7800 
7801   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7802     // C++2a [class.compare.default]p2 [P2002R0]:
7803     //   A defaulted <=> or == operator function for class C is defined as
7804     //   deleted if any non-static data member of C is of reference type
7805     if (Type->isReferenceType()) {
7806       if (Diagnose == ExplainDeleted) {
7807         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7808             << FD << RD;
7809       }
7810       return Result::deleted();
7811     }
7812 
7813     // [...] Let xi be an lvalue denoting the ith element [...]
7814     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7815     Expr *Args[] = {&Xi, &Xi};
7816 
7817     // All operators start by trying to apply that same operator recursively.
7818     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7819     assert(OO != OO_None && "not an overloaded operator!");
7820     return visitBinaryOperator(OO, Args, Subobj);
7821   }
7822 
7823   Result
7824   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7825                       Subobject Subobj,
7826                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7827     // Note that there is no need to consider rewritten candidates here if
7828     // we've already found there is no viable 'operator<=>' candidate (and are
7829     // considering synthesizing a '<=>' from '==' and '<').
7830     OverloadCandidateSet CandidateSet(
7831         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7832         OverloadCandidateSet::OperatorRewriteInfo(
7833             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7834 
7835     /// C++2a [class.compare.default]p1 [P2002R0]:
7836     ///   [...] the defaulted function itself is never a candidate for overload
7837     ///   resolution [...]
7838     CandidateSet.exclude(FD);
7839 
7840     if (Args[0]->getType()->isOverloadableType())
7841       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7842     else
7843       // FIXME: We determine whether this is a valid expression by checking to
7844       // see if there's a viable builtin operator candidate for it. That isn't
7845       // really what the rules ask us to do, but should give the right results.
7846       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7847 
7848     Result R;
7849 
7850     OverloadCandidateSet::iterator Best;
7851     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7852     case OR_Success: {
7853       // C++2a [class.compare.secondary]p2 [P2002R0]:
7854       //   The operator function [...] is defined as deleted if [...] the
7855       //   candidate selected by overload resolution is not a rewritten
7856       //   candidate.
7857       if ((DCK == DefaultedComparisonKind::NotEqual ||
7858            DCK == DefaultedComparisonKind::Relational) &&
7859           !Best->RewriteKind) {
7860         if (Diagnose == ExplainDeleted) {
7861           if (Best->Function) {
7862             S.Diag(Best->Function->getLocation(),
7863                    diag::note_defaulted_comparison_not_rewritten_callee)
7864                 << FD;
7865           } else {
7866             assert(Best->Conversions.size() == 2 &&
7867                    Best->Conversions[0].isUserDefined() &&
7868                    "non-user-defined conversion from class to built-in "
7869                    "comparison");
7870             S.Diag(Best->Conversions[0]
7871                        .UserDefined.FoundConversionFunction.getDecl()
7872                        ->getLocation(),
7873                    diag::note_defaulted_comparison_not_rewritten_conversion)
7874                 << FD;
7875           }
7876         }
7877         return Result::deleted();
7878       }
7879 
7880       // Throughout C++2a [class.compare]: if overload resolution does not
7881       // result in a usable function, the candidate function is defined as
7882       // deleted. This requires that we selected an accessible function.
7883       //
7884       // Note that this only considers the access of the function when named
7885       // within the type of the subobject, and not the access path for any
7886       // derived-to-base conversion.
7887       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7888       if (ArgClass && Best->FoundDecl.getDecl() &&
7889           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7890         QualType ObjectType = Subobj.Kind == Subobject::Member
7891                                   ? Args[0]->getType()
7892                                   : S.Context.getRecordType(RD);
7893         if (!S.isMemberAccessibleForDeletion(
7894                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7895                 Diagnose == ExplainDeleted
7896                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7897                           << FD << Subobj.Kind << Subobj.Decl
7898                     : S.PDiag()))
7899           return Result::deleted();
7900       }
7901 
7902       bool NeedsDeducing =
7903           OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7904 
7905       if (FunctionDecl *BestFD = Best->Function) {
7906         // C++2a [class.compare.default]p3 [P2002R0]:
7907         //   A defaulted comparison function is constexpr-compatible if
7908         //   [...] no overlod resolution performed [...] results in a
7909         //   non-constexpr function.
7910         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7911         // If it's not constexpr, explain why not.
7912         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7913           if (Subobj.Kind != Subobject::CompleteObject)
7914             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7915               << Subobj.Kind << Subobj.Decl;
7916           S.Diag(BestFD->getLocation(),
7917                  diag::note_defaulted_comparison_not_constexpr_here);
7918           // Bail out after explaining; we don't want any more notes.
7919           return Result::deleted();
7920         }
7921         R.Constexpr &= BestFD->isConstexpr();
7922 
7923         if (NeedsDeducing) {
7924           // If any callee has an undeduced return type, deduce it now.
7925           // FIXME: It's not clear how a failure here should be handled. For
7926           // now, we produce an eager diagnostic, because that is forward
7927           // compatible with most (all?) other reasonable options.
7928           if (BestFD->getReturnType()->isUndeducedType() &&
7929               S.DeduceReturnType(BestFD, FD->getLocation(),
7930                                  /*Diagnose=*/false)) {
7931             // Don't produce a duplicate error when asked to explain why the
7932             // comparison is deleted: we diagnosed that when initially checking
7933             // the defaulted operator.
7934             if (Diagnose == NoDiagnostics) {
7935               S.Diag(
7936                   FD->getLocation(),
7937                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7938                   << Subobj.Kind << Subobj.Decl;
7939               S.Diag(
7940                   Subobj.Loc,
7941                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7942                   << Subobj.Kind << Subobj.Decl;
7943               S.Diag(BestFD->getLocation(),
7944                      diag::note_defaulted_comparison_cannot_deduce_callee)
7945                   << Subobj.Kind << Subobj.Decl;
7946             }
7947             return Result::deleted();
7948           }
7949           auto *Info = S.Context.CompCategories.lookupInfoForType(
7950               BestFD->getCallResultType());
7951           if (!Info) {
7952             if (Diagnose == ExplainDeleted) {
7953               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7954                   << Subobj.Kind << Subobj.Decl
7955                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7956               S.Diag(BestFD->getLocation(),
7957                      diag::note_defaulted_comparison_cannot_deduce_callee)
7958                   << Subobj.Kind << Subobj.Decl;
7959             }
7960             return Result::deleted();
7961           }
7962           R.Category = Info->Kind;
7963         }
7964       } else {
7965         QualType T = Best->BuiltinParamTypes[0];
7966         assert(T == Best->BuiltinParamTypes[1] &&
7967                "builtin comparison for different types?");
7968         assert(Best->BuiltinParamTypes[2].isNull() &&
7969                "invalid builtin comparison");
7970 
7971         if (NeedsDeducing) {
7972           Optional<ComparisonCategoryType> Cat =
7973               getComparisonCategoryForBuiltinCmp(T);
7974           assert(Cat && "no category for builtin comparison?");
7975           R.Category = *Cat;
7976         }
7977       }
7978 
7979       // Note that we might be rewriting to a different operator. That call is
7980       // not considered until we come to actually build the comparison function.
7981       break;
7982     }
7983 
7984     case OR_Ambiguous:
7985       if (Diagnose == ExplainDeleted) {
7986         unsigned Kind = 0;
7987         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7988           Kind = OO == OO_EqualEqual ? 1 : 2;
7989         CandidateSet.NoteCandidates(
7990             PartialDiagnosticAt(
7991                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7992                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7993             S, OCD_AmbiguousCandidates, Args);
7994       }
7995       R = Result::deleted();
7996       break;
7997 
7998     case OR_Deleted:
7999       if (Diagnose == ExplainDeleted) {
8000         if ((DCK == DefaultedComparisonKind::NotEqual ||
8001              DCK == DefaultedComparisonKind::Relational) &&
8002             !Best->RewriteKind) {
8003           S.Diag(Best->Function->getLocation(),
8004                  diag::note_defaulted_comparison_not_rewritten_callee)
8005               << FD;
8006         } else {
8007           S.Diag(Subobj.Loc,
8008                  diag::note_defaulted_comparison_calls_deleted)
8009               << FD << Subobj.Kind << Subobj.Decl;
8010           S.NoteDeletedFunction(Best->Function);
8011         }
8012       }
8013       R = Result::deleted();
8014       break;
8015 
8016     case OR_No_Viable_Function:
8017       // If there's no usable candidate, we're done unless we can rewrite a
8018       // '<=>' in terms of '==' and '<'.
8019       if (OO == OO_Spaceship &&
8020           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8021         // For any kind of comparison category return type, we need a usable
8022         // '==' and a usable '<'.
8023         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8024                                        &CandidateSet)))
8025           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8026         break;
8027       }
8028 
8029       if (Diagnose == ExplainDeleted) {
8030         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8031             << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
8032 
8033         // For a three-way comparison, list both the candidates for the
8034         // original operator and the candidates for the synthesized operator.
8035         if (SpaceshipCandidates) {
8036           SpaceshipCandidates->NoteCandidates(
8037               S, Args,
8038               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8039                                                       Args, FD->getLocation()));
8040           S.Diag(Subobj.Loc,
8041                  diag::note_defaulted_comparison_no_viable_function_synthesized)
8042               << (OO == OO_EqualEqual ? 0 : 1);
8043         }
8044 
8045         CandidateSet.NoteCandidates(
8046             S, Args,
8047             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8048                                             FD->getLocation()));
8049       }
8050       R = Result::deleted();
8051       break;
8052     }
8053 
8054     return R;
8055   }
8056 };
8057 
8058 /// A list of statements.
8059 struct StmtListResult {
8060   bool IsInvalid = false;
8061   llvm::SmallVector<Stmt*, 16> Stmts;
8062 
8063   bool add(const StmtResult &S) {
8064     IsInvalid |= S.isInvalid();
8065     if (IsInvalid)
8066       return true;
8067     Stmts.push_back(S.get());
8068     return false;
8069   }
8070 };
8071 
8072 /// A visitor over the notional body of a defaulted comparison that synthesizes
8073 /// the actual body.
8074 class DefaultedComparisonSynthesizer
8075     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8076                                         StmtListResult, StmtResult,
8077                                         std::pair<ExprResult, ExprResult>> {
8078   SourceLocation Loc;
8079   unsigned ArrayDepth = 0;
8080 
8081 public:
8082   using Base = DefaultedComparisonVisitor;
8083   using ExprPair = std::pair<ExprResult, ExprResult>;
8084 
8085   friend Base;
8086 
8087   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8088                                  DefaultedComparisonKind DCK,
8089                                  SourceLocation BodyLoc)
8090       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8091 
8092   /// Build a suitable function body for this defaulted comparison operator.
8093   StmtResult build() {
8094     Sema::CompoundScopeRAII CompoundScope(S);
8095 
8096     StmtListResult Stmts = visit();
8097     if (Stmts.IsInvalid)
8098       return StmtError();
8099 
8100     ExprResult RetVal;
8101     switch (DCK) {
8102     case DefaultedComparisonKind::None:
8103       llvm_unreachable("not a defaulted comparison");
8104 
8105     case DefaultedComparisonKind::Equal: {
8106       // C++2a [class.eq]p3:
8107       //   [...] compar[e] the corresponding elements [...] until the first
8108       //   index i where xi == yi yields [...] false. If no such index exists,
8109       //   V is true. Otherwise, V is false.
8110       //
8111       // Join the comparisons with '&&'s and return the result. Use a right
8112       // fold (traversing the conditions right-to-left), because that
8113       // short-circuits more naturally.
8114       auto OldStmts = std::move(Stmts.Stmts);
8115       Stmts.Stmts.clear();
8116       ExprResult CmpSoFar;
8117       // Finish a particular comparison chain.
8118       auto FinishCmp = [&] {
8119         if (Expr *Prior = CmpSoFar.get()) {
8120           // Convert the last expression to 'return ...;'
8121           if (RetVal.isUnset() && Stmts.Stmts.empty())
8122             RetVal = CmpSoFar;
8123           // Convert any prior comparison to 'if (!(...)) return false;'
8124           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8125             return true;
8126           CmpSoFar = ExprResult();
8127         }
8128         return false;
8129       };
8130       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8131         Expr *E = dyn_cast<Expr>(EAsStmt);
8132         if (!E) {
8133           // Found an array comparison.
8134           if (FinishCmp() || Stmts.add(EAsStmt))
8135             return StmtError();
8136           continue;
8137         }
8138 
8139         if (CmpSoFar.isUnset()) {
8140           CmpSoFar = E;
8141           continue;
8142         }
8143         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8144         if (CmpSoFar.isInvalid())
8145           return StmtError();
8146       }
8147       if (FinishCmp())
8148         return StmtError();
8149       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8150       //   If no such index exists, V is true.
8151       if (RetVal.isUnset())
8152         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8153       break;
8154     }
8155 
8156     case DefaultedComparisonKind::ThreeWay: {
8157       // Per C++2a [class.spaceship]p3, as a fallback add:
8158       // return static_cast<R>(std::strong_ordering::equal);
8159       QualType StrongOrdering = S.CheckComparisonCategoryType(
8160           ComparisonCategoryType::StrongOrdering, Loc,
8161           Sema::ComparisonCategoryUsage::DefaultedOperator);
8162       if (StrongOrdering.isNull())
8163         return StmtError();
8164       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8165                              .getValueInfo(ComparisonCategoryResult::Equal)
8166                              ->VD;
8167       RetVal = getDecl(EqualVD);
8168       if (RetVal.isInvalid())
8169         return StmtError();
8170       RetVal = buildStaticCastToR(RetVal.get());
8171       break;
8172     }
8173 
8174     case DefaultedComparisonKind::NotEqual:
8175     case DefaultedComparisonKind::Relational:
8176       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8177       break;
8178     }
8179 
8180     // Build the final return statement.
8181     if (RetVal.isInvalid())
8182       return StmtError();
8183     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8184     if (ReturnStmt.isInvalid())
8185       return StmtError();
8186     Stmts.Stmts.push_back(ReturnStmt.get());
8187 
8188     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8189   }
8190 
8191 private:
8192   ExprResult getDecl(ValueDecl *VD) {
8193     return S.BuildDeclarationNameExpr(
8194         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8195   }
8196 
8197   ExprResult getParam(unsigned I) {
8198     ParmVarDecl *PD = FD->getParamDecl(I);
8199     return getDecl(PD);
8200   }
8201 
8202   ExprPair getCompleteObject() {
8203     unsigned Param = 0;
8204     ExprResult LHS;
8205     if (isa<CXXMethodDecl>(FD)) {
8206       // LHS is '*this'.
8207       LHS = S.ActOnCXXThis(Loc);
8208       if (!LHS.isInvalid())
8209         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8210     } else {
8211       LHS = getParam(Param++);
8212     }
8213     ExprResult RHS = getParam(Param++);
8214     assert(Param == FD->getNumParams());
8215     return {LHS, RHS};
8216   }
8217 
8218   ExprPair getBase(CXXBaseSpecifier *Base) {
8219     ExprPair Obj = getCompleteObject();
8220     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8221       return {ExprError(), ExprError()};
8222     CXXCastPath Path = {Base};
8223     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8224                                 CK_DerivedToBase, VK_LValue, &Path),
8225             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8226                                 CK_DerivedToBase, VK_LValue, &Path)};
8227   }
8228 
8229   ExprPair getField(FieldDecl *Field) {
8230     ExprPair Obj = getCompleteObject();
8231     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8232       return {ExprError(), ExprError()};
8233 
8234     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8235     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8236     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8237                                       CXXScopeSpec(), Field, Found, NameInfo),
8238             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8239                                       CXXScopeSpec(), Field, Found, NameInfo)};
8240   }
8241 
8242   // FIXME: When expanding a subobject, register a note in the code synthesis
8243   // stack to say which subobject we're comparing.
8244 
8245   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8246     if (Cond.isInvalid())
8247       return StmtError();
8248 
8249     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8250     if (NotCond.isInvalid())
8251       return StmtError();
8252 
8253     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8254     assert(!False.isInvalid() && "should never fail");
8255     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8256     if (ReturnFalse.isInvalid())
8257       return StmtError();
8258 
8259     return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8260                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8261                                           Sema::ConditionKind::Boolean),
8262                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8263   }
8264 
8265   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8266                                  ExprPair Subobj) {
8267     QualType SizeType = S.Context.getSizeType();
8268     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8269 
8270     // Build 'size_t i$n = 0'.
8271     IdentifierInfo *IterationVarName = nullptr;
8272     {
8273       SmallString<8> Str;
8274       llvm::raw_svector_ostream OS(Str);
8275       OS << "i" << ArrayDepth;
8276       IterationVarName = &S.Context.Idents.get(OS.str());
8277     }
8278     VarDecl *IterationVar = VarDecl::Create(
8279         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8280         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8281     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8282     IterationVar->setInit(
8283         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8284     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8285 
8286     auto IterRef = [&] {
8287       ExprResult Ref = S.BuildDeclarationNameExpr(
8288           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8289           IterationVar);
8290       assert(!Ref.isInvalid() && "can't reference our own variable?");
8291       return Ref.get();
8292     };
8293 
8294     // Build 'i$n != Size'.
8295     ExprResult Cond = S.CreateBuiltinBinOp(
8296         Loc, BO_NE, IterRef(),
8297         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8298     assert(!Cond.isInvalid() && "should never fail");
8299 
8300     // Build '++i$n'.
8301     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8302     assert(!Inc.isInvalid() && "should never fail");
8303 
8304     // Build 'a[i$n]' and 'b[i$n]'.
8305     auto Index = [&](ExprResult E) {
8306       if (E.isInvalid())
8307         return ExprError();
8308       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8309     };
8310     Subobj.first = Index(Subobj.first);
8311     Subobj.second = Index(Subobj.second);
8312 
8313     // Compare the array elements.
8314     ++ArrayDepth;
8315     StmtResult Substmt = visitSubobject(Type, Subobj);
8316     --ArrayDepth;
8317 
8318     if (Substmt.isInvalid())
8319       return StmtError();
8320 
8321     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8322     // For outer levels or for an 'operator<=>' we already have a suitable
8323     // statement that returns as necessary.
8324     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8325       assert(DCK == DefaultedComparisonKind::Equal &&
8326              "should have non-expression statement");
8327       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8328       if (Substmt.isInvalid())
8329         return StmtError();
8330     }
8331 
8332     // Build 'for (...) ...'
8333     return S.ActOnForStmt(Loc, Loc, Init,
8334                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8335                                            Sema::ConditionKind::Boolean),
8336                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8337                           Substmt.get());
8338   }
8339 
8340   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8341     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8342       return StmtError();
8343 
8344     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8345     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8346     ExprResult Op;
8347     if (Type->isOverloadableType())
8348       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8349                                    Obj.second.get(), /*PerformADL=*/true,
8350                                    /*AllowRewrittenCandidates=*/true, FD);
8351     else
8352       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8353     if (Op.isInvalid())
8354       return StmtError();
8355 
8356     switch (DCK) {
8357     case DefaultedComparisonKind::None:
8358       llvm_unreachable("not a defaulted comparison");
8359 
8360     case DefaultedComparisonKind::Equal:
8361       // Per C++2a [class.eq]p2, each comparison is individually contextually
8362       // converted to bool.
8363       Op = S.PerformContextuallyConvertToBool(Op.get());
8364       if (Op.isInvalid())
8365         return StmtError();
8366       return Op.get();
8367 
8368     case DefaultedComparisonKind::ThreeWay: {
8369       // Per C++2a [class.spaceship]p3, form:
8370       //   if (R cmp = static_cast<R>(op); cmp != 0)
8371       //     return cmp;
8372       QualType R = FD->getReturnType();
8373       Op = buildStaticCastToR(Op.get());
8374       if (Op.isInvalid())
8375         return StmtError();
8376 
8377       // R cmp = ...;
8378       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8379       VarDecl *VD =
8380           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8381                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8382       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8383       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8384 
8385       // cmp != 0
8386       ExprResult VDRef = getDecl(VD);
8387       if (VDRef.isInvalid())
8388         return StmtError();
8389       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8390       Expr *Zero =
8391           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8392       ExprResult Comp;
8393       if (VDRef.get()->getType()->isOverloadableType())
8394         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8395                                        true, FD);
8396       else
8397         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8398       if (Comp.isInvalid())
8399         return StmtError();
8400       Sema::ConditionResult Cond = S.ActOnCondition(
8401           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8402       if (Cond.isInvalid())
8403         return StmtError();
8404 
8405       // return cmp;
8406       VDRef = getDecl(VD);
8407       if (VDRef.isInvalid())
8408         return StmtError();
8409       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8410       if (ReturnStmt.isInvalid())
8411         return StmtError();
8412 
8413       // if (...)
8414       return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8415                            Loc, ReturnStmt.get(),
8416                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8417     }
8418 
8419     case DefaultedComparisonKind::NotEqual:
8420     case DefaultedComparisonKind::Relational:
8421       // C++2a [class.compare.secondary]p2:
8422       //   Otherwise, the operator function yields x @ y.
8423       return Op.get();
8424     }
8425     llvm_unreachable("");
8426   }
8427 
8428   /// Build "static_cast<R>(E)".
8429   ExprResult buildStaticCastToR(Expr *E) {
8430     QualType R = FD->getReturnType();
8431     assert(!R->isUndeducedType() && "type should have been deduced already");
8432 
8433     // Don't bother forming a no-op cast in the common case.
8434     if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8435       return E;
8436     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8437                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8438                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8439   }
8440 };
8441 }
8442 
8443 /// Perform the unqualified lookups that might be needed to form a defaulted
8444 /// comparison function for the given operator.
8445 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8446                                                   UnresolvedSetImpl &Operators,
8447                                                   OverloadedOperatorKind Op) {
8448   auto Lookup = [&](OverloadedOperatorKind OO) {
8449     Self.LookupOverloadedOperatorName(OO, S, Operators);
8450   };
8451 
8452   // Every defaulted operator looks up itself.
8453   Lookup(Op);
8454   // ... and the rewritten form of itself, if any.
8455   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8456     Lookup(ExtraOp);
8457 
8458   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8459   // synthesize a three-way comparison from '<' and '=='. In a dependent
8460   // context, we also need to look up '==' in case we implicitly declare a
8461   // defaulted 'operator=='.
8462   if (Op == OO_Spaceship) {
8463     Lookup(OO_ExclaimEqual);
8464     Lookup(OO_Less);
8465     Lookup(OO_EqualEqual);
8466   }
8467 }
8468 
8469 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8470                                               DefaultedComparisonKind DCK) {
8471   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8472 
8473   // Perform any unqualified lookups we're going to need to default this
8474   // function.
8475   if (S) {
8476     UnresolvedSet<32> Operators;
8477     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8478                                           FD->getOverloadedOperator());
8479     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8480         Context, Operators.pairs()));
8481   }
8482 
8483   // C++2a [class.compare.default]p1:
8484   //   A defaulted comparison operator function for some class C shall be a
8485   //   non-template function declared in the member-specification of C that is
8486   //    -- a non-static const member of C having one parameter of type
8487   //       const C&, or
8488   //    -- a friend of C having two parameters of type const C& or two
8489   //       parameters of type C.
8490 
8491   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8492   bool IsMethod = isa<CXXMethodDecl>(FD);
8493   if (IsMethod) {
8494     auto *MD = cast<CXXMethodDecl>(FD);
8495     assert(!MD->isStatic() && "comparison function cannot be a static member");
8496 
8497     // If we're out-of-class, this is the class we're comparing.
8498     if (!RD)
8499       RD = MD->getParent();
8500 
8501     if (!MD->isConst()) {
8502       SourceLocation InsertLoc;
8503       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8504         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8505       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8506       // corresponding defaulted 'operator<=>' already.
8507       if (!MD->isImplicit()) {
8508         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8509             << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8510       }
8511 
8512       // Add the 'const' to the type to recover.
8513       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8514       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8515       EPI.TypeQuals.addConst();
8516       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8517                                           FPT->getParamTypes(), EPI));
8518     }
8519   }
8520 
8521   if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8522     // Let's not worry about using a variadic template pack here -- who would do
8523     // such a thing?
8524     Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8525         << int(IsMethod) << int(DCK);
8526     return true;
8527   }
8528 
8529   const ParmVarDecl *KnownParm = nullptr;
8530   for (const ParmVarDecl *Param : FD->parameters()) {
8531     QualType ParmTy = Param->getType();
8532     if (ParmTy->isDependentType())
8533       continue;
8534     if (!KnownParm) {
8535       auto CTy = ParmTy;
8536       // Is it `T const &`?
8537       bool Ok = !IsMethod;
8538       QualType ExpectedTy;
8539       if (RD)
8540         ExpectedTy = Context.getRecordType(RD);
8541       if (auto *Ref = CTy->getAs<ReferenceType>()) {
8542         CTy = Ref->getPointeeType();
8543         if (RD)
8544           ExpectedTy.addConst();
8545         Ok = true;
8546       }
8547 
8548       // Is T a class?
8549       if (!Ok) {
8550       } else if (RD) {
8551         if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8552           Ok = false;
8553       } else if (auto *CRD = CTy->getAsRecordDecl()) {
8554         RD = cast<CXXRecordDecl>(CRD);
8555       } else {
8556         Ok = false;
8557       }
8558 
8559       if (Ok) {
8560         KnownParm = Param;
8561       } else {
8562         // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8563         // corresponding defaulted 'operator<=>' already.
8564         if (!FD->isImplicit()) {
8565           if (RD) {
8566             QualType PlainTy = Context.getRecordType(RD);
8567             QualType RefTy =
8568                 Context.getLValueReferenceType(PlainTy.withConst());
8569             Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8570                 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8571                 << Param->getSourceRange();
8572           } else {
8573             assert(!IsMethod && "should know expected type for method");
8574             Diag(FD->getLocation(),
8575                  diag::err_defaulted_comparison_param_unknown)
8576                 << int(DCK) << ParmTy << Param->getSourceRange();
8577           }
8578         }
8579         return true;
8580       }
8581     } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8582       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8583           << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8584           << ParmTy << Param->getSourceRange();
8585       return true;
8586     }
8587   }
8588 
8589   assert(RD && "must have determined class");
8590   if (IsMethod) {
8591   } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8592     // In-class, must be a friend decl.
8593     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8594   } else {
8595     // Out of class, require the defaulted comparison to be a friend (of a
8596     // complete type).
8597     if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8598                             diag::err_defaulted_comparison_not_friend, int(DCK),
8599                             int(1)))
8600       return true;
8601 
8602     if (llvm::find_if(RD->friends(), [&](const FriendDecl *F) {
8603           return FD->getCanonicalDecl() ==
8604                  F->getFriendDecl()->getCanonicalDecl();
8605         }) == RD->friends().end()) {
8606       Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8607           << int(DCK) << int(0) << RD;
8608       Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8609       return true;
8610     }
8611   }
8612 
8613   // C++2a [class.eq]p1, [class.rel]p1:
8614   //   A [defaulted comparison other than <=>] shall have a declared return
8615   //   type bool.
8616   if (DCK != DefaultedComparisonKind::ThreeWay &&
8617       !FD->getDeclaredReturnType()->isDependentType() &&
8618       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8619     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8620         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8621         << FD->getReturnTypeSourceRange();
8622     return true;
8623   }
8624   // C++2a [class.spaceship]p2 [P2002R0]:
8625   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8626   //   R shall not contain a placeholder type.
8627   if (DCK == DefaultedComparisonKind::ThreeWay &&
8628       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8629       !Context.hasSameType(FD->getDeclaredReturnType(),
8630                            Context.getAutoDeductType())) {
8631     Diag(FD->getLocation(),
8632          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8633         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8634         << FD->getReturnTypeSourceRange();
8635     return true;
8636   }
8637 
8638   // For a defaulted function in a dependent class, defer all remaining checks
8639   // until instantiation.
8640   if (RD->isDependentType())
8641     return false;
8642 
8643   // Determine whether the function should be defined as deleted.
8644   DefaultedComparisonInfo Info =
8645       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8646 
8647   bool First = FD == FD->getCanonicalDecl();
8648 
8649   // If we want to delete the function, then do so; there's nothing else to
8650   // check in that case.
8651   if (Info.Deleted) {
8652     if (!First) {
8653       // C++11 [dcl.fct.def.default]p4:
8654       //   [For a] user-provided explicitly-defaulted function [...] if such a
8655       //   function is implicitly defined as deleted, the program is ill-formed.
8656       //
8657       // This is really just a consequence of the general rule that you can
8658       // only delete a function on its first declaration.
8659       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8660           << FD->isImplicit() << (int)DCK;
8661       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8662                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8663           .visit();
8664       return true;
8665     }
8666 
8667     SetDeclDeleted(FD, FD->getLocation());
8668     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8669       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8670           << (int)DCK;
8671       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8672                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8673           .visit();
8674     }
8675     return false;
8676   }
8677 
8678   // C++2a [class.spaceship]p2:
8679   //   The return type is deduced as the common comparison type of R0, R1, ...
8680   if (DCK == DefaultedComparisonKind::ThreeWay &&
8681       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8682     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8683     if (RetLoc.isInvalid())
8684       RetLoc = FD->getBeginLoc();
8685     // FIXME: Should we really care whether we have the complete type and the
8686     // 'enumerator' constants here? A forward declaration seems sufficient.
8687     QualType Cat = CheckComparisonCategoryType(
8688         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8689     if (Cat.isNull())
8690       return true;
8691     Context.adjustDeducedFunctionResultType(
8692         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8693   }
8694 
8695   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8696   //   An explicitly-defaulted function that is not defined as deleted may be
8697   //   declared constexpr or consteval only if it is constexpr-compatible.
8698   // C++2a [class.compare.default]p3 [P2002R0]:
8699   //   A defaulted comparison function is constexpr-compatible if it satisfies
8700   //   the requirements for a constexpr function [...]
8701   // The only relevant requirements are that the parameter and return types are
8702   // literal types. The remaining conditions are checked by the analyzer.
8703   if (FD->isConstexpr()) {
8704     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8705         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8706         !Info.Constexpr) {
8707       Diag(FD->getBeginLoc(),
8708            diag::err_incorrect_defaulted_comparison_constexpr)
8709           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8710       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8711                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8712           .visit();
8713     }
8714   }
8715 
8716   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8717   //   If a constexpr-compatible function is explicitly defaulted on its first
8718   //   declaration, it is implicitly considered to be constexpr.
8719   // FIXME: Only applying this to the first declaration seems problematic, as
8720   // simple reorderings can affect the meaning of the program.
8721   if (First && !FD->isConstexpr() && Info.Constexpr)
8722     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8723 
8724   // C++2a [except.spec]p3:
8725   //   If a declaration of a function does not have a noexcept-specifier
8726   //   [and] is defaulted on its first declaration, [...] the exception
8727   //   specification is as specified below
8728   if (FD->getExceptionSpecType() == EST_None) {
8729     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8730     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8731     EPI.ExceptionSpec.Type = EST_Unevaluated;
8732     EPI.ExceptionSpec.SourceDecl = FD;
8733     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8734                                         FPT->getParamTypes(), EPI));
8735   }
8736 
8737   return false;
8738 }
8739 
8740 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8741                                              FunctionDecl *Spaceship) {
8742   Sema::CodeSynthesisContext Ctx;
8743   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8744   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8745   Ctx.Entity = Spaceship;
8746   pushCodeSynthesisContext(Ctx);
8747 
8748   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8749     EqualEqual->setImplicit();
8750 
8751   popCodeSynthesisContext();
8752 }
8753 
8754 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8755                                      DefaultedComparisonKind DCK) {
8756   assert(FD->isDefaulted() && !FD->isDeleted() &&
8757          !FD->doesThisDeclarationHaveABody());
8758   if (FD->willHaveBody() || FD->isInvalidDecl())
8759     return;
8760 
8761   SynthesizedFunctionScope Scope(*this, FD);
8762 
8763   // Add a context note for diagnostics produced after this point.
8764   Scope.addContextNote(UseLoc);
8765 
8766   {
8767     // Build and set up the function body.
8768     // The first parameter has type maybe-ref-to maybe-const T, use that to get
8769     // the type of the class being compared.
8770     auto PT = FD->getParamDecl(0)->getType();
8771     CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
8772     SourceLocation BodyLoc =
8773         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8774     StmtResult Body =
8775         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8776     if (Body.isInvalid()) {
8777       FD->setInvalidDecl();
8778       return;
8779     }
8780     FD->setBody(Body.get());
8781     FD->markUsed(Context);
8782   }
8783 
8784   // The exception specification is needed because we are defining the
8785   // function. Note that this will reuse the body we just built.
8786   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8787 
8788   if (ASTMutationListener *L = getASTMutationListener())
8789     L->CompletedImplicitDefinition(FD);
8790 }
8791 
8792 static Sema::ImplicitExceptionSpecification
8793 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8794                                         FunctionDecl *FD,
8795                                         Sema::DefaultedComparisonKind DCK) {
8796   ComputingExceptionSpec CES(S, FD, Loc);
8797   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8798 
8799   if (FD->isInvalidDecl())
8800     return ExceptSpec;
8801 
8802   // The common case is that we just defined the comparison function. In that
8803   // case, just look at whether the body can throw.
8804   if (FD->hasBody()) {
8805     ExceptSpec.CalledStmt(FD->getBody());
8806   } else {
8807     // Otherwise, build a body so we can check it. This should ideally only
8808     // happen when we're not actually marking the function referenced. (This is
8809     // only really important for efficiency: we don't want to build and throw
8810     // away bodies for comparison functions more than we strictly need to.)
8811 
8812     // Pretend to synthesize the function body in an unevaluated context.
8813     // Note that we can't actually just go ahead and define the function here:
8814     // we are not permitted to mark its callees as referenced.
8815     Sema::SynthesizedFunctionScope Scope(S, FD);
8816     EnterExpressionEvaluationContext Context(
8817         S, Sema::ExpressionEvaluationContext::Unevaluated);
8818 
8819     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8820     SourceLocation BodyLoc =
8821         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8822     StmtResult Body =
8823         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8824     if (!Body.isInvalid())
8825       ExceptSpec.CalledStmt(Body.get());
8826 
8827     // FIXME: Can we hold onto this body and just transform it to potentially
8828     // evaluated when we're asked to define the function rather than rebuilding
8829     // it? Either that, or we should only build the bits of the body that we
8830     // need (the expressions, not the statements).
8831   }
8832 
8833   return ExceptSpec;
8834 }
8835 
8836 void Sema::CheckDelayedMemberExceptionSpecs() {
8837   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8838   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8839 
8840   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8841   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8842 
8843   // Perform any deferred checking of exception specifications for virtual
8844   // destructors.
8845   for (auto &Check : Overriding)
8846     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8847 
8848   // Perform any deferred checking of exception specifications for befriended
8849   // special members.
8850   for (auto &Check : Equivalent)
8851     CheckEquivalentExceptionSpec(Check.second, Check.first);
8852 }
8853 
8854 namespace {
8855 /// CRTP base class for visiting operations performed by a special member
8856 /// function (or inherited constructor).
8857 template<typename Derived>
8858 struct SpecialMemberVisitor {
8859   Sema &S;
8860   CXXMethodDecl *MD;
8861   Sema::CXXSpecialMember CSM;
8862   Sema::InheritedConstructorInfo *ICI;
8863 
8864   // Properties of the special member, computed for convenience.
8865   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8866 
8867   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8868                        Sema::InheritedConstructorInfo *ICI)
8869       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8870     switch (CSM) {
8871     case Sema::CXXDefaultConstructor:
8872     case Sema::CXXCopyConstructor:
8873     case Sema::CXXMoveConstructor:
8874       IsConstructor = true;
8875       break;
8876     case Sema::CXXCopyAssignment:
8877     case Sema::CXXMoveAssignment:
8878       IsAssignment = true;
8879       break;
8880     case Sema::CXXDestructor:
8881       break;
8882     case Sema::CXXInvalid:
8883       llvm_unreachable("invalid special member kind");
8884     }
8885 
8886     if (MD->getNumParams()) {
8887       if (const ReferenceType *RT =
8888               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8889         ConstArg = RT->getPointeeType().isConstQualified();
8890     }
8891   }
8892 
8893   Derived &getDerived() { return static_cast<Derived&>(*this); }
8894 
8895   /// Is this a "move" special member?
8896   bool isMove() const {
8897     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8898   }
8899 
8900   /// Look up the corresponding special member in the given class.
8901   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8902                                              unsigned Quals, bool IsMutable) {
8903     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8904                                        ConstArg && !IsMutable);
8905   }
8906 
8907   /// Look up the constructor for the specified base class to see if it's
8908   /// overridden due to this being an inherited constructor.
8909   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8910     if (!ICI)
8911       return {};
8912     assert(CSM == Sema::CXXDefaultConstructor);
8913     auto *BaseCtor =
8914       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8915     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8916       return MD;
8917     return {};
8918   }
8919 
8920   /// A base or member subobject.
8921   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8922 
8923   /// Get the location to use for a subobject in diagnostics.
8924   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8925     // FIXME: For an indirect virtual base, the direct base leading to
8926     // the indirect virtual base would be a more useful choice.
8927     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8928       return B->getBaseTypeLoc();
8929     else
8930       return Subobj.get<FieldDecl*>()->getLocation();
8931   }
8932 
8933   enum BasesToVisit {
8934     /// Visit all non-virtual (direct) bases.
8935     VisitNonVirtualBases,
8936     /// Visit all direct bases, virtual or not.
8937     VisitDirectBases,
8938     /// Visit all non-virtual bases, and all virtual bases if the class
8939     /// is not abstract.
8940     VisitPotentiallyConstructedBases,
8941     /// Visit all direct or virtual bases.
8942     VisitAllBases
8943   };
8944 
8945   // Visit the bases and members of the class.
8946   bool visit(BasesToVisit Bases) {
8947     CXXRecordDecl *RD = MD->getParent();
8948 
8949     if (Bases == VisitPotentiallyConstructedBases)
8950       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8951 
8952     for (auto &B : RD->bases())
8953       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8954           getDerived().visitBase(&B))
8955         return true;
8956 
8957     if (Bases == VisitAllBases)
8958       for (auto &B : RD->vbases())
8959         if (getDerived().visitBase(&B))
8960           return true;
8961 
8962     for (auto *F : RD->fields())
8963       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8964           getDerived().visitField(F))
8965         return true;
8966 
8967     return false;
8968   }
8969 };
8970 }
8971 
8972 namespace {
8973 struct SpecialMemberDeletionInfo
8974     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8975   bool Diagnose;
8976 
8977   SourceLocation Loc;
8978 
8979   bool AllFieldsAreConst;
8980 
8981   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8982                             Sema::CXXSpecialMember CSM,
8983                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8984       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8985         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8986 
8987   bool inUnion() const { return MD->getParent()->isUnion(); }
8988 
8989   Sema::CXXSpecialMember getEffectiveCSM() {
8990     return ICI ? Sema::CXXInvalid : CSM;
8991   }
8992 
8993   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8994 
8995   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8996   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8997 
8998   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8999   bool shouldDeleteForField(FieldDecl *FD);
9000   bool shouldDeleteForAllConstMembers();
9001 
9002   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9003                                      unsigned Quals);
9004   bool shouldDeleteForSubobjectCall(Subobject Subobj,
9005                                     Sema::SpecialMemberOverloadResult SMOR,
9006                                     bool IsDtorCallInCtor);
9007 
9008   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9009 };
9010 }
9011 
9012 /// Is the given special member inaccessible when used on the given
9013 /// sub-object.
9014 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9015                                              CXXMethodDecl *target) {
9016   /// If we're operating on a base class, the object type is the
9017   /// type of this special member.
9018   QualType objectTy;
9019   AccessSpecifier access = target->getAccess();
9020   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9021     objectTy = S.Context.getTypeDeclType(MD->getParent());
9022     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9023 
9024   // If we're operating on a field, the object type is the type of the field.
9025   } else {
9026     objectTy = S.Context.getTypeDeclType(target->getParent());
9027   }
9028 
9029   return S.isMemberAccessibleForDeletion(
9030       target->getParent(), DeclAccessPair::make(target, access), objectTy);
9031 }
9032 
9033 /// Check whether we should delete a special member due to the implicit
9034 /// definition containing a call to a special member of a subobject.
9035 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9036     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9037     bool IsDtorCallInCtor) {
9038   CXXMethodDecl *Decl = SMOR.getMethod();
9039   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9040 
9041   int DiagKind = -1;
9042 
9043   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9044     DiagKind = !Decl ? 0 : 1;
9045   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9046     DiagKind = 2;
9047   else if (!isAccessible(Subobj, Decl))
9048     DiagKind = 3;
9049   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9050            !Decl->isTrivial()) {
9051     // A member of a union must have a trivial corresponding special member.
9052     // As a weird special case, a destructor call from a union's constructor
9053     // must be accessible and non-deleted, but need not be trivial. Such a
9054     // destructor is never actually called, but is semantically checked as
9055     // if it were.
9056     DiagKind = 4;
9057   }
9058 
9059   if (DiagKind == -1)
9060     return false;
9061 
9062   if (Diagnose) {
9063     if (Field) {
9064       S.Diag(Field->getLocation(),
9065              diag::note_deleted_special_member_class_subobject)
9066         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9067         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9068     } else {
9069       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9070       S.Diag(Base->getBeginLoc(),
9071              diag::note_deleted_special_member_class_subobject)
9072           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9073           << Base->getType() << DiagKind << IsDtorCallInCtor
9074           << /*IsObjCPtr*/false;
9075     }
9076 
9077     if (DiagKind == 1)
9078       S.NoteDeletedFunction(Decl);
9079     // FIXME: Explain inaccessibility if DiagKind == 3.
9080   }
9081 
9082   return true;
9083 }
9084 
9085 /// Check whether we should delete a special member function due to having a
9086 /// direct or virtual base class or non-static data member of class type M.
9087 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9088     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9089   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9090   bool IsMutable = Field && Field->isMutable();
9091 
9092   // C++11 [class.ctor]p5:
9093   // -- any direct or virtual base class, or non-static data member with no
9094   //    brace-or-equal-initializer, has class type M (or array thereof) and
9095   //    either M has no default constructor or overload resolution as applied
9096   //    to M's default constructor results in an ambiguity or in a function
9097   //    that is deleted or inaccessible
9098   // C++11 [class.copy]p11, C++11 [class.copy]p23:
9099   // -- a direct or virtual base class B that cannot be copied/moved because
9100   //    overload resolution, as applied to B's corresponding special member,
9101   //    results in an ambiguity or a function that is deleted or inaccessible
9102   //    from the defaulted special member
9103   // C++11 [class.dtor]p5:
9104   // -- any direct or virtual base class [...] has a type with a destructor
9105   //    that is deleted or inaccessible
9106   if (!(CSM == Sema::CXXDefaultConstructor &&
9107         Field && Field->hasInClassInitializer()) &&
9108       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9109                                    false))
9110     return true;
9111 
9112   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9113   // -- any direct or virtual base class or non-static data member has a
9114   //    type with a destructor that is deleted or inaccessible
9115   if (IsConstructor) {
9116     Sema::SpecialMemberOverloadResult SMOR =
9117         S.LookupSpecialMember(Class, Sema::CXXDestructor,
9118                               false, false, false, false, false);
9119     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9120       return true;
9121   }
9122 
9123   return false;
9124 }
9125 
9126 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9127     FieldDecl *FD, QualType FieldType) {
9128   // The defaulted special functions are defined as deleted if this is a variant
9129   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9130   // type under ARC.
9131   if (!FieldType.hasNonTrivialObjCLifetime())
9132     return false;
9133 
9134   // Don't make the defaulted default constructor defined as deleted if the
9135   // member has an in-class initializer.
9136   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9137     return false;
9138 
9139   if (Diagnose) {
9140     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9141     S.Diag(FD->getLocation(),
9142            diag::note_deleted_special_member_class_subobject)
9143         << getEffectiveCSM() << ParentClass << /*IsField*/true
9144         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9145   }
9146 
9147   return true;
9148 }
9149 
9150 /// Check whether we should delete a special member function due to the class
9151 /// having a particular direct or virtual base class.
9152 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9153   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9154   // If program is correct, BaseClass cannot be null, but if it is, the error
9155   // must be reported elsewhere.
9156   if (!BaseClass)
9157     return false;
9158   // If we have an inheriting constructor, check whether we're calling an
9159   // inherited constructor instead of a default constructor.
9160   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9161   if (auto *BaseCtor = SMOR.getMethod()) {
9162     // Note that we do not check access along this path; other than that,
9163     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9164     // FIXME: Check that the base has a usable destructor! Sink this into
9165     // shouldDeleteForClassSubobject.
9166     if (BaseCtor->isDeleted() && Diagnose) {
9167       S.Diag(Base->getBeginLoc(),
9168              diag::note_deleted_special_member_class_subobject)
9169           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9170           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9171           << /*IsObjCPtr*/false;
9172       S.NoteDeletedFunction(BaseCtor);
9173     }
9174     return BaseCtor->isDeleted();
9175   }
9176   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9177 }
9178 
9179 /// Check whether we should delete a special member function due to the class
9180 /// having a particular non-static data member.
9181 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9182   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9183   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9184 
9185   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9186     return true;
9187 
9188   if (CSM == Sema::CXXDefaultConstructor) {
9189     // For a default constructor, all references must be initialized in-class
9190     // and, if a union, it must have a non-const member.
9191     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9192       if (Diagnose)
9193         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9194           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9195       return true;
9196     }
9197     // C++11 [class.ctor]p5: any non-variant non-static data member of
9198     // const-qualified type (or array thereof) with no
9199     // brace-or-equal-initializer does not have a user-provided default
9200     // constructor.
9201     if (!inUnion() && FieldType.isConstQualified() &&
9202         !FD->hasInClassInitializer() &&
9203         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
9204       if (Diagnose)
9205         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9206           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9207       return true;
9208     }
9209 
9210     if (inUnion() && !FieldType.isConstQualified())
9211       AllFieldsAreConst = false;
9212   } else if (CSM == Sema::CXXCopyConstructor) {
9213     // For a copy constructor, data members must not be of rvalue reference
9214     // type.
9215     if (FieldType->isRValueReferenceType()) {
9216       if (Diagnose)
9217         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9218           << MD->getParent() << FD << FieldType;
9219       return true;
9220     }
9221   } else if (IsAssignment) {
9222     // For an assignment operator, data members must not be of reference type.
9223     if (FieldType->isReferenceType()) {
9224       if (Diagnose)
9225         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9226           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9227       return true;
9228     }
9229     if (!FieldRecord && FieldType.isConstQualified()) {
9230       // C++11 [class.copy]p23:
9231       // -- a non-static data member of const non-class type (or array thereof)
9232       if (Diagnose)
9233         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9234           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9235       return true;
9236     }
9237   }
9238 
9239   if (FieldRecord) {
9240     // Some additional restrictions exist on the variant members.
9241     if (!inUnion() && FieldRecord->isUnion() &&
9242         FieldRecord->isAnonymousStructOrUnion()) {
9243       bool AllVariantFieldsAreConst = true;
9244 
9245       // FIXME: Handle anonymous unions declared within anonymous unions.
9246       for (auto *UI : FieldRecord->fields()) {
9247         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9248 
9249         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9250           return true;
9251 
9252         if (!UnionFieldType.isConstQualified())
9253           AllVariantFieldsAreConst = false;
9254 
9255         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9256         if (UnionFieldRecord &&
9257             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9258                                           UnionFieldType.getCVRQualifiers()))
9259           return true;
9260       }
9261 
9262       // At least one member in each anonymous union must be non-const
9263       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9264           !FieldRecord->field_empty()) {
9265         if (Diagnose)
9266           S.Diag(FieldRecord->getLocation(),
9267                  diag::note_deleted_default_ctor_all_const)
9268             << !!ICI << MD->getParent() << /*anonymous union*/1;
9269         return true;
9270       }
9271 
9272       // Don't check the implicit member of the anonymous union type.
9273       // This is technically non-conformant but supported, and we have a
9274       // diagnostic for this elsewhere.
9275       return false;
9276     }
9277 
9278     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9279                                       FieldType.getCVRQualifiers()))
9280       return true;
9281   }
9282 
9283   return false;
9284 }
9285 
9286 /// C++11 [class.ctor] p5:
9287 ///   A defaulted default constructor for a class X is defined as deleted if
9288 /// X is a union and all of its variant members are of const-qualified type.
9289 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9290   // This is a silly definition, because it gives an empty union a deleted
9291   // default constructor. Don't do that.
9292   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9293     bool AnyFields = false;
9294     for (auto *F : MD->getParent()->fields())
9295       if ((AnyFields = !F->isUnnamedBitfield()))
9296         break;
9297     if (!AnyFields)
9298       return false;
9299     if (Diagnose)
9300       S.Diag(MD->getParent()->getLocation(),
9301              diag::note_deleted_default_ctor_all_const)
9302         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9303     return true;
9304   }
9305   return false;
9306 }
9307 
9308 /// Determine whether a defaulted special member function should be defined as
9309 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9310 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9311 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9312                                      InheritedConstructorInfo *ICI,
9313                                      bool Diagnose) {
9314   if (MD->isInvalidDecl())
9315     return false;
9316   CXXRecordDecl *RD = MD->getParent();
9317   assert(!RD->isDependentType() && "do deletion after instantiation");
9318   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9319     return false;
9320 
9321   // C++11 [expr.lambda.prim]p19:
9322   //   The closure type associated with a lambda-expression has a
9323   //   deleted (8.4.3) default constructor and a deleted copy
9324   //   assignment operator.
9325   // C++2a adds back these operators if the lambda has no lambda-capture.
9326   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9327       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9328     if (Diagnose)
9329       Diag(RD->getLocation(), diag::note_lambda_decl);
9330     return true;
9331   }
9332 
9333   // For an anonymous struct or union, the copy and assignment special members
9334   // will never be used, so skip the check. For an anonymous union declared at
9335   // namespace scope, the constructor and destructor are used.
9336   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9337       RD->isAnonymousStructOrUnion())
9338     return false;
9339 
9340   // C++11 [class.copy]p7, p18:
9341   //   If the class definition declares a move constructor or move assignment
9342   //   operator, an implicitly declared copy constructor or copy assignment
9343   //   operator is defined as deleted.
9344   if (MD->isImplicit() &&
9345       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9346     CXXMethodDecl *UserDeclaredMove = nullptr;
9347 
9348     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9349     // deletion of the corresponding copy operation, not both copy operations.
9350     // MSVC 2015 has adopted the standards conforming behavior.
9351     bool DeletesOnlyMatchingCopy =
9352         getLangOpts().MSVCCompat &&
9353         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9354 
9355     if (RD->hasUserDeclaredMoveConstructor() &&
9356         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9357       if (!Diagnose) return true;
9358 
9359       // Find any user-declared move constructor.
9360       for (auto *I : RD->ctors()) {
9361         if (I->isMoveConstructor()) {
9362           UserDeclaredMove = I;
9363           break;
9364         }
9365       }
9366       assert(UserDeclaredMove);
9367     } else if (RD->hasUserDeclaredMoveAssignment() &&
9368                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9369       if (!Diagnose) return true;
9370 
9371       // Find any user-declared move assignment operator.
9372       for (auto *I : RD->methods()) {
9373         if (I->isMoveAssignmentOperator()) {
9374           UserDeclaredMove = I;
9375           break;
9376         }
9377       }
9378       assert(UserDeclaredMove);
9379     }
9380 
9381     if (UserDeclaredMove) {
9382       Diag(UserDeclaredMove->getLocation(),
9383            diag::note_deleted_copy_user_declared_move)
9384         << (CSM == CXXCopyAssignment) << RD
9385         << UserDeclaredMove->isMoveAssignmentOperator();
9386       return true;
9387     }
9388   }
9389 
9390   // Do access control from the special member function
9391   ContextRAII MethodContext(*this, MD);
9392 
9393   // C++11 [class.dtor]p5:
9394   // -- for a virtual destructor, lookup of the non-array deallocation function
9395   //    results in an ambiguity or in a function that is deleted or inaccessible
9396   if (CSM == CXXDestructor && MD->isVirtual()) {
9397     FunctionDecl *OperatorDelete = nullptr;
9398     DeclarationName Name =
9399       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9400     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9401                                  OperatorDelete, /*Diagnose*/false)) {
9402       if (Diagnose)
9403         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9404       return true;
9405     }
9406   }
9407 
9408   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9409 
9410   // Per DR1611, do not consider virtual bases of constructors of abstract
9411   // classes, since we are not going to construct them.
9412   // Per DR1658, do not consider virtual bases of destructors of abstract
9413   // classes either.
9414   // Per DR2180, for assignment operators we only assign (and thus only
9415   // consider) direct bases.
9416   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9417                                  : SMI.VisitPotentiallyConstructedBases))
9418     return true;
9419 
9420   if (SMI.shouldDeleteForAllConstMembers())
9421     return true;
9422 
9423   if (getLangOpts().CUDA) {
9424     // We should delete the special member in CUDA mode if target inference
9425     // failed.
9426     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9427     // is treated as certain special member, which may not reflect what special
9428     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9429     // expects CSM to match MD, therefore recalculate CSM.
9430     assert(ICI || CSM == getSpecialMember(MD));
9431     auto RealCSM = CSM;
9432     if (ICI)
9433       RealCSM = getSpecialMember(MD);
9434 
9435     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9436                                                    SMI.ConstArg, Diagnose);
9437   }
9438 
9439   return false;
9440 }
9441 
9442 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9443   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9444   assert(DFK && "not a defaultable function");
9445   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9446 
9447   if (DFK.isSpecialMember()) {
9448     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9449                               nullptr, /*Diagnose=*/true);
9450   } else {
9451     DefaultedComparisonAnalyzer(
9452         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9453         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9454         .visit();
9455   }
9456 }
9457 
9458 /// Perform lookup for a special member of the specified kind, and determine
9459 /// whether it is trivial. If the triviality can be determined without the
9460 /// lookup, skip it. This is intended for use when determining whether a
9461 /// special member of a containing object is trivial, and thus does not ever
9462 /// perform overload resolution for default constructors.
9463 ///
9464 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9465 /// member that was most likely to be intended to be trivial, if any.
9466 ///
9467 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9468 /// determine whether the special member is trivial.
9469 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9470                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9471                                      bool ConstRHS,
9472                                      Sema::TrivialABIHandling TAH,
9473                                      CXXMethodDecl **Selected) {
9474   if (Selected)
9475     *Selected = nullptr;
9476 
9477   switch (CSM) {
9478   case Sema::CXXInvalid:
9479     llvm_unreachable("not a special member");
9480 
9481   case Sema::CXXDefaultConstructor:
9482     // C++11 [class.ctor]p5:
9483     //   A default constructor is trivial if:
9484     //    - all the [direct subobjects] have trivial default constructors
9485     //
9486     // Note, no overload resolution is performed in this case.
9487     if (RD->hasTrivialDefaultConstructor())
9488       return true;
9489 
9490     if (Selected) {
9491       // If there's a default constructor which could have been trivial, dig it
9492       // out. Otherwise, if there's any user-provided default constructor, point
9493       // to that as an example of why there's not a trivial one.
9494       CXXConstructorDecl *DefCtor = nullptr;
9495       if (RD->needsImplicitDefaultConstructor())
9496         S.DeclareImplicitDefaultConstructor(RD);
9497       for (auto *CI : RD->ctors()) {
9498         if (!CI->isDefaultConstructor())
9499           continue;
9500         DefCtor = CI;
9501         if (!DefCtor->isUserProvided())
9502           break;
9503       }
9504 
9505       *Selected = DefCtor;
9506     }
9507 
9508     return false;
9509 
9510   case Sema::CXXDestructor:
9511     // C++11 [class.dtor]p5:
9512     //   A destructor is trivial if:
9513     //    - all the direct [subobjects] have trivial destructors
9514     if (RD->hasTrivialDestructor() ||
9515         (TAH == Sema::TAH_ConsiderTrivialABI &&
9516          RD->hasTrivialDestructorForCall()))
9517       return true;
9518 
9519     if (Selected) {
9520       if (RD->needsImplicitDestructor())
9521         S.DeclareImplicitDestructor(RD);
9522       *Selected = RD->getDestructor();
9523     }
9524 
9525     return false;
9526 
9527   case Sema::CXXCopyConstructor:
9528     // C++11 [class.copy]p12:
9529     //   A copy constructor is trivial if:
9530     //    - the constructor selected to copy each direct [subobject] is trivial
9531     if (RD->hasTrivialCopyConstructor() ||
9532         (TAH == Sema::TAH_ConsiderTrivialABI &&
9533          RD->hasTrivialCopyConstructorForCall())) {
9534       if (Quals == Qualifiers::Const)
9535         // We must either select the trivial copy constructor or reach an
9536         // ambiguity; no need to actually perform overload resolution.
9537         return true;
9538     } else if (!Selected) {
9539       return false;
9540     }
9541     // In C++98, we are not supposed to perform overload resolution here, but we
9542     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9543     // cases like B as having a non-trivial copy constructor:
9544     //   struct A { template<typename T> A(T&); };
9545     //   struct B { mutable A a; };
9546     goto NeedOverloadResolution;
9547 
9548   case Sema::CXXCopyAssignment:
9549     // C++11 [class.copy]p25:
9550     //   A copy assignment operator is trivial if:
9551     //    - the assignment operator selected to copy each direct [subobject] is
9552     //      trivial
9553     if (RD->hasTrivialCopyAssignment()) {
9554       if (Quals == Qualifiers::Const)
9555         return true;
9556     } else if (!Selected) {
9557       return false;
9558     }
9559     // In C++98, we are not supposed to perform overload resolution here, but we
9560     // treat that as a language defect.
9561     goto NeedOverloadResolution;
9562 
9563   case Sema::CXXMoveConstructor:
9564   case Sema::CXXMoveAssignment:
9565   NeedOverloadResolution:
9566     Sema::SpecialMemberOverloadResult SMOR =
9567         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9568 
9569     // The standard doesn't describe how to behave if the lookup is ambiguous.
9570     // We treat it as not making the member non-trivial, just like the standard
9571     // mandates for the default constructor. This should rarely matter, because
9572     // the member will also be deleted.
9573     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9574       return true;
9575 
9576     if (!SMOR.getMethod()) {
9577       assert(SMOR.getKind() ==
9578              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9579       return false;
9580     }
9581 
9582     // We deliberately don't check if we found a deleted special member. We're
9583     // not supposed to!
9584     if (Selected)
9585       *Selected = SMOR.getMethod();
9586 
9587     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9588         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9589       return SMOR.getMethod()->isTrivialForCall();
9590     return SMOR.getMethod()->isTrivial();
9591   }
9592 
9593   llvm_unreachable("unknown special method kind");
9594 }
9595 
9596 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9597   for (auto *CI : RD->ctors())
9598     if (!CI->isImplicit())
9599       return CI;
9600 
9601   // Look for constructor templates.
9602   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9603   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9604     if (CXXConstructorDecl *CD =
9605           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9606       return CD;
9607   }
9608 
9609   return nullptr;
9610 }
9611 
9612 /// The kind of subobject we are checking for triviality. The values of this
9613 /// enumeration are used in diagnostics.
9614 enum TrivialSubobjectKind {
9615   /// The subobject is a base class.
9616   TSK_BaseClass,
9617   /// The subobject is a non-static data member.
9618   TSK_Field,
9619   /// The object is actually the complete object.
9620   TSK_CompleteObject
9621 };
9622 
9623 /// Check whether the special member selected for a given type would be trivial.
9624 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9625                                       QualType SubType, bool ConstRHS,
9626                                       Sema::CXXSpecialMember CSM,
9627                                       TrivialSubobjectKind Kind,
9628                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9629   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9630   if (!SubRD)
9631     return true;
9632 
9633   CXXMethodDecl *Selected;
9634   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9635                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9636     return true;
9637 
9638   if (Diagnose) {
9639     if (ConstRHS)
9640       SubType.addConst();
9641 
9642     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9643       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9644         << Kind << SubType.getUnqualifiedType();
9645       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9646         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9647     } else if (!Selected)
9648       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9649         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9650     else if (Selected->isUserProvided()) {
9651       if (Kind == TSK_CompleteObject)
9652         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9653           << Kind << SubType.getUnqualifiedType() << CSM;
9654       else {
9655         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9656           << Kind << SubType.getUnqualifiedType() << CSM;
9657         S.Diag(Selected->getLocation(), diag::note_declared_at);
9658       }
9659     } else {
9660       if (Kind != TSK_CompleteObject)
9661         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9662           << Kind << SubType.getUnqualifiedType() << CSM;
9663 
9664       // Explain why the defaulted or deleted special member isn't trivial.
9665       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9666                                Diagnose);
9667     }
9668   }
9669 
9670   return false;
9671 }
9672 
9673 /// Check whether the members of a class type allow a special member to be
9674 /// trivial.
9675 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9676                                      Sema::CXXSpecialMember CSM,
9677                                      bool ConstArg,
9678                                      Sema::TrivialABIHandling TAH,
9679                                      bool Diagnose) {
9680   for (const auto *FI : RD->fields()) {
9681     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9682       continue;
9683 
9684     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9685 
9686     // Pretend anonymous struct or union members are members of this class.
9687     if (FI->isAnonymousStructOrUnion()) {
9688       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9689                                     CSM, ConstArg, TAH, Diagnose))
9690         return false;
9691       continue;
9692     }
9693 
9694     // C++11 [class.ctor]p5:
9695     //   A default constructor is trivial if [...]
9696     //    -- no non-static data member of its class has a
9697     //       brace-or-equal-initializer
9698     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9699       if (Diagnose)
9700         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9701             << FI;
9702       return false;
9703     }
9704 
9705     // Objective C ARC 4.3.5:
9706     //   [...] nontrivally ownership-qualified types are [...] not trivially
9707     //   default constructible, copy constructible, move constructible, copy
9708     //   assignable, move assignable, or destructible [...]
9709     if (FieldType.hasNonTrivialObjCLifetime()) {
9710       if (Diagnose)
9711         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9712           << RD << FieldType.getObjCLifetime();
9713       return false;
9714     }
9715 
9716     bool ConstRHS = ConstArg && !FI->isMutable();
9717     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9718                                    CSM, TSK_Field, TAH, Diagnose))
9719       return false;
9720   }
9721 
9722   return true;
9723 }
9724 
9725 /// Diagnose why the specified class does not have a trivial special member of
9726 /// the given kind.
9727 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9728   QualType Ty = Context.getRecordType(RD);
9729 
9730   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9731   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9732                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9733                             /*Diagnose*/true);
9734 }
9735 
9736 /// Determine whether a defaulted or deleted special member function is trivial,
9737 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9738 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9739 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9740                                   TrivialABIHandling TAH, bool Diagnose) {
9741   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9742 
9743   CXXRecordDecl *RD = MD->getParent();
9744 
9745   bool ConstArg = false;
9746 
9747   // C++11 [class.copy]p12, p25: [DR1593]
9748   //   A [special member] is trivial if [...] its parameter-type-list is
9749   //   equivalent to the parameter-type-list of an implicit declaration [...]
9750   switch (CSM) {
9751   case CXXDefaultConstructor:
9752   case CXXDestructor:
9753     // Trivial default constructors and destructors cannot have parameters.
9754     break;
9755 
9756   case CXXCopyConstructor:
9757   case CXXCopyAssignment: {
9758     // Trivial copy operations always have const, non-volatile parameter types.
9759     ConstArg = true;
9760     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9761     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9762     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9763       if (Diagnose)
9764         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9765           << Param0->getSourceRange() << Param0->getType()
9766           << Context.getLValueReferenceType(
9767                Context.getRecordType(RD).withConst());
9768       return false;
9769     }
9770     break;
9771   }
9772 
9773   case CXXMoveConstructor:
9774   case CXXMoveAssignment: {
9775     // Trivial move operations always have non-cv-qualified parameters.
9776     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9777     const RValueReferenceType *RT =
9778       Param0->getType()->getAs<RValueReferenceType>();
9779     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9780       if (Diagnose)
9781         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9782           << Param0->getSourceRange() << Param0->getType()
9783           << Context.getRValueReferenceType(Context.getRecordType(RD));
9784       return false;
9785     }
9786     break;
9787   }
9788 
9789   case CXXInvalid:
9790     llvm_unreachable("not a special member");
9791   }
9792 
9793   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9794     if (Diagnose)
9795       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9796            diag::note_nontrivial_default_arg)
9797         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9798     return false;
9799   }
9800   if (MD->isVariadic()) {
9801     if (Diagnose)
9802       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9803     return false;
9804   }
9805 
9806   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9807   //   A copy/move [constructor or assignment operator] is trivial if
9808   //    -- the [member] selected to copy/move each direct base class subobject
9809   //       is trivial
9810   //
9811   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9812   //   A [default constructor or destructor] is trivial if
9813   //    -- all the direct base classes have trivial [default constructors or
9814   //       destructors]
9815   for (const auto &BI : RD->bases())
9816     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9817                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9818       return false;
9819 
9820   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9821   //   A copy/move [constructor or assignment operator] for a class X is
9822   //   trivial if
9823   //    -- for each non-static data member of X that is of class type (or array
9824   //       thereof), the constructor selected to copy/move that member is
9825   //       trivial
9826   //
9827   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9828   //   A [default constructor or destructor] is trivial if
9829   //    -- for all of the non-static data members of its class that are of class
9830   //       type (or array thereof), each such class has a trivial [default
9831   //       constructor or destructor]
9832   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9833     return false;
9834 
9835   // C++11 [class.dtor]p5:
9836   //   A destructor is trivial if [...]
9837   //    -- the destructor is not virtual
9838   if (CSM == CXXDestructor && MD->isVirtual()) {
9839     if (Diagnose)
9840       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9841     return false;
9842   }
9843 
9844   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9845   //   A [special member] for class X is trivial if [...]
9846   //    -- class X has no virtual functions and no virtual base classes
9847   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9848     if (!Diagnose)
9849       return false;
9850 
9851     if (RD->getNumVBases()) {
9852       // Check for virtual bases. We already know that the corresponding
9853       // member in all bases is trivial, so vbases must all be direct.
9854       CXXBaseSpecifier &BS = *RD->vbases_begin();
9855       assert(BS.isVirtual());
9856       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9857       return false;
9858     }
9859 
9860     // Must have a virtual method.
9861     for (const auto *MI : RD->methods()) {
9862       if (MI->isVirtual()) {
9863         SourceLocation MLoc = MI->getBeginLoc();
9864         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9865         return false;
9866       }
9867     }
9868 
9869     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9870   }
9871 
9872   // Looks like it's trivial!
9873   return true;
9874 }
9875 
9876 namespace {
9877 struct FindHiddenVirtualMethod {
9878   Sema *S;
9879   CXXMethodDecl *Method;
9880   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9881   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9882 
9883 private:
9884   /// Check whether any most overridden method from MD in Methods
9885   static bool CheckMostOverridenMethods(
9886       const CXXMethodDecl *MD,
9887       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9888     if (MD->size_overridden_methods() == 0)
9889       return Methods.count(MD->getCanonicalDecl());
9890     for (const CXXMethodDecl *O : MD->overridden_methods())
9891       if (CheckMostOverridenMethods(O, Methods))
9892         return true;
9893     return false;
9894   }
9895 
9896 public:
9897   /// Member lookup function that determines whether a given C++
9898   /// method overloads virtual methods in a base class without overriding any,
9899   /// to be used with CXXRecordDecl::lookupInBases().
9900   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9901     RecordDecl *BaseRecord =
9902         Specifier->getType()->castAs<RecordType>()->getDecl();
9903 
9904     DeclarationName Name = Method->getDeclName();
9905     assert(Name.getNameKind() == DeclarationName::Identifier);
9906 
9907     bool foundSameNameMethod = false;
9908     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9909     for (Path.Decls = BaseRecord->lookup(Name).begin();
9910          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9911       NamedDecl *D = *Path.Decls;
9912       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9913         MD = MD->getCanonicalDecl();
9914         foundSameNameMethod = true;
9915         // Interested only in hidden virtual methods.
9916         if (!MD->isVirtual())
9917           continue;
9918         // If the method we are checking overrides a method from its base
9919         // don't warn about the other overloaded methods. Clang deviates from
9920         // GCC by only diagnosing overloads of inherited virtual functions that
9921         // do not override any other virtual functions in the base. GCC's
9922         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9923         // function from a base class. These cases may be better served by a
9924         // warning (not specific to virtual functions) on call sites when the
9925         // call would select a different function from the base class, were it
9926         // visible.
9927         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9928         if (!S->IsOverload(Method, MD, false))
9929           return true;
9930         // Collect the overload only if its hidden.
9931         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9932           overloadedMethods.push_back(MD);
9933       }
9934     }
9935 
9936     if (foundSameNameMethod)
9937       OverloadedMethods.append(overloadedMethods.begin(),
9938                                overloadedMethods.end());
9939     return foundSameNameMethod;
9940   }
9941 };
9942 } // end anonymous namespace
9943 
9944 /// Add the most overridden methods from MD to Methods
9945 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9946                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9947   if (MD->size_overridden_methods() == 0)
9948     Methods.insert(MD->getCanonicalDecl());
9949   else
9950     for (const CXXMethodDecl *O : MD->overridden_methods())
9951       AddMostOverridenMethods(O, Methods);
9952 }
9953 
9954 /// Check if a method overloads virtual methods in a base class without
9955 /// overriding any.
9956 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9957                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9958   if (!MD->getDeclName().isIdentifier())
9959     return;
9960 
9961   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9962                      /*bool RecordPaths=*/false,
9963                      /*bool DetectVirtual=*/false);
9964   FindHiddenVirtualMethod FHVM;
9965   FHVM.Method = MD;
9966   FHVM.S = this;
9967 
9968   // Keep the base methods that were overridden or introduced in the subclass
9969   // by 'using' in a set. A base method not in this set is hidden.
9970   CXXRecordDecl *DC = MD->getParent();
9971   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9972   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9973     NamedDecl *ND = *I;
9974     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9975       ND = shad->getTargetDecl();
9976     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9977       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9978   }
9979 
9980   if (DC->lookupInBases(FHVM, Paths))
9981     OverloadedMethods = FHVM.OverloadedMethods;
9982 }
9983 
9984 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9985                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9986   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9987     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9988     PartialDiagnostic PD = PDiag(
9989          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9990     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9991     Diag(overloadedMD->getLocation(), PD);
9992   }
9993 }
9994 
9995 /// Diagnose methods which overload virtual methods in a base class
9996 /// without overriding any.
9997 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9998   if (MD->isInvalidDecl())
9999     return;
10000 
10001   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10002     return;
10003 
10004   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10005   FindHiddenVirtualMethods(MD, OverloadedMethods);
10006   if (!OverloadedMethods.empty()) {
10007     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10008       << MD << (OverloadedMethods.size() > 1);
10009 
10010     NoteHiddenVirtualMethods(MD, OverloadedMethods);
10011   }
10012 }
10013 
10014 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10015   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10016     // No diagnostics if this is a template instantiation.
10017     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10018       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10019            diag::ext_cannot_use_trivial_abi) << &RD;
10020       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10021            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10022     }
10023     RD.dropAttr<TrivialABIAttr>();
10024   };
10025 
10026   // Ill-formed if the copy and move constructors are deleted.
10027   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10028     // If the type is dependent, then assume it might have
10029     // implicit copy or move ctor because we won't know yet at this point.
10030     if (RD.isDependentType())
10031       return true;
10032     if (RD.needsImplicitCopyConstructor() &&
10033         !RD.defaultedCopyConstructorIsDeleted())
10034       return true;
10035     if (RD.needsImplicitMoveConstructor() &&
10036         !RD.defaultedMoveConstructorIsDeleted())
10037       return true;
10038     for (const CXXConstructorDecl *CD : RD.ctors())
10039       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10040         return true;
10041     return false;
10042   };
10043 
10044   if (!HasNonDeletedCopyOrMoveConstructor()) {
10045     PrintDiagAndRemoveAttr(0);
10046     return;
10047   }
10048 
10049   // Ill-formed if the struct has virtual functions.
10050   if (RD.isPolymorphic()) {
10051     PrintDiagAndRemoveAttr(1);
10052     return;
10053   }
10054 
10055   for (const auto &B : RD.bases()) {
10056     // Ill-formed if the base class is non-trivial for the purpose of calls or a
10057     // virtual base.
10058     if (!B.getType()->isDependentType() &&
10059         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10060       PrintDiagAndRemoveAttr(2);
10061       return;
10062     }
10063 
10064     if (B.isVirtual()) {
10065       PrintDiagAndRemoveAttr(3);
10066       return;
10067     }
10068   }
10069 
10070   for (const auto *FD : RD.fields()) {
10071     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10072     // non-trivial for the purpose of calls.
10073     QualType FT = FD->getType();
10074     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10075       PrintDiagAndRemoveAttr(4);
10076       return;
10077     }
10078 
10079     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10080       if (!RT->isDependentType() &&
10081           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10082         PrintDiagAndRemoveAttr(5);
10083         return;
10084       }
10085   }
10086 }
10087 
10088 void Sema::ActOnFinishCXXMemberSpecification(
10089     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10090     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10091   if (!TagDecl)
10092     return;
10093 
10094   AdjustDeclIfTemplate(TagDecl);
10095 
10096   for (const ParsedAttr &AL : AttrList) {
10097     if (AL.getKind() != ParsedAttr::AT_Visibility)
10098       continue;
10099     AL.setInvalid();
10100     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10101   }
10102 
10103   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
10104               // strict aliasing violation!
10105               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
10106               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
10107 
10108   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10109 }
10110 
10111 /// Find the equality comparison functions that should be implicitly declared
10112 /// in a given class definition, per C++2a [class.compare.default]p3.
10113 static void findImplicitlyDeclaredEqualityComparisons(
10114     ASTContext &Ctx, CXXRecordDecl *RD,
10115     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10116   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10117   if (!RD->lookup(EqEq).empty())
10118     // Member operator== explicitly declared: no implicit operator==s.
10119     return;
10120 
10121   // Traverse friends looking for an '==' or a '<=>'.
10122   for (FriendDecl *Friend : RD->friends()) {
10123     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10124     if (!FD) continue;
10125 
10126     if (FD->getOverloadedOperator() == OO_EqualEqual) {
10127       // Friend operator== explicitly declared: no implicit operator==s.
10128       Spaceships.clear();
10129       return;
10130     }
10131 
10132     if (FD->getOverloadedOperator() == OO_Spaceship &&
10133         FD->isExplicitlyDefaulted())
10134       Spaceships.push_back(FD);
10135   }
10136 
10137   // Look for members named 'operator<=>'.
10138   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10139   for (NamedDecl *ND : RD->lookup(Cmp)) {
10140     // Note that we could find a non-function here (either a function template
10141     // or a using-declaration). Neither case results in an implicit
10142     // 'operator=='.
10143     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10144       if (FD->isExplicitlyDefaulted())
10145         Spaceships.push_back(FD);
10146   }
10147 }
10148 
10149 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10150 /// special functions, such as the default constructor, copy
10151 /// constructor, or destructor, to the given C++ class (C++
10152 /// [special]p1).  This routine can only be executed just before the
10153 /// definition of the class is complete.
10154 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10155   // Don't add implicit special members to templated classes.
10156   // FIXME: This means unqualified lookups for 'operator=' within a class
10157   // template don't work properly.
10158   if (!ClassDecl->isDependentType()) {
10159     if (ClassDecl->needsImplicitDefaultConstructor()) {
10160       ++getASTContext().NumImplicitDefaultConstructors;
10161 
10162       if (ClassDecl->hasInheritedConstructor())
10163         DeclareImplicitDefaultConstructor(ClassDecl);
10164     }
10165 
10166     if (ClassDecl->needsImplicitCopyConstructor()) {
10167       ++getASTContext().NumImplicitCopyConstructors;
10168 
10169       // If the properties or semantics of the copy constructor couldn't be
10170       // determined while the class was being declared, force a declaration
10171       // of it now.
10172       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10173           ClassDecl->hasInheritedConstructor())
10174         DeclareImplicitCopyConstructor(ClassDecl);
10175       // For the MS ABI we need to know whether the copy ctor is deleted. A
10176       // prerequisite for deleting the implicit copy ctor is that the class has
10177       // a move ctor or move assignment that is either user-declared or whose
10178       // semantics are inherited from a subobject. FIXME: We should provide a
10179       // more direct way for CodeGen to ask whether the constructor was deleted.
10180       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10181                (ClassDecl->hasUserDeclaredMoveConstructor() ||
10182                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10183                 ClassDecl->hasUserDeclaredMoveAssignment() ||
10184                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10185         DeclareImplicitCopyConstructor(ClassDecl);
10186     }
10187 
10188     if (getLangOpts().CPlusPlus11 &&
10189         ClassDecl->needsImplicitMoveConstructor()) {
10190       ++getASTContext().NumImplicitMoveConstructors;
10191 
10192       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10193           ClassDecl->hasInheritedConstructor())
10194         DeclareImplicitMoveConstructor(ClassDecl);
10195     }
10196 
10197     if (ClassDecl->needsImplicitCopyAssignment()) {
10198       ++getASTContext().NumImplicitCopyAssignmentOperators;
10199 
10200       // If we have a dynamic class, then the copy assignment operator may be
10201       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10202       // it shows up in the right place in the vtable and that we diagnose
10203       // problems with the implicit exception specification.
10204       if (ClassDecl->isDynamicClass() ||
10205           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10206           ClassDecl->hasInheritedAssignment())
10207         DeclareImplicitCopyAssignment(ClassDecl);
10208     }
10209 
10210     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10211       ++getASTContext().NumImplicitMoveAssignmentOperators;
10212 
10213       // Likewise for the move assignment operator.
10214       if (ClassDecl->isDynamicClass() ||
10215           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10216           ClassDecl->hasInheritedAssignment())
10217         DeclareImplicitMoveAssignment(ClassDecl);
10218     }
10219 
10220     if (ClassDecl->needsImplicitDestructor()) {
10221       ++getASTContext().NumImplicitDestructors;
10222 
10223       // If we have a dynamic class, then the destructor may be virtual, so we
10224       // have to declare the destructor immediately. This ensures that, e.g., it
10225       // shows up in the right place in the vtable and that we diagnose problems
10226       // with the implicit exception specification.
10227       if (ClassDecl->isDynamicClass() ||
10228           ClassDecl->needsOverloadResolutionForDestructor())
10229         DeclareImplicitDestructor(ClassDecl);
10230     }
10231   }
10232 
10233   // C++2a [class.compare.default]p3:
10234   //   If the member-specification does not explicitly declare any member or
10235   //   friend named operator==, an == operator function is declared implicitly
10236   //   for each defaulted three-way comparison operator function defined in
10237   //   the member-specification
10238   // FIXME: Consider doing this lazily.
10239   // We do this during the initial parse for a class template, not during
10240   // instantiation, so that we can handle unqualified lookups for 'operator=='
10241   // when parsing the template.
10242   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10243     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10244     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10245                                               DefaultedSpaceships);
10246     for (auto *FD : DefaultedSpaceships)
10247       DeclareImplicitEqualityComparison(ClassDecl, FD);
10248   }
10249 }
10250 
10251 unsigned
10252 Sema::ActOnReenterTemplateScope(Decl *D,
10253                                 llvm::function_ref<Scope *()> EnterScope) {
10254   if (!D)
10255     return 0;
10256   AdjustDeclIfTemplate(D);
10257 
10258   // In order to get name lookup right, reenter template scopes in order from
10259   // outermost to innermost.
10260   SmallVector<TemplateParameterList *, 4> ParameterLists;
10261   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10262 
10263   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10264     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10265       ParameterLists.push_back(DD->getTemplateParameterList(i));
10266 
10267     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10268       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10269         ParameterLists.push_back(FTD->getTemplateParameters());
10270     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10271       LookupDC = VD->getDeclContext();
10272 
10273       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10274         ParameterLists.push_back(VTD->getTemplateParameters());
10275       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10276         ParameterLists.push_back(PSD->getTemplateParameters());
10277     }
10278   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10279     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10280       ParameterLists.push_back(TD->getTemplateParameterList(i));
10281 
10282     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10283       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10284         ParameterLists.push_back(CTD->getTemplateParameters());
10285       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10286         ParameterLists.push_back(PSD->getTemplateParameters());
10287     }
10288   }
10289   // FIXME: Alias declarations and concepts.
10290 
10291   unsigned Count = 0;
10292   Scope *InnermostTemplateScope = nullptr;
10293   for (TemplateParameterList *Params : ParameterLists) {
10294     // Ignore explicit specializations; they don't contribute to the template
10295     // depth.
10296     if (Params->size() == 0)
10297       continue;
10298 
10299     InnermostTemplateScope = EnterScope();
10300     for (NamedDecl *Param : *Params) {
10301       if (Param->getDeclName()) {
10302         InnermostTemplateScope->AddDecl(Param);
10303         IdResolver.AddDecl(Param);
10304       }
10305     }
10306     ++Count;
10307   }
10308 
10309   // Associate the new template scopes with the corresponding entities.
10310   if (InnermostTemplateScope) {
10311     assert(LookupDC && "no enclosing DeclContext for template lookup");
10312     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10313   }
10314 
10315   return Count;
10316 }
10317 
10318 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10319   if (!RecordD) return;
10320   AdjustDeclIfTemplate(RecordD);
10321   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10322   PushDeclContext(S, Record);
10323 }
10324 
10325 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10326   if (!RecordD) return;
10327   PopDeclContext();
10328 }
10329 
10330 /// This is used to implement the constant expression evaluation part of the
10331 /// attribute enable_if extension. There is nothing in standard C++ which would
10332 /// require reentering parameters.
10333 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10334   if (!Param)
10335     return;
10336 
10337   S->AddDecl(Param);
10338   if (Param->getDeclName())
10339     IdResolver.AddDecl(Param);
10340 }
10341 
10342 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10343 /// parsing a top-level (non-nested) C++ class, and we are now
10344 /// parsing those parts of the given Method declaration that could
10345 /// not be parsed earlier (C++ [class.mem]p2), such as default
10346 /// arguments. This action should enter the scope of the given
10347 /// Method declaration as if we had just parsed the qualified method
10348 /// name. However, it should not bring the parameters into scope;
10349 /// that will be performed by ActOnDelayedCXXMethodParameter.
10350 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10351 }
10352 
10353 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10354 /// C++ method declaration. We're (re-)introducing the given
10355 /// function parameter into scope for use in parsing later parts of
10356 /// the method declaration. For example, we could see an
10357 /// ActOnParamDefaultArgument event for this parameter.
10358 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10359   if (!ParamD)
10360     return;
10361 
10362   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10363 
10364   S->AddDecl(Param);
10365   if (Param->getDeclName())
10366     IdResolver.AddDecl(Param);
10367 }
10368 
10369 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10370 /// processing the delayed method declaration for Method. The method
10371 /// declaration is now considered finished. There may be a separate
10372 /// ActOnStartOfFunctionDef action later (not necessarily
10373 /// immediately!) for this method, if it was also defined inside the
10374 /// class body.
10375 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10376   if (!MethodD)
10377     return;
10378 
10379   AdjustDeclIfTemplate(MethodD);
10380 
10381   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10382 
10383   // Now that we have our default arguments, check the constructor
10384   // again. It could produce additional diagnostics or affect whether
10385   // the class has implicitly-declared destructors, among other
10386   // things.
10387   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10388     CheckConstructor(Constructor);
10389 
10390   // Check the default arguments, which we may have added.
10391   if (!Method->isInvalidDecl())
10392     CheckCXXDefaultArguments(Method);
10393 }
10394 
10395 // Emit the given diagnostic for each non-address-space qualifier.
10396 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10397 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10398   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10399   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10400     bool DiagOccured = false;
10401     FTI.MethodQualifiers->forEachQualifier(
10402         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10403                                    SourceLocation SL) {
10404           // This diagnostic should be emitted on any qualifier except an addr
10405           // space qualifier. However, forEachQualifier currently doesn't visit
10406           // addr space qualifiers, so there's no way to write this condition
10407           // right now; we just diagnose on everything.
10408           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10409           DiagOccured = true;
10410         });
10411     if (DiagOccured)
10412       D.setInvalidType();
10413   }
10414 }
10415 
10416 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10417 /// the well-formedness of the constructor declarator @p D with type @p
10418 /// R. If there are any errors in the declarator, this routine will
10419 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10420 /// will be updated to reflect a well-formed type for the constructor and
10421 /// returned.
10422 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10423                                           StorageClass &SC) {
10424   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10425 
10426   // C++ [class.ctor]p3:
10427   //   A constructor shall not be virtual (10.3) or static (9.4). A
10428   //   constructor can be invoked for a const, volatile or const
10429   //   volatile object. A constructor shall not be declared const,
10430   //   volatile, or const volatile (9.3.2).
10431   if (isVirtual) {
10432     if (!D.isInvalidType())
10433       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10434         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10435         << SourceRange(D.getIdentifierLoc());
10436     D.setInvalidType();
10437   }
10438   if (SC == SC_Static) {
10439     if (!D.isInvalidType())
10440       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10441         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10442         << SourceRange(D.getIdentifierLoc());
10443     D.setInvalidType();
10444     SC = SC_None;
10445   }
10446 
10447   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10448     diagnoseIgnoredQualifiers(
10449         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10450         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10451         D.getDeclSpec().getRestrictSpecLoc(),
10452         D.getDeclSpec().getAtomicSpecLoc());
10453     D.setInvalidType();
10454   }
10455 
10456   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10457 
10458   // C++0x [class.ctor]p4:
10459   //   A constructor shall not be declared with a ref-qualifier.
10460   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10461   if (FTI.hasRefQualifier()) {
10462     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10463       << FTI.RefQualifierIsLValueRef
10464       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10465     D.setInvalidType();
10466   }
10467 
10468   // Rebuild the function type "R" without any type qualifiers (in
10469   // case any of the errors above fired) and with "void" as the
10470   // return type, since constructors don't have return types.
10471   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10472   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10473     return R;
10474 
10475   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10476   EPI.TypeQuals = Qualifiers();
10477   EPI.RefQualifier = RQ_None;
10478 
10479   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10480 }
10481 
10482 /// CheckConstructor - Checks a fully-formed constructor for
10483 /// well-formedness, issuing any diagnostics required. Returns true if
10484 /// the constructor declarator is invalid.
10485 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10486   CXXRecordDecl *ClassDecl
10487     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10488   if (!ClassDecl)
10489     return Constructor->setInvalidDecl();
10490 
10491   // C++ [class.copy]p3:
10492   //   A declaration of a constructor for a class X is ill-formed if
10493   //   its first parameter is of type (optionally cv-qualified) X and
10494   //   either there are no other parameters or else all other
10495   //   parameters have default arguments.
10496   if (!Constructor->isInvalidDecl() &&
10497       Constructor->hasOneParamOrDefaultArgs() &&
10498       Constructor->getTemplateSpecializationKind() !=
10499           TSK_ImplicitInstantiation) {
10500     QualType ParamType = Constructor->getParamDecl(0)->getType();
10501     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10502     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10503       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10504       const char *ConstRef
10505         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10506                                                         : " const &";
10507       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10508         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10509 
10510       // FIXME: Rather that making the constructor invalid, we should endeavor
10511       // to fix the type.
10512       Constructor->setInvalidDecl();
10513     }
10514   }
10515 }
10516 
10517 /// CheckDestructor - Checks a fully-formed destructor definition for
10518 /// well-formedness, issuing any diagnostics required.  Returns true
10519 /// on error.
10520 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10521   CXXRecordDecl *RD = Destructor->getParent();
10522 
10523   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10524     SourceLocation Loc;
10525 
10526     if (!Destructor->isImplicit())
10527       Loc = Destructor->getLocation();
10528     else
10529       Loc = RD->getLocation();
10530 
10531     // If we have a virtual destructor, look up the deallocation function
10532     if (FunctionDecl *OperatorDelete =
10533             FindDeallocationFunctionForDestructor(Loc, RD)) {
10534       Expr *ThisArg = nullptr;
10535 
10536       // If the notional 'delete this' expression requires a non-trivial
10537       // conversion from 'this' to the type of a destroying operator delete's
10538       // first parameter, perform that conversion now.
10539       if (OperatorDelete->isDestroyingOperatorDelete()) {
10540         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10541         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10542           // C++ [class.dtor]p13:
10543           //   ... as if for the expression 'delete this' appearing in a
10544           //   non-virtual destructor of the destructor's class.
10545           ContextRAII SwitchContext(*this, Destructor);
10546           ExprResult This =
10547               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10548           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10549           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10550           if (This.isInvalid()) {
10551             // FIXME: Register this as a context note so that it comes out
10552             // in the right order.
10553             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10554             return true;
10555           }
10556           ThisArg = This.get();
10557         }
10558       }
10559 
10560       DiagnoseUseOfDecl(OperatorDelete, Loc);
10561       MarkFunctionReferenced(Loc, OperatorDelete);
10562       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10563     }
10564   }
10565 
10566   return false;
10567 }
10568 
10569 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10570 /// the well-formednes of the destructor declarator @p D with type @p
10571 /// R. If there are any errors in the declarator, this routine will
10572 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10573 /// will be updated to reflect a well-formed type for the destructor and
10574 /// returned.
10575 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10576                                          StorageClass& SC) {
10577   // C++ [class.dtor]p1:
10578   //   [...] A typedef-name that names a class is a class-name
10579   //   (7.1.3); however, a typedef-name that names a class shall not
10580   //   be used as the identifier in the declarator for a destructor
10581   //   declaration.
10582   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10583   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10584     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10585       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10586   else if (const TemplateSpecializationType *TST =
10587              DeclaratorType->getAs<TemplateSpecializationType>())
10588     if (TST->isTypeAlias())
10589       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10590         << DeclaratorType << 1;
10591 
10592   // C++ [class.dtor]p2:
10593   //   A destructor is used to destroy objects of its class type. A
10594   //   destructor takes no parameters, and no return type can be
10595   //   specified for it (not even void). The address of a destructor
10596   //   shall not be taken. A destructor shall not be static. A
10597   //   destructor can be invoked for a const, volatile or const
10598   //   volatile object. A destructor shall not be declared const,
10599   //   volatile or const volatile (9.3.2).
10600   if (SC == SC_Static) {
10601     if (!D.isInvalidType())
10602       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10603         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10604         << SourceRange(D.getIdentifierLoc())
10605         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10606 
10607     SC = SC_None;
10608   }
10609   if (!D.isInvalidType()) {
10610     // Destructors don't have return types, but the parser will
10611     // happily parse something like:
10612     //
10613     //   class X {
10614     //     float ~X();
10615     //   };
10616     //
10617     // The return type will be eliminated later.
10618     if (D.getDeclSpec().hasTypeSpecifier())
10619       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10620         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10621         << SourceRange(D.getIdentifierLoc());
10622     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10623       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10624                                 SourceLocation(),
10625                                 D.getDeclSpec().getConstSpecLoc(),
10626                                 D.getDeclSpec().getVolatileSpecLoc(),
10627                                 D.getDeclSpec().getRestrictSpecLoc(),
10628                                 D.getDeclSpec().getAtomicSpecLoc());
10629       D.setInvalidType();
10630     }
10631   }
10632 
10633   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10634 
10635   // C++0x [class.dtor]p2:
10636   //   A destructor shall not be declared with a ref-qualifier.
10637   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10638   if (FTI.hasRefQualifier()) {
10639     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10640       << FTI.RefQualifierIsLValueRef
10641       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10642     D.setInvalidType();
10643   }
10644 
10645   // Make sure we don't have any parameters.
10646   if (FTIHasNonVoidParameters(FTI)) {
10647     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10648 
10649     // Delete the parameters.
10650     FTI.freeParams();
10651     D.setInvalidType();
10652   }
10653 
10654   // Make sure the destructor isn't variadic.
10655   if (FTI.isVariadic) {
10656     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10657     D.setInvalidType();
10658   }
10659 
10660   // Rebuild the function type "R" without any type qualifiers or
10661   // parameters (in case any of the errors above fired) and with
10662   // "void" as the return type, since destructors don't have return
10663   // types.
10664   if (!D.isInvalidType())
10665     return R;
10666 
10667   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10668   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10669   EPI.Variadic = false;
10670   EPI.TypeQuals = Qualifiers();
10671   EPI.RefQualifier = RQ_None;
10672   return Context.getFunctionType(Context.VoidTy, None, EPI);
10673 }
10674 
10675 static void extendLeft(SourceRange &R, SourceRange Before) {
10676   if (Before.isInvalid())
10677     return;
10678   R.setBegin(Before.getBegin());
10679   if (R.getEnd().isInvalid())
10680     R.setEnd(Before.getEnd());
10681 }
10682 
10683 static void extendRight(SourceRange &R, SourceRange After) {
10684   if (After.isInvalid())
10685     return;
10686   if (R.getBegin().isInvalid())
10687     R.setBegin(After.getBegin());
10688   R.setEnd(After.getEnd());
10689 }
10690 
10691 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10692 /// well-formednes of the conversion function declarator @p D with
10693 /// type @p R. If there are any errors in the declarator, this routine
10694 /// will emit diagnostics and return true. Otherwise, it will return
10695 /// false. Either way, the type @p R will be updated to reflect a
10696 /// well-formed type for the conversion operator.
10697 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10698                                      StorageClass& SC) {
10699   // C++ [class.conv.fct]p1:
10700   //   Neither parameter types nor return type can be specified. The
10701   //   type of a conversion function (8.3.5) is "function taking no
10702   //   parameter returning conversion-type-id."
10703   if (SC == SC_Static) {
10704     if (!D.isInvalidType())
10705       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10706         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10707         << D.getName().getSourceRange();
10708     D.setInvalidType();
10709     SC = SC_None;
10710   }
10711 
10712   TypeSourceInfo *ConvTSI = nullptr;
10713   QualType ConvType =
10714       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10715 
10716   const DeclSpec &DS = D.getDeclSpec();
10717   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10718     // Conversion functions don't have return types, but the parser will
10719     // happily parse something like:
10720     //
10721     //   class X {
10722     //     float operator bool();
10723     //   };
10724     //
10725     // The return type will be changed later anyway.
10726     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10727       << SourceRange(DS.getTypeSpecTypeLoc())
10728       << SourceRange(D.getIdentifierLoc());
10729     D.setInvalidType();
10730   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10731     // It's also plausible that the user writes type qualifiers in the wrong
10732     // place, such as:
10733     //   struct S { const operator int(); };
10734     // FIXME: we could provide a fixit to move the qualifiers onto the
10735     // conversion type.
10736     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10737         << SourceRange(D.getIdentifierLoc()) << 0;
10738     D.setInvalidType();
10739   }
10740 
10741   const auto *Proto = R->castAs<FunctionProtoType>();
10742 
10743   // Make sure we don't have any parameters.
10744   if (Proto->getNumParams() > 0) {
10745     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10746 
10747     // Delete the parameters.
10748     D.getFunctionTypeInfo().freeParams();
10749     D.setInvalidType();
10750   } else if (Proto->isVariadic()) {
10751     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10752     D.setInvalidType();
10753   }
10754 
10755   // Diagnose "&operator bool()" and other such nonsense.  This
10756   // is actually a gcc extension which we don't support.
10757   if (Proto->getReturnType() != ConvType) {
10758     bool NeedsTypedef = false;
10759     SourceRange Before, After;
10760 
10761     // Walk the chunks and extract information on them for our diagnostic.
10762     bool PastFunctionChunk = false;
10763     for (auto &Chunk : D.type_objects()) {
10764       switch (Chunk.Kind) {
10765       case DeclaratorChunk::Function:
10766         if (!PastFunctionChunk) {
10767           if (Chunk.Fun.HasTrailingReturnType) {
10768             TypeSourceInfo *TRT = nullptr;
10769             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10770             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10771           }
10772           PastFunctionChunk = true;
10773           break;
10774         }
10775         LLVM_FALLTHROUGH;
10776       case DeclaratorChunk::Array:
10777         NeedsTypedef = true;
10778         extendRight(After, Chunk.getSourceRange());
10779         break;
10780 
10781       case DeclaratorChunk::Pointer:
10782       case DeclaratorChunk::BlockPointer:
10783       case DeclaratorChunk::Reference:
10784       case DeclaratorChunk::MemberPointer:
10785       case DeclaratorChunk::Pipe:
10786         extendLeft(Before, Chunk.getSourceRange());
10787         break;
10788 
10789       case DeclaratorChunk::Paren:
10790         extendLeft(Before, Chunk.Loc);
10791         extendRight(After, Chunk.EndLoc);
10792         break;
10793       }
10794     }
10795 
10796     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10797                          After.isValid()  ? After.getBegin() :
10798                                             D.getIdentifierLoc();
10799     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10800     DB << Before << After;
10801 
10802     if (!NeedsTypedef) {
10803       DB << /*don't need a typedef*/0;
10804 
10805       // If we can provide a correct fix-it hint, do so.
10806       if (After.isInvalid() && ConvTSI) {
10807         SourceLocation InsertLoc =
10808             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10809         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10810            << FixItHint::CreateInsertionFromRange(
10811                   InsertLoc, CharSourceRange::getTokenRange(Before))
10812            << FixItHint::CreateRemoval(Before);
10813       }
10814     } else if (!Proto->getReturnType()->isDependentType()) {
10815       DB << /*typedef*/1 << Proto->getReturnType();
10816     } else if (getLangOpts().CPlusPlus11) {
10817       DB << /*alias template*/2 << Proto->getReturnType();
10818     } else {
10819       DB << /*might not be fixable*/3;
10820     }
10821 
10822     // Recover by incorporating the other type chunks into the result type.
10823     // Note, this does *not* change the name of the function. This is compatible
10824     // with the GCC extension:
10825     //   struct S { &operator int(); } s;
10826     //   int &r = s.operator int(); // ok in GCC
10827     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10828     ConvType = Proto->getReturnType();
10829   }
10830 
10831   // C++ [class.conv.fct]p4:
10832   //   The conversion-type-id shall not represent a function type nor
10833   //   an array type.
10834   if (ConvType->isArrayType()) {
10835     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10836     ConvType = Context.getPointerType(ConvType);
10837     D.setInvalidType();
10838   } else if (ConvType->isFunctionType()) {
10839     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10840     ConvType = Context.getPointerType(ConvType);
10841     D.setInvalidType();
10842   }
10843 
10844   // Rebuild the function type "R" without any parameters (in case any
10845   // of the errors above fired) and with the conversion type as the
10846   // return type.
10847   if (D.isInvalidType())
10848     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10849 
10850   // C++0x explicit conversion operators.
10851   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10852     Diag(DS.getExplicitSpecLoc(),
10853          getLangOpts().CPlusPlus11
10854              ? diag::warn_cxx98_compat_explicit_conversion_functions
10855              : diag::ext_explicit_conversion_functions)
10856         << SourceRange(DS.getExplicitSpecRange());
10857 }
10858 
10859 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10860 /// the declaration of the given C++ conversion function. This routine
10861 /// is responsible for recording the conversion function in the C++
10862 /// class, if possible.
10863 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10864   assert(Conversion && "Expected to receive a conversion function declaration");
10865 
10866   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10867 
10868   // Make sure we aren't redeclaring the conversion function.
10869   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10870   // C++ [class.conv.fct]p1:
10871   //   [...] A conversion function is never used to convert a
10872   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10873   //   same object type (or a reference to it), to a (possibly
10874   //   cv-qualified) base class of that type (or a reference to it),
10875   //   or to (possibly cv-qualified) void.
10876   QualType ClassType
10877     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10878   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10879     ConvType = ConvTypeRef->getPointeeType();
10880   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10881       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10882     /* Suppress diagnostics for instantiations. */;
10883   else if (Conversion->size_overridden_methods() != 0)
10884     /* Suppress diagnostics for overriding virtual function in a base class. */;
10885   else if (ConvType->isRecordType()) {
10886     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10887     if (ConvType == ClassType)
10888       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10889         << ClassType;
10890     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10891       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10892         <<  ClassType << ConvType;
10893   } else if (ConvType->isVoidType()) {
10894     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10895       << ClassType << ConvType;
10896   }
10897 
10898   if (FunctionTemplateDecl *ConversionTemplate
10899                                 = Conversion->getDescribedFunctionTemplate())
10900     return ConversionTemplate;
10901 
10902   return Conversion;
10903 }
10904 
10905 namespace {
10906 /// Utility class to accumulate and print a diagnostic listing the invalid
10907 /// specifier(s) on a declaration.
10908 struct BadSpecifierDiagnoser {
10909   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10910       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10911   ~BadSpecifierDiagnoser() {
10912     Diagnostic << Specifiers;
10913   }
10914 
10915   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10916     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10917   }
10918   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10919     return check(SpecLoc,
10920                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10921   }
10922   void check(SourceLocation SpecLoc, const char *Spec) {
10923     if (SpecLoc.isInvalid()) return;
10924     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10925     if (!Specifiers.empty()) Specifiers += " ";
10926     Specifiers += Spec;
10927   }
10928 
10929   Sema &S;
10930   Sema::SemaDiagnosticBuilder Diagnostic;
10931   std::string Specifiers;
10932 };
10933 }
10934 
10935 /// Check the validity of a declarator that we parsed for a deduction-guide.
10936 /// These aren't actually declarators in the grammar, so we need to check that
10937 /// the user didn't specify any pieces that are not part of the deduction-guide
10938 /// grammar.
10939 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10940                                          StorageClass &SC) {
10941   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10942   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10943   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10944 
10945   // C++ [temp.deduct.guide]p3:
10946   //   A deduction-gide shall be declared in the same scope as the
10947   //   corresponding class template.
10948   if (!CurContext->getRedeclContext()->Equals(
10949           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10950     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10951       << GuidedTemplateDecl;
10952     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10953   }
10954 
10955   auto &DS = D.getMutableDeclSpec();
10956   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10957   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10958       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10959       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10960     BadSpecifierDiagnoser Diagnoser(
10961         *this, D.getIdentifierLoc(),
10962         diag::err_deduction_guide_invalid_specifier);
10963 
10964     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10965     DS.ClearStorageClassSpecs();
10966     SC = SC_None;
10967 
10968     // 'explicit' is permitted.
10969     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10970     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10971     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10972     DS.ClearConstexprSpec();
10973 
10974     Diagnoser.check(DS.getConstSpecLoc(), "const");
10975     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10976     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10977     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10978     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10979     DS.ClearTypeQualifiers();
10980 
10981     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10982     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10983     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10984     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10985     DS.ClearTypeSpecType();
10986   }
10987 
10988   if (D.isInvalidType())
10989     return;
10990 
10991   // Check the declarator is simple enough.
10992   bool FoundFunction = false;
10993   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10994     if (Chunk.Kind == DeclaratorChunk::Paren)
10995       continue;
10996     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10997       Diag(D.getDeclSpec().getBeginLoc(),
10998            diag::err_deduction_guide_with_complex_decl)
10999           << D.getSourceRange();
11000       break;
11001     }
11002     if (!Chunk.Fun.hasTrailingReturnType()) {
11003       Diag(D.getName().getBeginLoc(),
11004            diag::err_deduction_guide_no_trailing_return_type);
11005       break;
11006     }
11007 
11008     // Check that the return type is written as a specialization of
11009     // the template specified as the deduction-guide's name.
11010     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11011     TypeSourceInfo *TSI = nullptr;
11012     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11013     assert(TSI && "deduction guide has valid type but invalid return type?");
11014     bool AcceptableReturnType = false;
11015     bool MightInstantiateToSpecialization = false;
11016     if (auto RetTST =
11017             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
11018       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11019       bool TemplateMatches =
11020           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11021       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
11022         AcceptableReturnType = true;
11023       else {
11024         // This could still instantiate to the right type, unless we know it
11025         // names the wrong class template.
11026         auto *TD = SpecifiedName.getAsTemplateDecl();
11027         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11028                                              !TemplateMatches);
11029       }
11030     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11031       MightInstantiateToSpecialization = true;
11032     }
11033 
11034     if (!AcceptableReturnType) {
11035       Diag(TSI->getTypeLoc().getBeginLoc(),
11036            diag::err_deduction_guide_bad_trailing_return_type)
11037           << GuidedTemplate << TSI->getType()
11038           << MightInstantiateToSpecialization
11039           << TSI->getTypeLoc().getSourceRange();
11040     }
11041 
11042     // Keep going to check that we don't have any inner declarator pieces (we
11043     // could still have a function returning a pointer to a function).
11044     FoundFunction = true;
11045   }
11046 
11047   if (D.isFunctionDefinition())
11048     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11049 }
11050 
11051 //===----------------------------------------------------------------------===//
11052 // Namespace Handling
11053 //===----------------------------------------------------------------------===//
11054 
11055 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11056 /// reopened.
11057 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11058                                             SourceLocation Loc,
11059                                             IdentifierInfo *II, bool *IsInline,
11060                                             NamespaceDecl *PrevNS) {
11061   assert(*IsInline != PrevNS->isInline());
11062 
11063   // 'inline' must appear on the original definition, but not necessarily
11064   // on all extension definitions, so the note should point to the first
11065   // definition to avoid confusion.
11066   PrevNS = PrevNS->getFirstDecl();
11067 
11068   if (PrevNS->isInline())
11069     // The user probably just forgot the 'inline', so suggest that it
11070     // be added back.
11071     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11072       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11073   else
11074     S.Diag(Loc, diag::err_inline_namespace_mismatch);
11075 
11076   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11077   *IsInline = PrevNS->isInline();
11078 }
11079 
11080 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11081 /// definition.
11082 Decl *Sema::ActOnStartNamespaceDef(
11083     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
11084     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
11085     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
11086   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11087   // For anonymous namespace, take the location of the left brace.
11088   SourceLocation Loc = II ? IdentLoc : LBrace;
11089   bool IsInline = InlineLoc.isValid();
11090   bool IsInvalid = false;
11091   bool IsStd = false;
11092   bool AddToKnown = false;
11093   Scope *DeclRegionScope = NamespcScope->getParent();
11094 
11095   NamespaceDecl *PrevNS = nullptr;
11096   if (II) {
11097     // C++ [namespace.def]p2:
11098     //   The identifier in an original-namespace-definition shall not
11099     //   have been previously defined in the declarative region in
11100     //   which the original-namespace-definition appears. The
11101     //   identifier in an original-namespace-definition is the name of
11102     //   the namespace. Subsequently in that declarative region, it is
11103     //   treated as an original-namespace-name.
11104     //
11105     // Since namespace names are unique in their scope, and we don't
11106     // look through using directives, just look for any ordinary names
11107     // as if by qualified name lookup.
11108     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11109                    ForExternalRedeclaration);
11110     LookupQualifiedName(R, CurContext->getRedeclContext());
11111     NamedDecl *PrevDecl =
11112         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11113     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11114 
11115     if (PrevNS) {
11116       // This is an extended namespace definition.
11117       if (IsInline != PrevNS->isInline())
11118         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11119                                         &IsInline, PrevNS);
11120     } else if (PrevDecl) {
11121       // This is an invalid name redefinition.
11122       Diag(Loc, diag::err_redefinition_different_kind)
11123         << II;
11124       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11125       IsInvalid = true;
11126       // Continue on to push Namespc as current DeclContext and return it.
11127     } else if (II->isStr("std") &&
11128                CurContext->getRedeclContext()->isTranslationUnit()) {
11129       // This is the first "real" definition of the namespace "std", so update
11130       // our cache of the "std" namespace to point at this definition.
11131       PrevNS = getStdNamespace();
11132       IsStd = true;
11133       AddToKnown = !IsInline;
11134     } else {
11135       // We've seen this namespace for the first time.
11136       AddToKnown = !IsInline;
11137     }
11138   } else {
11139     // Anonymous namespaces.
11140 
11141     // Determine whether the parent already has an anonymous namespace.
11142     DeclContext *Parent = CurContext->getRedeclContext();
11143     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11144       PrevNS = TU->getAnonymousNamespace();
11145     } else {
11146       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11147       PrevNS = ND->getAnonymousNamespace();
11148     }
11149 
11150     if (PrevNS && IsInline != PrevNS->isInline())
11151       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11152                                       &IsInline, PrevNS);
11153   }
11154 
11155   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
11156                                                  StartLoc, Loc, II, PrevNS);
11157   if (IsInvalid)
11158     Namespc->setInvalidDecl();
11159 
11160   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11161   AddPragmaAttributes(DeclRegionScope, Namespc);
11162 
11163   // FIXME: Should we be merging attributes?
11164   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11165     PushNamespaceVisibilityAttr(Attr, Loc);
11166 
11167   if (IsStd)
11168     StdNamespace = Namespc;
11169   if (AddToKnown)
11170     KnownNamespaces[Namespc] = false;
11171 
11172   if (II) {
11173     PushOnScopeChains(Namespc, DeclRegionScope);
11174   } else {
11175     // Link the anonymous namespace into its parent.
11176     DeclContext *Parent = CurContext->getRedeclContext();
11177     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11178       TU->setAnonymousNamespace(Namespc);
11179     } else {
11180       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11181     }
11182 
11183     CurContext->addDecl(Namespc);
11184 
11185     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11186     //   behaves as if it were replaced by
11187     //     namespace unique { /* empty body */ }
11188     //     using namespace unique;
11189     //     namespace unique { namespace-body }
11190     //   where all occurrences of 'unique' in a translation unit are
11191     //   replaced by the same identifier and this identifier differs
11192     //   from all other identifiers in the entire program.
11193 
11194     // We just create the namespace with an empty name and then add an
11195     // implicit using declaration, just like the standard suggests.
11196     //
11197     // CodeGen enforces the "universally unique" aspect by giving all
11198     // declarations semantically contained within an anonymous
11199     // namespace internal linkage.
11200 
11201     if (!PrevNS) {
11202       UD = UsingDirectiveDecl::Create(Context, Parent,
11203                                       /* 'using' */ LBrace,
11204                                       /* 'namespace' */ SourceLocation(),
11205                                       /* qualifier */ NestedNameSpecifierLoc(),
11206                                       /* identifier */ SourceLocation(),
11207                                       Namespc,
11208                                       /* Ancestor */ Parent);
11209       UD->setImplicit();
11210       Parent->addDecl(UD);
11211     }
11212   }
11213 
11214   ActOnDocumentableDecl(Namespc);
11215 
11216   // Although we could have an invalid decl (i.e. the namespace name is a
11217   // redefinition), push it as current DeclContext and try to continue parsing.
11218   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11219   // for the namespace has the declarations that showed up in that particular
11220   // namespace definition.
11221   PushDeclContext(NamespcScope, Namespc);
11222   return Namespc;
11223 }
11224 
11225 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11226 /// is a namespace alias, returns the namespace it points to.
11227 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11228   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11229     return AD->getNamespace();
11230   return dyn_cast_or_null<NamespaceDecl>(D);
11231 }
11232 
11233 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11234 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11235 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11236   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11237   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11238   Namespc->setRBraceLoc(RBrace);
11239   PopDeclContext();
11240   if (Namespc->hasAttr<VisibilityAttr>())
11241     PopPragmaVisibility(true, RBrace);
11242   // If this namespace contains an export-declaration, export it now.
11243   if (DeferredExportedNamespaces.erase(Namespc))
11244     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11245 }
11246 
11247 CXXRecordDecl *Sema::getStdBadAlloc() const {
11248   return cast_or_null<CXXRecordDecl>(
11249                                   StdBadAlloc.get(Context.getExternalSource()));
11250 }
11251 
11252 EnumDecl *Sema::getStdAlignValT() const {
11253   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11254 }
11255 
11256 NamespaceDecl *Sema::getStdNamespace() const {
11257   return cast_or_null<NamespaceDecl>(
11258                                  StdNamespace.get(Context.getExternalSource()));
11259 }
11260 
11261 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11262   if (!StdExperimentalNamespaceCache) {
11263     if (auto Std = getStdNamespace()) {
11264       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11265                           SourceLocation(), LookupNamespaceName);
11266       if (!LookupQualifiedName(Result, Std) ||
11267           !(StdExperimentalNamespaceCache =
11268                 Result.getAsSingle<NamespaceDecl>()))
11269         Result.suppressDiagnostics();
11270     }
11271   }
11272   return StdExperimentalNamespaceCache;
11273 }
11274 
11275 namespace {
11276 
11277 enum UnsupportedSTLSelect {
11278   USS_InvalidMember,
11279   USS_MissingMember,
11280   USS_NonTrivial,
11281   USS_Other
11282 };
11283 
11284 struct InvalidSTLDiagnoser {
11285   Sema &S;
11286   SourceLocation Loc;
11287   QualType TyForDiags;
11288 
11289   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11290                       const VarDecl *VD = nullptr) {
11291     {
11292       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11293                << TyForDiags << ((int)Sel);
11294       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11295         assert(!Name.empty());
11296         D << Name;
11297       }
11298     }
11299     if (Sel == USS_InvalidMember) {
11300       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11301           << VD << VD->getSourceRange();
11302     }
11303     return QualType();
11304   }
11305 };
11306 } // namespace
11307 
11308 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11309                                            SourceLocation Loc,
11310                                            ComparisonCategoryUsage Usage) {
11311   assert(getLangOpts().CPlusPlus &&
11312          "Looking for comparison category type outside of C++.");
11313 
11314   // Use an elaborated type for diagnostics which has a name containing the
11315   // prepended 'std' namespace but not any inline namespace names.
11316   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11317     auto *NNS =
11318         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11319     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11320   };
11321 
11322   // Check if we've already successfully checked the comparison category type
11323   // before. If so, skip checking it again.
11324   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11325   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11326     // The only thing we need to check is that the type has a reachable
11327     // definition in the current context.
11328     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11329       return QualType();
11330 
11331     return Info->getType();
11332   }
11333 
11334   // If lookup failed
11335   if (!Info) {
11336     std::string NameForDiags = "std::";
11337     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11338     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11339         << NameForDiags << (int)Usage;
11340     return QualType();
11341   }
11342 
11343   assert(Info->Kind == Kind);
11344   assert(Info->Record);
11345 
11346   // Update the Record decl in case we encountered a forward declaration on our
11347   // first pass. FIXME: This is a bit of a hack.
11348   if (Info->Record->hasDefinition())
11349     Info->Record = Info->Record->getDefinition();
11350 
11351   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11352     return QualType();
11353 
11354   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11355 
11356   if (!Info->Record->isTriviallyCopyable())
11357     return UnsupportedSTLError(USS_NonTrivial);
11358 
11359   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11360     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11361     // Tolerate empty base classes.
11362     if (Base->isEmpty())
11363       continue;
11364     // Reject STL implementations which have at least one non-empty base.
11365     return UnsupportedSTLError();
11366   }
11367 
11368   // Check that the STL has implemented the types using a single integer field.
11369   // This expectation allows better codegen for builtin operators. We require:
11370   //   (1) The class has exactly one field.
11371   //   (2) The field is an integral or enumeration type.
11372   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11373   if (std::distance(FIt, FEnd) != 1 ||
11374       !FIt->getType()->isIntegralOrEnumerationType()) {
11375     return UnsupportedSTLError();
11376   }
11377 
11378   // Build each of the require values and store them in Info.
11379   for (ComparisonCategoryResult CCR :
11380        ComparisonCategories::getPossibleResultsForType(Kind)) {
11381     StringRef MemName = ComparisonCategories::getResultString(CCR);
11382     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11383 
11384     if (!ValInfo)
11385       return UnsupportedSTLError(USS_MissingMember, MemName);
11386 
11387     VarDecl *VD = ValInfo->VD;
11388     assert(VD && "should not be null!");
11389 
11390     // Attempt to diagnose reasons why the STL definition of this type
11391     // might be foobar, including it failing to be a constant expression.
11392     // TODO Handle more ways the lookup or result can be invalid.
11393     if (!VD->isStaticDataMember() ||
11394         !VD->isUsableInConstantExpressions(Context))
11395       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11396 
11397     // Attempt to evaluate the var decl as a constant expression and extract
11398     // the value of its first field as a ICE. If this fails, the STL
11399     // implementation is not supported.
11400     if (!ValInfo->hasValidIntValue())
11401       return UnsupportedSTLError();
11402 
11403     MarkVariableReferenced(Loc, VD);
11404   }
11405 
11406   // We've successfully built the required types and expressions. Update
11407   // the cache and return the newly cached value.
11408   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11409   return Info->getType();
11410 }
11411 
11412 /// Retrieve the special "std" namespace, which may require us to
11413 /// implicitly define the namespace.
11414 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11415   if (!StdNamespace) {
11416     // The "std" namespace has not yet been defined, so build one implicitly.
11417     StdNamespace = NamespaceDecl::Create(Context,
11418                                          Context.getTranslationUnitDecl(),
11419                                          /*Inline=*/false,
11420                                          SourceLocation(), SourceLocation(),
11421                                          &PP.getIdentifierTable().get("std"),
11422                                          /*PrevDecl=*/nullptr);
11423     getStdNamespace()->setImplicit(true);
11424   }
11425 
11426   return getStdNamespace();
11427 }
11428 
11429 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11430   assert(getLangOpts().CPlusPlus &&
11431          "Looking for std::initializer_list outside of C++.");
11432 
11433   // We're looking for implicit instantiations of
11434   // template <typename E> class std::initializer_list.
11435 
11436   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11437     return false;
11438 
11439   ClassTemplateDecl *Template = nullptr;
11440   const TemplateArgument *Arguments = nullptr;
11441 
11442   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11443 
11444     ClassTemplateSpecializationDecl *Specialization =
11445         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11446     if (!Specialization)
11447       return false;
11448 
11449     Template = Specialization->getSpecializedTemplate();
11450     Arguments = Specialization->getTemplateArgs().data();
11451   } else if (const TemplateSpecializationType *TST =
11452                  Ty->getAs<TemplateSpecializationType>()) {
11453     Template = dyn_cast_or_null<ClassTemplateDecl>(
11454         TST->getTemplateName().getAsTemplateDecl());
11455     Arguments = TST->getArgs();
11456   }
11457   if (!Template)
11458     return false;
11459 
11460   if (!StdInitializerList) {
11461     // Haven't recognized std::initializer_list yet, maybe this is it.
11462     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11463     if (TemplateClass->getIdentifier() !=
11464             &PP.getIdentifierTable().get("initializer_list") ||
11465         !getStdNamespace()->InEnclosingNamespaceSetOf(
11466             TemplateClass->getDeclContext()))
11467       return false;
11468     // This is a template called std::initializer_list, but is it the right
11469     // template?
11470     TemplateParameterList *Params = Template->getTemplateParameters();
11471     if (Params->getMinRequiredArguments() != 1)
11472       return false;
11473     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11474       return false;
11475 
11476     // It's the right template.
11477     StdInitializerList = Template;
11478   }
11479 
11480   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11481     return false;
11482 
11483   // This is an instance of std::initializer_list. Find the argument type.
11484   if (Element)
11485     *Element = Arguments[0].getAsType();
11486   return true;
11487 }
11488 
11489 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11490   NamespaceDecl *Std = S.getStdNamespace();
11491   if (!Std) {
11492     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11493     return nullptr;
11494   }
11495 
11496   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11497                       Loc, Sema::LookupOrdinaryName);
11498   if (!S.LookupQualifiedName(Result, Std)) {
11499     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11500     return nullptr;
11501   }
11502   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11503   if (!Template) {
11504     Result.suppressDiagnostics();
11505     // We found something weird. Complain about the first thing we found.
11506     NamedDecl *Found = *Result.begin();
11507     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11508     return nullptr;
11509   }
11510 
11511   // We found some template called std::initializer_list. Now verify that it's
11512   // correct.
11513   TemplateParameterList *Params = Template->getTemplateParameters();
11514   if (Params->getMinRequiredArguments() != 1 ||
11515       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11516     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11517     return nullptr;
11518   }
11519 
11520   return Template;
11521 }
11522 
11523 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11524   if (!StdInitializerList) {
11525     StdInitializerList = LookupStdInitializerList(*this, Loc);
11526     if (!StdInitializerList)
11527       return QualType();
11528   }
11529 
11530   TemplateArgumentListInfo Args(Loc, Loc);
11531   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11532                                        Context.getTrivialTypeSourceInfo(Element,
11533                                                                         Loc)));
11534   return Context.getCanonicalType(
11535       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11536 }
11537 
11538 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11539   // C++ [dcl.init.list]p2:
11540   //   A constructor is an initializer-list constructor if its first parameter
11541   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11542   //   std::initializer_list<E> for some type E, and either there are no other
11543   //   parameters or else all other parameters have default arguments.
11544   if (!Ctor->hasOneParamOrDefaultArgs())
11545     return false;
11546 
11547   QualType ArgType = Ctor->getParamDecl(0)->getType();
11548   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11549     ArgType = RT->getPointeeType().getUnqualifiedType();
11550 
11551   return isStdInitializerList(ArgType, nullptr);
11552 }
11553 
11554 /// Determine whether a using statement is in a context where it will be
11555 /// apply in all contexts.
11556 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11557   switch (CurContext->getDeclKind()) {
11558     case Decl::TranslationUnit:
11559       return true;
11560     case Decl::LinkageSpec:
11561       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11562     default:
11563       return false;
11564   }
11565 }
11566 
11567 namespace {
11568 
11569 // Callback to only accept typo corrections that are namespaces.
11570 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11571 public:
11572   bool ValidateCandidate(const TypoCorrection &candidate) override {
11573     if (NamedDecl *ND = candidate.getCorrectionDecl())
11574       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11575     return false;
11576   }
11577 
11578   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11579     return std::make_unique<NamespaceValidatorCCC>(*this);
11580   }
11581 };
11582 
11583 }
11584 
11585 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11586                                        CXXScopeSpec &SS,
11587                                        SourceLocation IdentLoc,
11588                                        IdentifierInfo *Ident) {
11589   R.clear();
11590   NamespaceValidatorCCC CCC{};
11591   if (TypoCorrection Corrected =
11592           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11593                         Sema::CTK_ErrorRecovery)) {
11594     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11595       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11596       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11597                               Ident->getName().equals(CorrectedStr);
11598       S.diagnoseTypo(Corrected,
11599                      S.PDiag(diag::err_using_directive_member_suggest)
11600                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11601                      S.PDiag(diag::note_namespace_defined_here));
11602     } else {
11603       S.diagnoseTypo(Corrected,
11604                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11605                      S.PDiag(diag::note_namespace_defined_here));
11606     }
11607     R.addDecl(Corrected.getFoundDecl());
11608     return true;
11609   }
11610   return false;
11611 }
11612 
11613 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11614                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11615                                 SourceLocation IdentLoc,
11616                                 IdentifierInfo *NamespcName,
11617                                 const ParsedAttributesView &AttrList) {
11618   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11619   assert(NamespcName && "Invalid NamespcName.");
11620   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11621 
11622   // This can only happen along a recovery path.
11623   while (S->isTemplateParamScope())
11624     S = S->getParent();
11625   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11626 
11627   UsingDirectiveDecl *UDir = nullptr;
11628   NestedNameSpecifier *Qualifier = nullptr;
11629   if (SS.isSet())
11630     Qualifier = SS.getScopeRep();
11631 
11632   // Lookup namespace name.
11633   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11634   LookupParsedName(R, S, &SS);
11635   if (R.isAmbiguous())
11636     return nullptr;
11637 
11638   if (R.empty()) {
11639     R.clear();
11640     // Allow "using namespace std;" or "using namespace ::std;" even if
11641     // "std" hasn't been defined yet, for GCC compatibility.
11642     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11643         NamespcName->isStr("std")) {
11644       Diag(IdentLoc, diag::ext_using_undefined_std);
11645       R.addDecl(getOrCreateStdNamespace());
11646       R.resolveKind();
11647     }
11648     // Otherwise, attempt typo correction.
11649     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11650   }
11651 
11652   if (!R.empty()) {
11653     NamedDecl *Named = R.getRepresentativeDecl();
11654     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11655     assert(NS && "expected namespace decl");
11656 
11657     // The use of a nested name specifier may trigger deprecation warnings.
11658     DiagnoseUseOfDecl(Named, IdentLoc);
11659 
11660     // C++ [namespace.udir]p1:
11661     //   A using-directive specifies that the names in the nominated
11662     //   namespace can be used in the scope in which the
11663     //   using-directive appears after the using-directive. During
11664     //   unqualified name lookup (3.4.1), the names appear as if they
11665     //   were declared in the nearest enclosing namespace which
11666     //   contains both the using-directive and the nominated
11667     //   namespace. [Note: in this context, "contains" means "contains
11668     //   directly or indirectly". ]
11669 
11670     // Find enclosing context containing both using-directive and
11671     // nominated namespace.
11672     DeclContext *CommonAncestor = NS;
11673     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11674       CommonAncestor = CommonAncestor->getParent();
11675 
11676     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11677                                       SS.getWithLocInContext(Context),
11678                                       IdentLoc, Named, CommonAncestor);
11679 
11680     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11681         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11682       Diag(IdentLoc, diag::warn_using_directive_in_header);
11683     }
11684 
11685     PushUsingDirective(S, UDir);
11686   } else {
11687     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11688   }
11689 
11690   if (UDir)
11691     ProcessDeclAttributeList(S, UDir, AttrList);
11692 
11693   return UDir;
11694 }
11695 
11696 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11697   // If the scope has an associated entity and the using directive is at
11698   // namespace or translation unit scope, add the UsingDirectiveDecl into
11699   // its lookup structure so qualified name lookup can find it.
11700   DeclContext *Ctx = S->getEntity();
11701   if (Ctx && !Ctx->isFunctionOrMethod())
11702     Ctx->addDecl(UDir);
11703   else
11704     // Otherwise, it is at block scope. The using-directives will affect lookup
11705     // only to the end of the scope.
11706     S->PushUsingDirective(UDir);
11707 }
11708 
11709 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11710                                   SourceLocation UsingLoc,
11711                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11712                                   UnqualifiedId &Name,
11713                                   SourceLocation EllipsisLoc,
11714                                   const ParsedAttributesView &AttrList) {
11715   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11716 
11717   if (SS.isEmpty()) {
11718     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11719     return nullptr;
11720   }
11721 
11722   switch (Name.getKind()) {
11723   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11724   case UnqualifiedIdKind::IK_Identifier:
11725   case UnqualifiedIdKind::IK_OperatorFunctionId:
11726   case UnqualifiedIdKind::IK_LiteralOperatorId:
11727   case UnqualifiedIdKind::IK_ConversionFunctionId:
11728     break;
11729 
11730   case UnqualifiedIdKind::IK_ConstructorName:
11731   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11732     // C++11 inheriting constructors.
11733     Diag(Name.getBeginLoc(),
11734          getLangOpts().CPlusPlus11
11735              ? diag::warn_cxx98_compat_using_decl_constructor
11736              : diag::err_using_decl_constructor)
11737         << SS.getRange();
11738 
11739     if (getLangOpts().CPlusPlus11) break;
11740 
11741     return nullptr;
11742 
11743   case UnqualifiedIdKind::IK_DestructorName:
11744     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11745     return nullptr;
11746 
11747   case UnqualifiedIdKind::IK_TemplateId:
11748     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11749         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11750     return nullptr;
11751 
11752   case UnqualifiedIdKind::IK_DeductionGuideName:
11753     llvm_unreachable("cannot parse qualified deduction guide name");
11754   }
11755 
11756   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11757   DeclarationName TargetName = TargetNameInfo.getName();
11758   if (!TargetName)
11759     return nullptr;
11760 
11761   // Warn about access declarations.
11762   if (UsingLoc.isInvalid()) {
11763     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11764                                  ? diag::err_access_decl
11765                                  : diag::warn_access_decl_deprecated)
11766         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11767   }
11768 
11769   if (EllipsisLoc.isInvalid()) {
11770     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11771         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11772       return nullptr;
11773   } else {
11774     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11775         !TargetNameInfo.containsUnexpandedParameterPack()) {
11776       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11777         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11778       EllipsisLoc = SourceLocation();
11779     }
11780   }
11781 
11782   NamedDecl *UD =
11783       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11784                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11785                             /*IsInstantiation*/ false,
11786                             AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11787   if (UD)
11788     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11789 
11790   return UD;
11791 }
11792 
11793 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
11794                                       SourceLocation UsingLoc,
11795                                       SourceLocation EnumLoc,
11796                                       const DeclSpec &DS) {
11797   switch (DS.getTypeSpecType()) {
11798   case DeclSpec::TST_error:
11799     // This will already have been diagnosed
11800     return nullptr;
11801 
11802   case DeclSpec::TST_enum:
11803     break;
11804 
11805   case DeclSpec::TST_typename:
11806     Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
11807     return nullptr;
11808 
11809   default:
11810     llvm_unreachable("unexpected DeclSpec type");
11811   }
11812 
11813   // As with enum-decls, we ignore attributes for now.
11814   auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
11815   if (auto *Def = Enum->getDefinition())
11816     Enum = Def;
11817 
11818   auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
11819                                        DS.getTypeSpecTypeNameLoc(), Enum);
11820   if (UD)
11821     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11822 
11823   return UD;
11824 }
11825 
11826 /// Determine whether a using declaration considers the given
11827 /// declarations as "equivalent", e.g., if they are redeclarations of
11828 /// the same entity or are both typedefs of the same type.
11829 static bool
11830 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11831   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11832     return true;
11833 
11834   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11835     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11836       return Context.hasSameType(TD1->getUnderlyingType(),
11837                                  TD2->getUnderlyingType());
11838 
11839   // Two using_if_exists using-declarations are equivalent if both are
11840   // unresolved.
11841   if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11842       isa<UnresolvedUsingIfExistsDecl>(D2))
11843     return true;
11844 
11845   return false;
11846 }
11847 
11848 
11849 /// Determines whether to create a using shadow decl for a particular
11850 /// decl, given the set of decls existing prior to this using lookup.
11851 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
11852                                 const LookupResult &Previous,
11853                                 UsingShadowDecl *&PrevShadow) {
11854   // Diagnose finding a decl which is not from a base class of the
11855   // current class.  We do this now because there are cases where this
11856   // function will silently decide not to build a shadow decl, which
11857   // will pre-empt further diagnostics.
11858   //
11859   // We don't need to do this in C++11 because we do the check once on
11860   // the qualifier.
11861   //
11862   // FIXME: diagnose the following if we care enough:
11863   //   struct A { int foo; };
11864   //   struct B : A { using A::foo; };
11865   //   template <class T> struct C : A {};
11866   //   template <class T> struct D : C<T> { using B::foo; } // <---
11867   // This is invalid (during instantiation) in C++03 because B::foo
11868   // resolves to the using decl in B, which is not a base class of D<T>.
11869   // We can't diagnose it immediately because C<T> is an unknown
11870   // specialization. The UsingShadowDecl in D<T> then points directly
11871   // to A::foo, which will look well-formed when we instantiate.
11872   // The right solution is to not collapse the shadow-decl chain.
11873   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
11874     if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
11875       DeclContext *OrigDC = Orig->getDeclContext();
11876 
11877       // Handle enums and anonymous structs.
11878       if (isa<EnumDecl>(OrigDC))
11879         OrigDC = OrigDC->getParent();
11880       CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11881       while (OrigRec->isAnonymousStructOrUnion())
11882         OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11883 
11884       if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11885         if (OrigDC == CurContext) {
11886           Diag(Using->getLocation(),
11887                diag::err_using_decl_nested_name_specifier_is_current_class)
11888               << Using->getQualifierLoc().getSourceRange();
11889           Diag(Orig->getLocation(), diag::note_using_decl_target);
11890           Using->setInvalidDecl();
11891           return true;
11892         }
11893 
11894         Diag(Using->getQualifierLoc().getBeginLoc(),
11895              diag::err_using_decl_nested_name_specifier_is_not_base_class)
11896             << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
11897             << Using->getQualifierLoc().getSourceRange();
11898         Diag(Orig->getLocation(), diag::note_using_decl_target);
11899         Using->setInvalidDecl();
11900         return true;
11901       }
11902     }
11903 
11904   if (Previous.empty()) return false;
11905 
11906   NamedDecl *Target = Orig;
11907   if (isa<UsingShadowDecl>(Target))
11908     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11909 
11910   // If the target happens to be one of the previous declarations, we
11911   // don't have a conflict.
11912   //
11913   // FIXME: but we might be increasing its access, in which case we
11914   // should redeclare it.
11915   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11916   bool FoundEquivalentDecl = false;
11917   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11918          I != E; ++I) {
11919     NamedDecl *D = (*I)->getUnderlyingDecl();
11920     // We can have UsingDecls in our Previous results because we use the same
11921     // LookupResult for checking whether the UsingDecl itself is a valid
11922     // redeclaration.
11923     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
11924       continue;
11925 
11926     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11927       // C++ [class.mem]p19:
11928       //   If T is the name of a class, then [every named member other than
11929       //   a non-static data member] shall have a name different from T
11930       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11931           !isa<IndirectFieldDecl>(Target) &&
11932           !isa<UnresolvedUsingValueDecl>(Target) &&
11933           DiagnoseClassNameShadow(
11934               CurContext,
11935               DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
11936         return true;
11937     }
11938 
11939     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11940       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11941         PrevShadow = Shadow;
11942       FoundEquivalentDecl = true;
11943     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11944       // We don't conflict with an existing using shadow decl of an equivalent
11945       // declaration, but we're not a redeclaration of it.
11946       FoundEquivalentDecl = true;
11947     }
11948 
11949     if (isVisible(D))
11950       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11951   }
11952 
11953   if (FoundEquivalentDecl)
11954     return false;
11955 
11956   // Always emit a diagnostic for a mismatch between an unresolved
11957   // using_if_exists and a resolved using declaration in either direction.
11958   if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
11959       (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
11960     if (!NonTag && !Tag)
11961       return false;
11962     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11963     Diag(Target->getLocation(), diag::note_using_decl_target);
11964     Diag((NonTag ? NonTag : Tag)->getLocation(),
11965          diag::note_using_decl_conflict);
11966     BUD->setInvalidDecl();
11967     return true;
11968   }
11969 
11970   if (FunctionDecl *FD = Target->getAsFunction()) {
11971     NamedDecl *OldDecl = nullptr;
11972     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11973                           /*IsForUsingDecl*/ true)) {
11974     case Ovl_Overload:
11975       return false;
11976 
11977     case Ovl_NonFunction:
11978       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11979       break;
11980 
11981     // We found a decl with the exact signature.
11982     case Ovl_Match:
11983       // If we're in a record, we want to hide the target, so we
11984       // return true (without a diagnostic) to tell the caller not to
11985       // build a shadow decl.
11986       if (CurContext->isRecord())
11987         return true;
11988 
11989       // If we're not in a record, this is an error.
11990       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11991       break;
11992     }
11993 
11994     Diag(Target->getLocation(), diag::note_using_decl_target);
11995     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11996     BUD->setInvalidDecl();
11997     return true;
11998   }
11999 
12000   // Target is not a function.
12001 
12002   if (isa<TagDecl>(Target)) {
12003     // No conflict between a tag and a non-tag.
12004     if (!Tag) return false;
12005 
12006     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12007     Diag(Target->getLocation(), diag::note_using_decl_target);
12008     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12009     BUD->setInvalidDecl();
12010     return true;
12011   }
12012 
12013   // No conflict between a tag and a non-tag.
12014   if (!NonTag) return false;
12015 
12016   Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12017   Diag(Target->getLocation(), diag::note_using_decl_target);
12018   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12019   BUD->setInvalidDecl();
12020   return true;
12021 }
12022 
12023 /// Determine whether a direct base class is a virtual base class.
12024 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12025   if (!Derived->getNumVBases())
12026     return false;
12027   for (auto &B : Derived->bases())
12028     if (B.getType()->getAsCXXRecordDecl() == Base)
12029       return B.isVirtual();
12030   llvm_unreachable("not a direct base class");
12031 }
12032 
12033 /// Builds a shadow declaration corresponding to a 'using' declaration.
12034 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12035                                             NamedDecl *Orig,
12036                                             UsingShadowDecl *PrevDecl) {
12037   // If we resolved to another shadow declaration, just coalesce them.
12038   NamedDecl *Target = Orig;
12039   if (isa<UsingShadowDecl>(Target)) {
12040     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12041     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12042   }
12043 
12044   NamedDecl *NonTemplateTarget = Target;
12045   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12046     NonTemplateTarget = TargetTD->getTemplatedDecl();
12047 
12048   UsingShadowDecl *Shadow;
12049   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12050     UsingDecl *Using = cast<UsingDecl>(BUD);
12051     bool IsVirtualBase =
12052         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12053                             Using->getQualifier()->getAsRecordDecl());
12054     Shadow = ConstructorUsingShadowDecl::Create(
12055         Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12056   } else {
12057     Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12058                                      Target->getDeclName(), BUD, Target);
12059   }
12060   BUD->addShadowDecl(Shadow);
12061 
12062   Shadow->setAccess(BUD->getAccess());
12063   if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12064     Shadow->setInvalidDecl();
12065 
12066   Shadow->setPreviousDecl(PrevDecl);
12067 
12068   if (S)
12069     PushOnScopeChains(Shadow, S);
12070   else
12071     CurContext->addDecl(Shadow);
12072 
12073 
12074   return Shadow;
12075 }
12076 
12077 /// Hides a using shadow declaration.  This is required by the current
12078 /// using-decl implementation when a resolvable using declaration in a
12079 /// class is followed by a declaration which would hide or override
12080 /// one or more of the using decl's targets; for example:
12081 ///
12082 ///   struct Base { void foo(int); };
12083 ///   struct Derived : Base {
12084 ///     using Base::foo;
12085 ///     void foo(int);
12086 ///   };
12087 ///
12088 /// The governing language is C++03 [namespace.udecl]p12:
12089 ///
12090 ///   When a using-declaration brings names from a base class into a
12091 ///   derived class scope, member functions in the derived class
12092 ///   override and/or hide member functions with the same name and
12093 ///   parameter types in a base class (rather than conflicting).
12094 ///
12095 /// There are two ways to implement this:
12096 ///   (1) optimistically create shadow decls when they're not hidden
12097 ///       by existing declarations, or
12098 ///   (2) don't create any shadow decls (or at least don't make them
12099 ///       visible) until we've fully parsed/instantiated the class.
12100 /// The problem with (1) is that we might have to retroactively remove
12101 /// a shadow decl, which requires several O(n) operations because the
12102 /// decl structures are (very reasonably) not designed for removal.
12103 /// (2) avoids this but is very fiddly and phase-dependent.
12104 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12105   if (Shadow->getDeclName().getNameKind() ==
12106         DeclarationName::CXXConversionFunctionName)
12107     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12108 
12109   // Remove it from the DeclContext...
12110   Shadow->getDeclContext()->removeDecl(Shadow);
12111 
12112   // ...and the scope, if applicable...
12113   if (S) {
12114     S->RemoveDecl(Shadow);
12115     IdResolver.RemoveDecl(Shadow);
12116   }
12117 
12118   // ...and the using decl.
12119   Shadow->getIntroducer()->removeShadowDecl(Shadow);
12120 
12121   // TODO: complain somehow if Shadow was used.  It shouldn't
12122   // be possible for this to happen, because...?
12123 }
12124 
12125 /// Find the base specifier for a base class with the given type.
12126 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12127                                                 QualType DesiredBase,
12128                                                 bool &AnyDependentBases) {
12129   // Check whether the named type is a direct base class.
12130   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12131     .getUnqualifiedType();
12132   for (auto &Base : Derived->bases()) {
12133     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12134     if (CanonicalDesiredBase == BaseType)
12135       return &Base;
12136     if (BaseType->isDependentType())
12137       AnyDependentBases = true;
12138   }
12139   return nullptr;
12140 }
12141 
12142 namespace {
12143 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12144 public:
12145   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12146                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12147       : HasTypenameKeyword(HasTypenameKeyword),
12148         IsInstantiation(IsInstantiation), OldNNS(NNS),
12149         RequireMemberOf(RequireMemberOf) {}
12150 
12151   bool ValidateCandidate(const TypoCorrection &Candidate) override {
12152     NamedDecl *ND = Candidate.getCorrectionDecl();
12153 
12154     // Keywords are not valid here.
12155     if (!ND || isa<NamespaceDecl>(ND))
12156       return false;
12157 
12158     // Completely unqualified names are invalid for a 'using' declaration.
12159     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12160       return false;
12161 
12162     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12163     // reject.
12164 
12165     if (RequireMemberOf) {
12166       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12167       if (FoundRecord && FoundRecord->isInjectedClassName()) {
12168         // No-one ever wants a using-declaration to name an injected-class-name
12169         // of a base class, unless they're declaring an inheriting constructor.
12170         ASTContext &Ctx = ND->getASTContext();
12171         if (!Ctx.getLangOpts().CPlusPlus11)
12172           return false;
12173         QualType FoundType = Ctx.getRecordType(FoundRecord);
12174 
12175         // Check that the injected-class-name is named as a member of its own
12176         // type; we don't want to suggest 'using Derived::Base;', since that
12177         // means something else.
12178         NestedNameSpecifier *Specifier =
12179             Candidate.WillReplaceSpecifier()
12180                 ? Candidate.getCorrectionSpecifier()
12181                 : OldNNS;
12182         if (!Specifier->getAsType() ||
12183             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12184           return false;
12185 
12186         // Check that this inheriting constructor declaration actually names a
12187         // direct base class of the current class.
12188         bool AnyDependentBases = false;
12189         if (!findDirectBaseWithType(RequireMemberOf,
12190                                     Ctx.getRecordType(FoundRecord),
12191                                     AnyDependentBases) &&
12192             !AnyDependentBases)
12193           return false;
12194       } else {
12195         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12196         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12197           return false;
12198 
12199         // FIXME: Check that the base class member is accessible?
12200       }
12201     } else {
12202       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12203       if (FoundRecord && FoundRecord->isInjectedClassName())
12204         return false;
12205     }
12206 
12207     if (isa<TypeDecl>(ND))
12208       return HasTypenameKeyword || !IsInstantiation;
12209 
12210     return !HasTypenameKeyword;
12211   }
12212 
12213   std::unique_ptr<CorrectionCandidateCallback> clone() override {
12214     return std::make_unique<UsingValidatorCCC>(*this);
12215   }
12216 
12217 private:
12218   bool HasTypenameKeyword;
12219   bool IsInstantiation;
12220   NestedNameSpecifier *OldNNS;
12221   CXXRecordDecl *RequireMemberOf;
12222 };
12223 } // end anonymous namespace
12224 
12225 /// Remove decls we can't actually see from a lookup being used to declare
12226 /// shadow using decls.
12227 ///
12228 /// \param S - The scope of the potential shadow decl
12229 /// \param Previous - The lookup of a potential shadow decl's name.
12230 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12231   // It is really dumb that we have to do this.
12232   LookupResult::Filter F = Previous.makeFilter();
12233   while (F.hasNext()) {
12234     NamedDecl *D = F.next();
12235     if (!isDeclInScope(D, CurContext, S))
12236       F.erase();
12237     // If we found a local extern declaration that's not ordinarily visible,
12238     // and this declaration is being added to a non-block scope, ignore it.
12239     // We're only checking for scope conflicts here, not also for violations
12240     // of the linkage rules.
12241     else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12242              !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12243       F.erase();
12244   }
12245   F.done();
12246 }
12247 
12248 /// Builds a using declaration.
12249 ///
12250 /// \param IsInstantiation - Whether this call arises from an
12251 ///   instantiation of an unresolved using declaration.  We treat
12252 ///   the lookup differently for these declarations.
12253 NamedDecl *Sema::BuildUsingDeclaration(
12254     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12255     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12256     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12257     const ParsedAttributesView &AttrList, bool IsInstantiation,
12258     bool IsUsingIfExists) {
12259   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12260   SourceLocation IdentLoc = NameInfo.getLoc();
12261   assert(IdentLoc.isValid() && "Invalid TargetName location.");
12262 
12263   // FIXME: We ignore attributes for now.
12264 
12265   // For an inheriting constructor declaration, the name of the using
12266   // declaration is the name of a constructor in this class, not in the
12267   // base class.
12268   DeclarationNameInfo UsingName = NameInfo;
12269   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12270     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12271       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12272           Context.getCanonicalType(Context.getRecordType(RD))));
12273 
12274   // Do the redeclaration lookup in the current scope.
12275   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12276                         ForVisibleRedeclaration);
12277   Previous.setHideTags(false);
12278   if (S) {
12279     LookupName(Previous, S);
12280 
12281     FilterUsingLookup(S, Previous);
12282   } else {
12283     assert(IsInstantiation && "no scope in non-instantiation");
12284     if (CurContext->isRecord())
12285       LookupQualifiedName(Previous, CurContext);
12286     else {
12287       // No redeclaration check is needed here; in non-member contexts we
12288       // diagnosed all possible conflicts with other using-declarations when
12289       // building the template:
12290       //
12291       // For a dependent non-type using declaration, the only valid case is
12292       // if we instantiate to a single enumerator. We check for conflicts
12293       // between shadow declarations we introduce, and we check in the template
12294       // definition for conflicts between a non-type using declaration and any
12295       // other declaration, which together covers all cases.
12296       //
12297       // A dependent typename using declaration will never successfully
12298       // instantiate, since it will always name a class member, so we reject
12299       // that in the template definition.
12300     }
12301   }
12302 
12303   // Check for invalid redeclarations.
12304   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12305                                   SS, IdentLoc, Previous))
12306     return nullptr;
12307 
12308   // 'using_if_exists' doesn't make sense on an inherited constructor.
12309   if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12310                              DeclarationName::CXXConstructorName) {
12311     Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12312     return nullptr;
12313   }
12314 
12315   DeclContext *LookupContext = computeDeclContext(SS);
12316   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12317   if (!LookupContext || EllipsisLoc.isValid()) {
12318     NamedDecl *D;
12319     // Dependent scope, or an unexpanded pack
12320     if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12321                                                   SS, NameInfo, IdentLoc))
12322       return nullptr;
12323 
12324     if (HasTypenameKeyword) {
12325       // FIXME: not all declaration name kinds are legal here
12326       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12327                                               UsingLoc, TypenameLoc,
12328                                               QualifierLoc,
12329                                               IdentLoc, NameInfo.getName(),
12330                                               EllipsisLoc);
12331     } else {
12332       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12333                                            QualifierLoc, NameInfo, EllipsisLoc);
12334     }
12335     D->setAccess(AS);
12336     CurContext->addDecl(D);
12337     ProcessDeclAttributeList(S, D, AttrList);
12338     return D;
12339   }
12340 
12341   auto Build = [&](bool Invalid) {
12342     UsingDecl *UD =
12343         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12344                           UsingName, HasTypenameKeyword);
12345     UD->setAccess(AS);
12346     CurContext->addDecl(UD);
12347     ProcessDeclAttributeList(S, UD, AttrList);
12348     UD->setInvalidDecl(Invalid);
12349     return UD;
12350   };
12351   auto BuildInvalid = [&]{ return Build(true); };
12352   auto BuildValid = [&]{ return Build(false); };
12353 
12354   if (RequireCompleteDeclContext(SS, LookupContext))
12355     return BuildInvalid();
12356 
12357   // Look up the target name.
12358   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12359 
12360   // Unlike most lookups, we don't always want to hide tag
12361   // declarations: tag names are visible through the using declaration
12362   // even if hidden by ordinary names, *except* in a dependent context
12363   // where they may be used by two-phase lookup.
12364   if (!IsInstantiation)
12365     R.setHideTags(false);
12366 
12367   // For the purposes of this lookup, we have a base object type
12368   // equal to that of the current context.
12369   if (CurContext->isRecord()) {
12370     R.setBaseObjectType(
12371                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12372   }
12373 
12374   LookupQualifiedName(R, LookupContext);
12375 
12376   // Validate the context, now we have a lookup
12377   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12378                               IdentLoc, &R))
12379     return nullptr;
12380 
12381   if (R.empty() && IsUsingIfExists)
12382     R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12383                                                   UsingName.getName()),
12384               AS_public);
12385 
12386   // Try to correct typos if possible. If constructor name lookup finds no
12387   // results, that means the named class has no explicit constructors, and we
12388   // suppressed declaring implicit ones (probably because it's dependent or
12389   // invalid).
12390   if (R.empty() &&
12391       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12392     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12393     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12394     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12395     auto *II = NameInfo.getName().getAsIdentifierInfo();
12396     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12397         CurContext->isStdNamespace() &&
12398         isa<TranslationUnitDecl>(LookupContext) &&
12399         getSourceManager().isInSystemHeader(UsingLoc))
12400       return nullptr;
12401     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12402                           dyn_cast<CXXRecordDecl>(CurContext));
12403     if (TypoCorrection Corrected =
12404             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12405                         CTK_ErrorRecovery)) {
12406       // We reject candidates where DroppedSpecifier == true, hence the
12407       // literal '0' below.
12408       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12409                                 << NameInfo.getName() << LookupContext << 0
12410                                 << SS.getRange());
12411 
12412       // If we picked a correction with no attached Decl we can't do anything
12413       // useful with it, bail out.
12414       NamedDecl *ND = Corrected.getCorrectionDecl();
12415       if (!ND)
12416         return BuildInvalid();
12417 
12418       // If we corrected to an inheriting constructor, handle it as one.
12419       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12420       if (RD && RD->isInjectedClassName()) {
12421         // The parent of the injected class name is the class itself.
12422         RD = cast<CXXRecordDecl>(RD->getParent());
12423 
12424         // Fix up the information we'll use to build the using declaration.
12425         if (Corrected.WillReplaceSpecifier()) {
12426           NestedNameSpecifierLocBuilder Builder;
12427           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12428                               QualifierLoc.getSourceRange());
12429           QualifierLoc = Builder.getWithLocInContext(Context);
12430         }
12431 
12432         // In this case, the name we introduce is the name of a derived class
12433         // constructor.
12434         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12435         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12436             Context.getCanonicalType(Context.getRecordType(CurClass))));
12437         UsingName.setNamedTypeInfo(nullptr);
12438         for (auto *Ctor : LookupConstructors(RD))
12439           R.addDecl(Ctor);
12440         R.resolveKind();
12441       } else {
12442         // FIXME: Pick up all the declarations if we found an overloaded
12443         // function.
12444         UsingName.setName(ND->getDeclName());
12445         R.addDecl(ND);
12446       }
12447     } else {
12448       Diag(IdentLoc, diag::err_no_member)
12449         << NameInfo.getName() << LookupContext << SS.getRange();
12450       return BuildInvalid();
12451     }
12452   }
12453 
12454   if (R.isAmbiguous())
12455     return BuildInvalid();
12456 
12457   if (HasTypenameKeyword) {
12458     // If we asked for a typename and got a non-type decl, error out.
12459     if (!R.getAsSingle<TypeDecl>() &&
12460         !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12461       Diag(IdentLoc, diag::err_using_typename_non_type);
12462       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12463         Diag((*I)->getUnderlyingDecl()->getLocation(),
12464              diag::note_using_decl_target);
12465       return BuildInvalid();
12466     }
12467   } else {
12468     // If we asked for a non-typename and we got a type, error out,
12469     // but only if this is an instantiation of an unresolved using
12470     // decl.  Otherwise just silently find the type name.
12471     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12472       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12473       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12474       return BuildInvalid();
12475     }
12476   }
12477 
12478   // C++14 [namespace.udecl]p6:
12479   // A using-declaration shall not name a namespace.
12480   if (R.getAsSingle<NamespaceDecl>()) {
12481     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12482       << SS.getRange();
12483     return BuildInvalid();
12484   }
12485 
12486   UsingDecl *UD = BuildValid();
12487 
12488   // Some additional rules apply to inheriting constructors.
12489   if (UsingName.getName().getNameKind() ==
12490         DeclarationName::CXXConstructorName) {
12491     // Suppress access diagnostics; the access check is instead performed at the
12492     // point of use for an inheriting constructor.
12493     R.suppressDiagnostics();
12494     if (CheckInheritingConstructorUsingDecl(UD))
12495       return UD;
12496   }
12497 
12498   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12499     UsingShadowDecl *PrevDecl = nullptr;
12500     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12501       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12502   }
12503 
12504   return UD;
12505 }
12506 
12507 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12508                                            SourceLocation UsingLoc,
12509                                            SourceLocation EnumLoc,
12510                                            SourceLocation NameLoc,
12511                                            EnumDecl *ED) {
12512   bool Invalid = false;
12513 
12514   if (CurContext->getRedeclContext()->isRecord()) {
12515     /// In class scope, check if this is a duplicate, for better a diagnostic.
12516     DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12517     LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12518                           ForVisibleRedeclaration);
12519 
12520     LookupName(Previous, S);
12521 
12522     for (NamedDecl *D : Previous)
12523       if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12524         if (UED->getEnumDecl() == ED) {
12525           Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12526               << SourceRange(EnumLoc, NameLoc);
12527           Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12528           Invalid = true;
12529           break;
12530         }
12531   }
12532 
12533   if (RequireCompleteEnumDecl(ED, NameLoc))
12534     Invalid = true;
12535 
12536   UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12537                                             EnumLoc, NameLoc, ED);
12538   UD->setAccess(AS);
12539   CurContext->addDecl(UD);
12540 
12541   if (Invalid) {
12542     UD->setInvalidDecl();
12543     return UD;
12544   }
12545 
12546   // Create the shadow decls for each enumerator
12547   for (EnumConstantDecl *EC : ED->enumerators()) {
12548     UsingShadowDecl *PrevDecl = nullptr;
12549     DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12550     LookupResult Previous(*this, DNI, LookupOrdinaryName,
12551                           ForVisibleRedeclaration);
12552     LookupName(Previous, S);
12553     FilterUsingLookup(S, Previous);
12554 
12555     if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12556       BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12557   }
12558 
12559   return UD;
12560 }
12561 
12562 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12563                                     ArrayRef<NamedDecl *> Expansions) {
12564   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12565          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12566          isa<UsingPackDecl>(InstantiatedFrom));
12567 
12568   auto *UPD =
12569       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12570   UPD->setAccess(InstantiatedFrom->getAccess());
12571   CurContext->addDecl(UPD);
12572   return UPD;
12573 }
12574 
12575 /// Additional checks for a using declaration referring to a constructor name.
12576 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12577   assert(!UD->hasTypename() && "expecting a constructor name");
12578 
12579   const Type *SourceType = UD->getQualifier()->getAsType();
12580   assert(SourceType &&
12581          "Using decl naming constructor doesn't have type in scope spec.");
12582   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12583 
12584   // Check whether the named type is a direct base class.
12585   bool AnyDependentBases = false;
12586   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12587                                       AnyDependentBases);
12588   if (!Base && !AnyDependentBases) {
12589     Diag(UD->getUsingLoc(),
12590          diag::err_using_decl_constructor_not_in_direct_base)
12591       << UD->getNameInfo().getSourceRange()
12592       << QualType(SourceType, 0) << TargetClass;
12593     UD->setInvalidDecl();
12594     return true;
12595   }
12596 
12597   if (Base)
12598     Base->setInheritConstructors();
12599 
12600   return false;
12601 }
12602 
12603 /// Checks that the given using declaration is not an invalid
12604 /// redeclaration.  Note that this is checking only for the using decl
12605 /// itself, not for any ill-formedness among the UsingShadowDecls.
12606 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12607                                        bool HasTypenameKeyword,
12608                                        const CXXScopeSpec &SS,
12609                                        SourceLocation NameLoc,
12610                                        const LookupResult &Prev) {
12611   NestedNameSpecifier *Qual = SS.getScopeRep();
12612 
12613   // C++03 [namespace.udecl]p8:
12614   // C++0x [namespace.udecl]p10:
12615   //   A using-declaration is a declaration and can therefore be used
12616   //   repeatedly where (and only where) multiple declarations are
12617   //   allowed.
12618   //
12619   // That's in non-member contexts.
12620   if (!CurContext->getRedeclContext()->isRecord()) {
12621     // A dependent qualifier outside a class can only ever resolve to an
12622     // enumeration type. Therefore it conflicts with any other non-type
12623     // declaration in the same scope.
12624     // FIXME: How should we check for dependent type-type conflicts at block
12625     // scope?
12626     if (Qual->isDependent() && !HasTypenameKeyword) {
12627       for (auto *D : Prev) {
12628         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12629           bool OldCouldBeEnumerator =
12630               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12631           Diag(NameLoc,
12632                OldCouldBeEnumerator ? diag::err_redefinition
12633                                     : diag::err_redefinition_different_kind)
12634               << Prev.getLookupName();
12635           Diag(D->getLocation(), diag::note_previous_definition);
12636           return true;
12637         }
12638       }
12639     }
12640     return false;
12641   }
12642 
12643   const NestedNameSpecifier *CNNS =
12644       Context.getCanonicalNestedNameSpecifier(Qual);
12645   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12646     NamedDecl *D = *I;
12647 
12648     bool DTypename;
12649     NestedNameSpecifier *DQual;
12650     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12651       DTypename = UD->hasTypename();
12652       DQual = UD->getQualifier();
12653     } else if (UnresolvedUsingValueDecl *UD
12654                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12655       DTypename = false;
12656       DQual = UD->getQualifier();
12657     } else if (UnresolvedUsingTypenameDecl *UD
12658                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12659       DTypename = true;
12660       DQual = UD->getQualifier();
12661     } else continue;
12662 
12663     // using decls differ if one says 'typename' and the other doesn't.
12664     // FIXME: non-dependent using decls?
12665     if (HasTypenameKeyword != DTypename) continue;
12666 
12667     // using decls differ if they name different scopes (but note that
12668     // template instantiation can cause this check to trigger when it
12669     // didn't before instantiation).
12670     if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12671       continue;
12672 
12673     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12674     Diag(D->getLocation(), diag::note_using_decl) << 1;
12675     return true;
12676   }
12677 
12678   return false;
12679 }
12680 
12681 /// Checks that the given nested-name qualifier used in a using decl
12682 /// in the current context is appropriately related to the current
12683 /// scope.  If an error is found, diagnoses it and returns true.
12684 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12685 /// result of that lookup. UD is likewise nullptr, except when we have an
12686 /// already-populated UsingDecl whose shadow decls contain the same information
12687 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12688 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12689                                    const CXXScopeSpec &SS,
12690                                    const DeclarationNameInfo &NameInfo,
12691                                    SourceLocation NameLoc,
12692                                    const LookupResult *R, const UsingDecl *UD) {
12693   DeclContext *NamedContext = computeDeclContext(SS);
12694   assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
12695          "resolvable context must have exactly one set of decls");
12696 
12697   // C++ 20 permits using an enumerator that does not have a class-hierarchy
12698   // relationship.
12699   bool Cxx20Enumerator = false;
12700   if (NamedContext) {
12701     EnumConstantDecl *EC = nullptr;
12702     if (R)
12703       EC = R->getAsSingle<EnumConstantDecl>();
12704     else if (UD && UD->shadow_size() == 1)
12705       EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12706     if (EC)
12707       Cxx20Enumerator = getLangOpts().CPlusPlus20;
12708 
12709     if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12710       // C++14 [namespace.udecl]p7:
12711       // A using-declaration shall not name a scoped enumerator.
12712       // C++20 p1099 permits enumerators.
12713       if (EC && R && ED->isScoped())
12714         Diag(SS.getBeginLoc(),
12715              getLangOpts().CPlusPlus20
12716                  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12717                  : diag::ext_using_decl_scoped_enumerator)
12718             << SS.getRange();
12719 
12720       // We want to consider the scope of the enumerator
12721       NamedContext = ED->getDeclContext();
12722     }
12723   }
12724 
12725   if (!CurContext->isRecord()) {
12726     // C++03 [namespace.udecl]p3:
12727     // C++0x [namespace.udecl]p8:
12728     //   A using-declaration for a class member shall be a member-declaration.
12729     // C++20 [namespace.udecl]p7
12730     //   ... other than an enumerator ...
12731 
12732     // If we weren't able to compute a valid scope, it might validly be a
12733     // dependent class or enumeration scope. If we have a 'typename' keyword,
12734     // the scope must resolve to a class type.
12735     if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12736                      : !HasTypename)
12737       return false; // OK
12738 
12739     Diag(NameLoc,
12740          Cxx20Enumerator
12741              ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12742              : diag::err_using_decl_can_not_refer_to_class_member)
12743         << SS.getRange();
12744 
12745     if (Cxx20Enumerator)
12746       return false; // OK
12747 
12748     auto *RD = NamedContext
12749                    ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12750                    : nullptr;
12751     if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12752       // See if there's a helpful fixit
12753 
12754       if (!R) {
12755         // We will have already diagnosed the problem on the template
12756         // definition,  Maybe we should do so again?
12757       } else if (R->getAsSingle<TypeDecl>()) {
12758         if (getLangOpts().CPlusPlus11) {
12759           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12760           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12761             << 0 // alias declaration
12762             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12763                                           NameInfo.getName().getAsString() +
12764                                               " = ");
12765         } else {
12766           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12767           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12768           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12769             << 1 // typedef declaration
12770             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12771             << FixItHint::CreateInsertion(
12772                    InsertLoc, " " + NameInfo.getName().getAsString());
12773         }
12774       } else if (R->getAsSingle<VarDecl>()) {
12775         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12776         // repeating the type of the static data member here.
12777         FixItHint FixIt;
12778         if (getLangOpts().CPlusPlus11) {
12779           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12780           FixIt = FixItHint::CreateReplacement(
12781               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12782         }
12783 
12784         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12785           << 2 // reference declaration
12786           << FixIt;
12787       } else if (R->getAsSingle<EnumConstantDecl>()) {
12788         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12789         // repeating the type of the enumeration here, and we can't do so if
12790         // the type is anonymous.
12791         FixItHint FixIt;
12792         if (getLangOpts().CPlusPlus11) {
12793           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12794           FixIt = FixItHint::CreateReplacement(
12795               UsingLoc,
12796               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12797         }
12798 
12799         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12800           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12801           << FixIt;
12802       }
12803     }
12804 
12805     return true; // Fail
12806   }
12807 
12808   // If the named context is dependent, we can't decide much.
12809   if (!NamedContext) {
12810     // FIXME: in C++0x, we can diagnose if we can prove that the
12811     // nested-name-specifier does not refer to a base class, which is
12812     // still possible in some cases.
12813 
12814     // Otherwise we have to conservatively report that things might be
12815     // okay.
12816     return false;
12817   }
12818 
12819   // The current scope is a record.
12820   if (!NamedContext->isRecord()) {
12821     // Ideally this would point at the last name in the specifier,
12822     // but we don't have that level of source info.
12823     Diag(SS.getBeginLoc(),
12824          Cxx20Enumerator
12825              ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12826              : diag::err_using_decl_nested_name_specifier_is_not_class)
12827         << SS.getScopeRep() << SS.getRange();
12828 
12829     if (Cxx20Enumerator)
12830       return false; // OK
12831 
12832     return true;
12833   }
12834 
12835   if (!NamedContext->isDependentContext() &&
12836       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12837     return true;
12838 
12839   if (getLangOpts().CPlusPlus11) {
12840     // C++11 [namespace.udecl]p3:
12841     //   In a using-declaration used as a member-declaration, the
12842     //   nested-name-specifier shall name a base class of the class
12843     //   being defined.
12844 
12845     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12846                                  cast<CXXRecordDecl>(NamedContext))) {
12847 
12848       if (Cxx20Enumerator) {
12849         Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12850             << SS.getRange();
12851         return false;
12852       }
12853 
12854       if (CurContext == NamedContext) {
12855         Diag(SS.getBeginLoc(),
12856              diag::err_using_decl_nested_name_specifier_is_current_class)
12857             << SS.getRange();
12858         return !getLangOpts().CPlusPlus20;
12859       }
12860 
12861       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12862         Diag(SS.getBeginLoc(),
12863              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12864             << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12865             << SS.getRange();
12866       }
12867       return true;
12868     }
12869 
12870     return false;
12871   }
12872 
12873   // C++03 [namespace.udecl]p4:
12874   //   A using-declaration used as a member-declaration shall refer
12875   //   to a member of a base class of the class being defined [etc.].
12876 
12877   // Salient point: SS doesn't have to name a base class as long as
12878   // lookup only finds members from base classes.  Therefore we can
12879   // diagnose here only if we can prove that that can't happen,
12880   // i.e. if the class hierarchies provably don't intersect.
12881 
12882   // TODO: it would be nice if "definitely valid" results were cached
12883   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12884   // need to be repeated.
12885 
12886   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12887   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12888     Bases.insert(Base);
12889     return true;
12890   };
12891 
12892   // Collect all bases. Return false if we find a dependent base.
12893   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12894     return false;
12895 
12896   // Returns true if the base is dependent or is one of the accumulated base
12897   // classes.
12898   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12899     return !Bases.count(Base);
12900   };
12901 
12902   // Return false if the class has a dependent base or if it or one
12903   // of its bases is present in the base set of the current context.
12904   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12905       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12906     return false;
12907 
12908   Diag(SS.getRange().getBegin(),
12909        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12910     << SS.getScopeRep()
12911     << cast<CXXRecordDecl>(CurContext)
12912     << SS.getRange();
12913 
12914   return true;
12915 }
12916 
12917 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12918                                   MultiTemplateParamsArg TemplateParamLists,
12919                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12920                                   const ParsedAttributesView &AttrList,
12921                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12922   // Skip up to the relevant declaration scope.
12923   while (S->isTemplateParamScope())
12924     S = S->getParent();
12925   assert((S->getFlags() & Scope::DeclScope) &&
12926          "got alias-declaration outside of declaration scope");
12927 
12928   if (Type.isInvalid())
12929     return nullptr;
12930 
12931   bool Invalid = false;
12932   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12933   TypeSourceInfo *TInfo = nullptr;
12934   GetTypeFromParser(Type.get(), &TInfo);
12935 
12936   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12937     return nullptr;
12938 
12939   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12940                                       UPPC_DeclarationType)) {
12941     Invalid = true;
12942     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12943                                              TInfo->getTypeLoc().getBeginLoc());
12944   }
12945 
12946   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12947                         TemplateParamLists.size()
12948                             ? forRedeclarationInCurContext()
12949                             : ForVisibleRedeclaration);
12950   LookupName(Previous, S);
12951 
12952   // Warn about shadowing the name of a template parameter.
12953   if (Previous.isSingleResult() &&
12954       Previous.getFoundDecl()->isTemplateParameter()) {
12955     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12956     Previous.clear();
12957   }
12958 
12959   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12960          "name in alias declaration must be an identifier");
12961   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12962                                                Name.StartLocation,
12963                                                Name.Identifier, TInfo);
12964 
12965   NewTD->setAccess(AS);
12966 
12967   if (Invalid)
12968     NewTD->setInvalidDecl();
12969 
12970   ProcessDeclAttributeList(S, NewTD, AttrList);
12971   AddPragmaAttributes(S, NewTD);
12972 
12973   CheckTypedefForVariablyModifiedType(S, NewTD);
12974   Invalid |= NewTD->isInvalidDecl();
12975 
12976   bool Redeclaration = false;
12977 
12978   NamedDecl *NewND;
12979   if (TemplateParamLists.size()) {
12980     TypeAliasTemplateDecl *OldDecl = nullptr;
12981     TemplateParameterList *OldTemplateParams = nullptr;
12982 
12983     if (TemplateParamLists.size() != 1) {
12984       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12985         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12986          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12987     }
12988     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12989 
12990     // Check that we can declare a template here.
12991     if (CheckTemplateDeclScope(S, TemplateParams))
12992       return nullptr;
12993 
12994     // Only consider previous declarations in the same scope.
12995     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12996                          /*ExplicitInstantiationOrSpecialization*/false);
12997     if (!Previous.empty()) {
12998       Redeclaration = true;
12999 
13000       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13001       if (!OldDecl && !Invalid) {
13002         Diag(UsingLoc, diag::err_redefinition_different_kind)
13003           << Name.Identifier;
13004 
13005         NamedDecl *OldD = Previous.getRepresentativeDecl();
13006         if (OldD->getLocation().isValid())
13007           Diag(OldD->getLocation(), diag::note_previous_definition);
13008 
13009         Invalid = true;
13010       }
13011 
13012       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13013         if (TemplateParameterListsAreEqual(TemplateParams,
13014                                            OldDecl->getTemplateParameters(),
13015                                            /*Complain=*/true,
13016                                            TPL_TemplateMatch))
13017           OldTemplateParams =
13018               OldDecl->getMostRecentDecl()->getTemplateParameters();
13019         else
13020           Invalid = true;
13021 
13022         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13023         if (!Invalid &&
13024             !Context.hasSameType(OldTD->getUnderlyingType(),
13025                                  NewTD->getUnderlyingType())) {
13026           // FIXME: The C++0x standard does not clearly say this is ill-formed,
13027           // but we can't reasonably accept it.
13028           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13029             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13030           if (OldTD->getLocation().isValid())
13031             Diag(OldTD->getLocation(), diag::note_previous_definition);
13032           Invalid = true;
13033         }
13034       }
13035     }
13036 
13037     // Merge any previous default template arguments into our parameters,
13038     // and check the parameter list.
13039     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13040                                    TPC_TypeAliasTemplate))
13041       return nullptr;
13042 
13043     TypeAliasTemplateDecl *NewDecl =
13044       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13045                                     Name.Identifier, TemplateParams,
13046                                     NewTD);
13047     NewTD->setDescribedAliasTemplate(NewDecl);
13048 
13049     NewDecl->setAccess(AS);
13050 
13051     if (Invalid)
13052       NewDecl->setInvalidDecl();
13053     else if (OldDecl) {
13054       NewDecl->setPreviousDecl(OldDecl);
13055       CheckRedeclarationInModule(NewDecl, OldDecl);
13056     }
13057 
13058     NewND = NewDecl;
13059   } else {
13060     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13061       setTagNameForLinkagePurposes(TD, NewTD);
13062       handleTagNumbering(TD, S);
13063     }
13064     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13065     NewND = NewTD;
13066   }
13067 
13068   PushOnScopeChains(NewND, S);
13069   ActOnDocumentableDecl(NewND);
13070   return NewND;
13071 }
13072 
13073 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13074                                    SourceLocation AliasLoc,
13075                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
13076                                    SourceLocation IdentLoc,
13077                                    IdentifierInfo *Ident) {
13078 
13079   // Lookup the namespace name.
13080   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13081   LookupParsedName(R, S, &SS);
13082 
13083   if (R.isAmbiguous())
13084     return nullptr;
13085 
13086   if (R.empty()) {
13087     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13088       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13089       return nullptr;
13090     }
13091   }
13092   assert(!R.isAmbiguous() && !R.empty());
13093   NamedDecl *ND = R.getRepresentativeDecl();
13094 
13095   // Check if we have a previous declaration with the same name.
13096   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13097                      ForVisibleRedeclaration);
13098   LookupName(PrevR, S);
13099 
13100   // Check we're not shadowing a template parameter.
13101   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13102     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13103     PrevR.clear();
13104   }
13105 
13106   // Filter out any other lookup result from an enclosing scope.
13107   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13108                        /*AllowInlineNamespace*/false);
13109 
13110   // Find the previous declaration and check that we can redeclare it.
13111   NamespaceAliasDecl *Prev = nullptr;
13112   if (PrevR.isSingleResult()) {
13113     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13114     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13115       // We already have an alias with the same name that points to the same
13116       // namespace; check that it matches.
13117       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13118         Prev = AD;
13119       } else if (isVisible(PrevDecl)) {
13120         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13121           << Alias;
13122         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13123           << AD->getNamespace();
13124         return nullptr;
13125       }
13126     } else if (isVisible(PrevDecl)) {
13127       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13128                             ? diag::err_redefinition
13129                             : diag::err_redefinition_different_kind;
13130       Diag(AliasLoc, DiagID) << Alias;
13131       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13132       return nullptr;
13133     }
13134   }
13135 
13136   // The use of a nested name specifier may trigger deprecation warnings.
13137   DiagnoseUseOfDecl(ND, IdentLoc);
13138 
13139   NamespaceAliasDecl *AliasDecl =
13140     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13141                                Alias, SS.getWithLocInContext(Context),
13142                                IdentLoc, ND);
13143   if (Prev)
13144     AliasDecl->setPreviousDecl(Prev);
13145 
13146   PushOnScopeChains(AliasDecl, S);
13147   return AliasDecl;
13148 }
13149 
13150 namespace {
13151 struct SpecialMemberExceptionSpecInfo
13152     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13153   SourceLocation Loc;
13154   Sema::ImplicitExceptionSpecification ExceptSpec;
13155 
13156   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13157                                  Sema::CXXSpecialMember CSM,
13158                                  Sema::InheritedConstructorInfo *ICI,
13159                                  SourceLocation Loc)
13160       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13161 
13162   bool visitBase(CXXBaseSpecifier *Base);
13163   bool visitField(FieldDecl *FD);
13164 
13165   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13166                            unsigned Quals);
13167 
13168   void visitSubobjectCall(Subobject Subobj,
13169                           Sema::SpecialMemberOverloadResult SMOR);
13170 };
13171 }
13172 
13173 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13174   auto *RT = Base->getType()->getAs<RecordType>();
13175   if (!RT)
13176     return false;
13177 
13178   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13179   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13180   if (auto *BaseCtor = SMOR.getMethod()) {
13181     visitSubobjectCall(Base, BaseCtor);
13182     return false;
13183   }
13184 
13185   visitClassSubobject(BaseClass, Base, 0);
13186   return false;
13187 }
13188 
13189 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13190   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13191     Expr *E = FD->getInClassInitializer();
13192     if (!E)
13193       // FIXME: It's a little wasteful to build and throw away a
13194       // CXXDefaultInitExpr here.
13195       // FIXME: We should have a single context note pointing at Loc, and
13196       // this location should be MD->getLocation() instead, since that's
13197       // the location where we actually use the default init expression.
13198       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13199     if (E)
13200       ExceptSpec.CalledExpr(E);
13201   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13202                             ->getAs<RecordType>()) {
13203     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13204                         FD->getType().getCVRQualifiers());
13205   }
13206   return false;
13207 }
13208 
13209 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13210                                                          Subobject Subobj,
13211                                                          unsigned Quals) {
13212   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13213   bool IsMutable = Field && Field->isMutable();
13214   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13215 }
13216 
13217 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13218     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13219   // Note, if lookup fails, it doesn't matter what exception specification we
13220   // choose because the special member will be deleted.
13221   if (CXXMethodDecl *MD = SMOR.getMethod())
13222     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13223 }
13224 
13225 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13226   llvm::APSInt Result;
13227   ExprResult Converted = CheckConvertedConstantExpression(
13228       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13229   ExplicitSpec.setExpr(Converted.get());
13230   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13231     ExplicitSpec.setKind(Result.getBoolValue()
13232                              ? ExplicitSpecKind::ResolvedTrue
13233                              : ExplicitSpecKind::ResolvedFalse);
13234     return true;
13235   }
13236   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13237   return false;
13238 }
13239 
13240 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13241   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13242   if (!ExplicitExpr->isTypeDependent())
13243     tryResolveExplicitSpecifier(ES);
13244   return ES;
13245 }
13246 
13247 static Sema::ImplicitExceptionSpecification
13248 ComputeDefaultedSpecialMemberExceptionSpec(
13249     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13250     Sema::InheritedConstructorInfo *ICI) {
13251   ComputingExceptionSpec CES(S, MD, Loc);
13252 
13253   CXXRecordDecl *ClassDecl = MD->getParent();
13254 
13255   // C++ [except.spec]p14:
13256   //   An implicitly declared special member function (Clause 12) shall have an
13257   //   exception-specification. [...]
13258   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13259   if (ClassDecl->isInvalidDecl())
13260     return Info.ExceptSpec;
13261 
13262   // FIXME: If this diagnostic fires, we're probably missing a check for
13263   // attempting to resolve an exception specification before it's known
13264   // at a higher level.
13265   if (S.RequireCompleteType(MD->getLocation(),
13266                             S.Context.getRecordType(ClassDecl),
13267                             diag::err_exception_spec_incomplete_type))
13268     return Info.ExceptSpec;
13269 
13270   // C++1z [except.spec]p7:
13271   //   [Look for exceptions thrown by] a constructor selected [...] to
13272   //   initialize a potentially constructed subobject,
13273   // C++1z [except.spec]p8:
13274   //   The exception specification for an implicitly-declared destructor, or a
13275   //   destructor without a noexcept-specifier, is potentially-throwing if and
13276   //   only if any of the destructors for any of its potentially constructed
13277   //   subojects is potentially throwing.
13278   // FIXME: We respect the first rule but ignore the "potentially constructed"
13279   // in the second rule to resolve a core issue (no number yet) that would have
13280   // us reject:
13281   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13282   //   struct B : A {};
13283   //   struct C : B { void f(); };
13284   // ... due to giving B::~B() a non-throwing exception specification.
13285   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13286                                 : Info.VisitAllBases);
13287 
13288   return Info.ExceptSpec;
13289 }
13290 
13291 namespace {
13292 /// RAII object to register a special member as being currently declared.
13293 struct DeclaringSpecialMember {
13294   Sema &S;
13295   Sema::SpecialMemberDecl D;
13296   Sema::ContextRAII SavedContext;
13297   bool WasAlreadyBeingDeclared;
13298 
13299   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13300       : S(S), D(RD, CSM), SavedContext(S, RD) {
13301     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13302     if (WasAlreadyBeingDeclared)
13303       // This almost never happens, but if it does, ensure that our cache
13304       // doesn't contain a stale result.
13305       S.SpecialMemberCache.clear();
13306     else {
13307       // Register a note to be produced if we encounter an error while
13308       // declaring the special member.
13309       Sema::CodeSynthesisContext Ctx;
13310       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13311       // FIXME: We don't have a location to use here. Using the class's
13312       // location maintains the fiction that we declare all special members
13313       // with the class, but (1) it's not clear that lying about that helps our
13314       // users understand what's going on, and (2) there may be outer contexts
13315       // on the stack (some of which are relevant) and printing them exposes
13316       // our lies.
13317       Ctx.PointOfInstantiation = RD->getLocation();
13318       Ctx.Entity = RD;
13319       Ctx.SpecialMember = CSM;
13320       S.pushCodeSynthesisContext(Ctx);
13321     }
13322   }
13323   ~DeclaringSpecialMember() {
13324     if (!WasAlreadyBeingDeclared) {
13325       S.SpecialMembersBeingDeclared.erase(D);
13326       S.popCodeSynthesisContext();
13327     }
13328   }
13329 
13330   /// Are we already trying to declare this special member?
13331   bool isAlreadyBeingDeclared() const {
13332     return WasAlreadyBeingDeclared;
13333   }
13334 };
13335 }
13336 
13337 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13338   // Look up any existing declarations, but don't trigger declaration of all
13339   // implicit special members with this name.
13340   DeclarationName Name = FD->getDeclName();
13341   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13342                  ForExternalRedeclaration);
13343   for (auto *D : FD->getParent()->lookup(Name))
13344     if (auto *Acceptable = R.getAcceptableDecl(D))
13345       R.addDecl(Acceptable);
13346   R.resolveKind();
13347   R.suppressDiagnostics();
13348 
13349   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
13350 }
13351 
13352 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13353                                           QualType ResultTy,
13354                                           ArrayRef<QualType> Args) {
13355   // Build an exception specification pointing back at this constructor.
13356   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13357 
13358   LangAS AS = getDefaultCXXMethodAddrSpace();
13359   if (AS != LangAS::Default) {
13360     EPI.TypeQuals.addAddressSpace(AS);
13361   }
13362 
13363   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13364   SpecialMem->setType(QT);
13365 
13366   // During template instantiation of implicit special member functions we need
13367   // a reliable TypeSourceInfo for the function prototype in order to allow
13368   // functions to be substituted.
13369   if (inTemplateInstantiation() &&
13370       cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13371     TypeSourceInfo *TSI =
13372         Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13373     SpecialMem->setTypeSourceInfo(TSI);
13374   }
13375 }
13376 
13377 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13378                                                      CXXRecordDecl *ClassDecl) {
13379   // C++ [class.ctor]p5:
13380   //   A default constructor for a class X is a constructor of class X
13381   //   that can be called without an argument. If there is no
13382   //   user-declared constructor for class X, a default constructor is
13383   //   implicitly declared. An implicitly-declared default constructor
13384   //   is an inline public member of its class.
13385   assert(ClassDecl->needsImplicitDefaultConstructor() &&
13386          "Should not build implicit default constructor!");
13387 
13388   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13389   if (DSM.isAlreadyBeingDeclared())
13390     return nullptr;
13391 
13392   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13393                                                      CXXDefaultConstructor,
13394                                                      false);
13395 
13396   // Create the actual constructor declaration.
13397   CanQualType ClassType
13398     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13399   SourceLocation ClassLoc = ClassDecl->getLocation();
13400   DeclarationName Name
13401     = Context.DeclarationNames.getCXXConstructorName(ClassType);
13402   DeclarationNameInfo NameInfo(Name, ClassLoc);
13403   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13404       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13405       /*TInfo=*/nullptr, ExplicitSpecifier(),
13406       getCurFPFeatures().isFPConstrained(),
13407       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13408       Constexpr ? ConstexprSpecKind::Constexpr
13409                 : ConstexprSpecKind::Unspecified);
13410   DefaultCon->setAccess(AS_public);
13411   DefaultCon->setDefaulted();
13412 
13413   if (getLangOpts().CUDA) {
13414     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13415                                             DefaultCon,
13416                                             /* ConstRHS */ false,
13417                                             /* Diagnose */ false);
13418   }
13419 
13420   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13421 
13422   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13423   // constructors is easy to compute.
13424   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13425 
13426   // Note that we have declared this constructor.
13427   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13428 
13429   Scope *S = getScopeForContext(ClassDecl);
13430   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13431 
13432   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13433     SetDeclDeleted(DefaultCon, ClassLoc);
13434 
13435   if (S)
13436     PushOnScopeChains(DefaultCon, S, false);
13437   ClassDecl->addDecl(DefaultCon);
13438 
13439   return DefaultCon;
13440 }
13441 
13442 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13443                                             CXXConstructorDecl *Constructor) {
13444   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13445           !Constructor->doesThisDeclarationHaveABody() &&
13446           !Constructor->isDeleted()) &&
13447     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13448   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13449     return;
13450 
13451   CXXRecordDecl *ClassDecl = Constructor->getParent();
13452   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13453 
13454   SynthesizedFunctionScope Scope(*this, Constructor);
13455 
13456   // The exception specification is needed because we are defining the
13457   // function.
13458   ResolveExceptionSpec(CurrentLocation,
13459                        Constructor->getType()->castAs<FunctionProtoType>());
13460   MarkVTableUsed(CurrentLocation, ClassDecl);
13461 
13462   // Add a context note for diagnostics produced after this point.
13463   Scope.addContextNote(CurrentLocation);
13464 
13465   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13466     Constructor->setInvalidDecl();
13467     return;
13468   }
13469 
13470   SourceLocation Loc = Constructor->getEndLoc().isValid()
13471                            ? Constructor->getEndLoc()
13472                            : Constructor->getLocation();
13473   Constructor->setBody(new (Context) CompoundStmt(Loc));
13474   Constructor->markUsed(Context);
13475 
13476   if (ASTMutationListener *L = getASTMutationListener()) {
13477     L->CompletedImplicitDefinition(Constructor);
13478   }
13479 
13480   DiagnoseUninitializedFields(*this, Constructor);
13481 }
13482 
13483 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13484   // Perform any delayed checks on exception specifications.
13485   CheckDelayedMemberExceptionSpecs();
13486 }
13487 
13488 /// Find or create the fake constructor we synthesize to model constructing an
13489 /// object of a derived class via a constructor of a base class.
13490 CXXConstructorDecl *
13491 Sema::findInheritingConstructor(SourceLocation Loc,
13492                                 CXXConstructorDecl *BaseCtor,
13493                                 ConstructorUsingShadowDecl *Shadow) {
13494   CXXRecordDecl *Derived = Shadow->getParent();
13495   SourceLocation UsingLoc = Shadow->getLocation();
13496 
13497   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13498   // For now we use the name of the base class constructor as a member of the
13499   // derived class to indicate a (fake) inherited constructor name.
13500   DeclarationName Name = BaseCtor->getDeclName();
13501 
13502   // Check to see if we already have a fake constructor for this inherited
13503   // constructor call.
13504   for (NamedDecl *Ctor : Derived->lookup(Name))
13505     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13506                                ->getInheritedConstructor()
13507                                .getConstructor(),
13508                            BaseCtor))
13509       return cast<CXXConstructorDecl>(Ctor);
13510 
13511   DeclarationNameInfo NameInfo(Name, UsingLoc);
13512   TypeSourceInfo *TInfo =
13513       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13514   FunctionProtoTypeLoc ProtoLoc =
13515       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13516 
13517   // Check the inherited constructor is valid and find the list of base classes
13518   // from which it was inherited.
13519   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13520 
13521   bool Constexpr =
13522       BaseCtor->isConstexpr() &&
13523       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13524                                         false, BaseCtor, &ICI);
13525 
13526   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13527       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13528       BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13529       /*isInline=*/true,
13530       /*isImplicitlyDeclared=*/true,
13531       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13532       InheritedConstructor(Shadow, BaseCtor),
13533       BaseCtor->getTrailingRequiresClause());
13534   if (Shadow->isInvalidDecl())
13535     DerivedCtor->setInvalidDecl();
13536 
13537   // Build an unevaluated exception specification for this fake constructor.
13538   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13539   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13540   EPI.ExceptionSpec.Type = EST_Unevaluated;
13541   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13542   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13543                                                FPT->getParamTypes(), EPI));
13544 
13545   // Build the parameter declarations.
13546   SmallVector<ParmVarDecl *, 16> ParamDecls;
13547   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13548     TypeSourceInfo *TInfo =
13549         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13550     ParmVarDecl *PD = ParmVarDecl::Create(
13551         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13552         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13553     PD->setScopeInfo(0, I);
13554     PD->setImplicit();
13555     // Ensure attributes are propagated onto parameters (this matters for
13556     // format, pass_object_size, ...).
13557     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13558     ParamDecls.push_back(PD);
13559     ProtoLoc.setParam(I, PD);
13560   }
13561 
13562   // Set up the new constructor.
13563   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13564   DerivedCtor->setAccess(BaseCtor->getAccess());
13565   DerivedCtor->setParams(ParamDecls);
13566   Derived->addDecl(DerivedCtor);
13567 
13568   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13569     SetDeclDeleted(DerivedCtor, UsingLoc);
13570 
13571   return DerivedCtor;
13572 }
13573 
13574 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13575   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13576                                Ctor->getInheritedConstructor().getShadowDecl());
13577   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13578                             /*Diagnose*/true);
13579 }
13580 
13581 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13582                                        CXXConstructorDecl *Constructor) {
13583   CXXRecordDecl *ClassDecl = Constructor->getParent();
13584   assert(Constructor->getInheritedConstructor() &&
13585          !Constructor->doesThisDeclarationHaveABody() &&
13586          !Constructor->isDeleted());
13587   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13588     return;
13589 
13590   // Initializations are performed "as if by a defaulted default constructor",
13591   // so enter the appropriate scope.
13592   SynthesizedFunctionScope Scope(*this, Constructor);
13593 
13594   // The exception specification is needed because we are defining the
13595   // function.
13596   ResolveExceptionSpec(CurrentLocation,
13597                        Constructor->getType()->castAs<FunctionProtoType>());
13598   MarkVTableUsed(CurrentLocation, ClassDecl);
13599 
13600   // Add a context note for diagnostics produced after this point.
13601   Scope.addContextNote(CurrentLocation);
13602 
13603   ConstructorUsingShadowDecl *Shadow =
13604       Constructor->getInheritedConstructor().getShadowDecl();
13605   CXXConstructorDecl *InheritedCtor =
13606       Constructor->getInheritedConstructor().getConstructor();
13607 
13608   // [class.inhctor.init]p1:
13609   //   initialization proceeds as if a defaulted default constructor is used to
13610   //   initialize the D object and each base class subobject from which the
13611   //   constructor was inherited
13612 
13613   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13614   CXXRecordDecl *RD = Shadow->getParent();
13615   SourceLocation InitLoc = Shadow->getLocation();
13616 
13617   // Build explicit initializers for all base classes from which the
13618   // constructor was inherited.
13619   SmallVector<CXXCtorInitializer*, 8> Inits;
13620   for (bool VBase : {false, true}) {
13621     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13622       if (B.isVirtual() != VBase)
13623         continue;
13624 
13625       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13626       if (!BaseRD)
13627         continue;
13628 
13629       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13630       if (!BaseCtor.first)
13631         continue;
13632 
13633       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13634       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13635           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13636 
13637       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13638       Inits.push_back(new (Context) CXXCtorInitializer(
13639           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13640           SourceLocation()));
13641     }
13642   }
13643 
13644   // We now proceed as if for a defaulted default constructor, with the relevant
13645   // initializers replaced.
13646 
13647   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13648     Constructor->setInvalidDecl();
13649     return;
13650   }
13651 
13652   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13653   Constructor->markUsed(Context);
13654 
13655   if (ASTMutationListener *L = getASTMutationListener()) {
13656     L->CompletedImplicitDefinition(Constructor);
13657   }
13658 
13659   DiagnoseUninitializedFields(*this, Constructor);
13660 }
13661 
13662 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13663   // C++ [class.dtor]p2:
13664   //   If a class has no user-declared destructor, a destructor is
13665   //   declared implicitly. An implicitly-declared destructor is an
13666   //   inline public member of its class.
13667   assert(ClassDecl->needsImplicitDestructor());
13668 
13669   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13670   if (DSM.isAlreadyBeingDeclared())
13671     return nullptr;
13672 
13673   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13674                                                      CXXDestructor,
13675                                                      false);
13676 
13677   // Create the actual destructor declaration.
13678   CanQualType ClassType
13679     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13680   SourceLocation ClassLoc = ClassDecl->getLocation();
13681   DeclarationName Name
13682     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13683   DeclarationNameInfo NameInfo(Name, ClassLoc);
13684   CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
13685       Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13686       getCurFPFeatures().isFPConstrained(),
13687       /*isInline=*/true,
13688       /*isImplicitlyDeclared=*/true,
13689       Constexpr ? ConstexprSpecKind::Constexpr
13690                 : ConstexprSpecKind::Unspecified);
13691   Destructor->setAccess(AS_public);
13692   Destructor->setDefaulted();
13693 
13694   if (getLangOpts().CUDA) {
13695     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13696                                             Destructor,
13697                                             /* ConstRHS */ false,
13698                                             /* Diagnose */ false);
13699   }
13700 
13701   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13702 
13703   // We don't need to use SpecialMemberIsTrivial here; triviality for
13704   // destructors is easy to compute.
13705   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13706   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13707                                 ClassDecl->hasTrivialDestructorForCall());
13708 
13709   // Note that we have declared this destructor.
13710   ++getASTContext().NumImplicitDestructorsDeclared;
13711 
13712   Scope *S = getScopeForContext(ClassDecl);
13713   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13714 
13715   // We can't check whether an implicit destructor is deleted before we complete
13716   // the definition of the class, because its validity depends on the alignment
13717   // of the class. We'll check this from ActOnFields once the class is complete.
13718   if (ClassDecl->isCompleteDefinition() &&
13719       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13720     SetDeclDeleted(Destructor, ClassLoc);
13721 
13722   // Introduce this destructor into its scope.
13723   if (S)
13724     PushOnScopeChains(Destructor, S, false);
13725   ClassDecl->addDecl(Destructor);
13726 
13727   return Destructor;
13728 }
13729 
13730 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13731                                     CXXDestructorDecl *Destructor) {
13732   assert((Destructor->isDefaulted() &&
13733           !Destructor->doesThisDeclarationHaveABody() &&
13734           !Destructor->isDeleted()) &&
13735          "DefineImplicitDestructor - call it for implicit default dtor");
13736   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13737     return;
13738 
13739   CXXRecordDecl *ClassDecl = Destructor->getParent();
13740   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13741 
13742   SynthesizedFunctionScope Scope(*this, Destructor);
13743 
13744   // The exception specification is needed because we are defining the
13745   // function.
13746   ResolveExceptionSpec(CurrentLocation,
13747                        Destructor->getType()->castAs<FunctionProtoType>());
13748   MarkVTableUsed(CurrentLocation, ClassDecl);
13749 
13750   // Add a context note for diagnostics produced after this point.
13751   Scope.addContextNote(CurrentLocation);
13752 
13753   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13754                                          Destructor->getParent());
13755 
13756   if (CheckDestructor(Destructor)) {
13757     Destructor->setInvalidDecl();
13758     return;
13759   }
13760 
13761   SourceLocation Loc = Destructor->getEndLoc().isValid()
13762                            ? Destructor->getEndLoc()
13763                            : Destructor->getLocation();
13764   Destructor->setBody(new (Context) CompoundStmt(Loc));
13765   Destructor->markUsed(Context);
13766 
13767   if (ASTMutationListener *L = getASTMutationListener()) {
13768     L->CompletedImplicitDefinition(Destructor);
13769   }
13770 }
13771 
13772 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13773                                           CXXDestructorDecl *Destructor) {
13774   if (Destructor->isInvalidDecl())
13775     return;
13776 
13777   CXXRecordDecl *ClassDecl = Destructor->getParent();
13778   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13779          "implicit complete dtors unneeded outside MS ABI");
13780   assert(ClassDecl->getNumVBases() > 0 &&
13781          "complete dtor only exists for classes with vbases");
13782 
13783   SynthesizedFunctionScope Scope(*this, Destructor);
13784 
13785   // Add a context note for diagnostics produced after this point.
13786   Scope.addContextNote(CurrentLocation);
13787 
13788   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13789 }
13790 
13791 /// Perform any semantic analysis which needs to be delayed until all
13792 /// pending class member declarations have been parsed.
13793 void Sema::ActOnFinishCXXMemberDecls() {
13794   // If the context is an invalid C++ class, just suppress these checks.
13795   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13796     if (Record->isInvalidDecl()) {
13797       DelayedOverridingExceptionSpecChecks.clear();
13798       DelayedEquivalentExceptionSpecChecks.clear();
13799       return;
13800     }
13801     checkForMultipleExportedDefaultConstructors(*this, Record);
13802   }
13803 }
13804 
13805 void Sema::ActOnFinishCXXNonNestedClass() {
13806   referenceDLLExportedClassMethods();
13807 
13808   if (!DelayedDllExportMemberFunctions.empty()) {
13809     SmallVector<CXXMethodDecl*, 4> WorkList;
13810     std::swap(DelayedDllExportMemberFunctions, WorkList);
13811     for (CXXMethodDecl *M : WorkList) {
13812       DefineDefaultedFunction(*this, M, M->getLocation());
13813 
13814       // Pass the method to the consumer to get emitted. This is not necessary
13815       // for explicit instantiation definitions, as they will get emitted
13816       // anyway.
13817       if (M->getParent()->getTemplateSpecializationKind() !=
13818           TSK_ExplicitInstantiationDefinition)
13819         ActOnFinishInlineFunctionDef(M);
13820     }
13821   }
13822 }
13823 
13824 void Sema::referenceDLLExportedClassMethods() {
13825   if (!DelayedDllExportClasses.empty()) {
13826     // Calling ReferenceDllExportedMembers might cause the current function to
13827     // be called again, so use a local copy of DelayedDllExportClasses.
13828     SmallVector<CXXRecordDecl *, 4> WorkList;
13829     std::swap(DelayedDllExportClasses, WorkList);
13830     for (CXXRecordDecl *Class : WorkList)
13831       ReferenceDllExportedMembers(*this, Class);
13832   }
13833 }
13834 
13835 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13836   assert(getLangOpts().CPlusPlus11 &&
13837          "adjusting dtor exception specs was introduced in c++11");
13838 
13839   if (Destructor->isDependentContext())
13840     return;
13841 
13842   // C++11 [class.dtor]p3:
13843   //   A declaration of a destructor that does not have an exception-
13844   //   specification is implicitly considered to have the same exception-
13845   //   specification as an implicit declaration.
13846   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13847   if (DtorType->hasExceptionSpec())
13848     return;
13849 
13850   // Replace the destructor's type, building off the existing one. Fortunately,
13851   // the only thing of interest in the destructor type is its extended info.
13852   // The return and arguments are fixed.
13853   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13854   EPI.ExceptionSpec.Type = EST_Unevaluated;
13855   EPI.ExceptionSpec.SourceDecl = Destructor;
13856   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13857 
13858   // FIXME: If the destructor has a body that could throw, and the newly created
13859   // spec doesn't allow exceptions, we should emit a warning, because this
13860   // change in behavior can break conforming C++03 programs at runtime.
13861   // However, we don't have a body or an exception specification yet, so it
13862   // needs to be done somewhere else.
13863 }
13864 
13865 namespace {
13866 /// An abstract base class for all helper classes used in building the
13867 //  copy/move operators. These classes serve as factory functions and help us
13868 //  avoid using the same Expr* in the AST twice.
13869 class ExprBuilder {
13870   ExprBuilder(const ExprBuilder&) = delete;
13871   ExprBuilder &operator=(const ExprBuilder&) = delete;
13872 
13873 protected:
13874   static Expr *assertNotNull(Expr *E) {
13875     assert(E && "Expression construction must not fail.");
13876     return E;
13877   }
13878 
13879 public:
13880   ExprBuilder() {}
13881   virtual ~ExprBuilder() {}
13882 
13883   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13884 };
13885 
13886 class RefBuilder: public ExprBuilder {
13887   VarDecl *Var;
13888   QualType VarType;
13889 
13890 public:
13891   Expr *build(Sema &S, SourceLocation Loc) const override {
13892     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13893   }
13894 
13895   RefBuilder(VarDecl *Var, QualType VarType)
13896       : Var(Var), VarType(VarType) {}
13897 };
13898 
13899 class ThisBuilder: public ExprBuilder {
13900 public:
13901   Expr *build(Sema &S, SourceLocation Loc) const override {
13902     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13903   }
13904 };
13905 
13906 class CastBuilder: public ExprBuilder {
13907   const ExprBuilder &Builder;
13908   QualType Type;
13909   ExprValueKind Kind;
13910   const CXXCastPath &Path;
13911 
13912 public:
13913   Expr *build(Sema &S, SourceLocation Loc) const override {
13914     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13915                                              CK_UncheckedDerivedToBase, Kind,
13916                                              &Path).get());
13917   }
13918 
13919   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13920               const CXXCastPath &Path)
13921       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13922 };
13923 
13924 class DerefBuilder: public ExprBuilder {
13925   const ExprBuilder &Builder;
13926 
13927 public:
13928   Expr *build(Sema &S, SourceLocation Loc) const override {
13929     return assertNotNull(
13930         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13931   }
13932 
13933   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13934 };
13935 
13936 class MemberBuilder: public ExprBuilder {
13937   const ExprBuilder &Builder;
13938   QualType Type;
13939   CXXScopeSpec SS;
13940   bool IsArrow;
13941   LookupResult &MemberLookup;
13942 
13943 public:
13944   Expr *build(Sema &S, SourceLocation Loc) const override {
13945     return assertNotNull(S.BuildMemberReferenceExpr(
13946         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13947         nullptr, MemberLookup, nullptr, nullptr).get());
13948   }
13949 
13950   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13951                 LookupResult &MemberLookup)
13952       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13953         MemberLookup(MemberLookup) {}
13954 };
13955 
13956 class MoveCastBuilder: public ExprBuilder {
13957   const ExprBuilder &Builder;
13958 
13959 public:
13960   Expr *build(Sema &S, SourceLocation Loc) const override {
13961     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13962   }
13963 
13964   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13965 };
13966 
13967 class LvalueConvBuilder: public ExprBuilder {
13968   const ExprBuilder &Builder;
13969 
13970 public:
13971   Expr *build(Sema &S, SourceLocation Loc) const override {
13972     return assertNotNull(
13973         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13974   }
13975 
13976   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13977 };
13978 
13979 class SubscriptBuilder: public ExprBuilder {
13980   const ExprBuilder &Base;
13981   const ExprBuilder &Index;
13982 
13983 public:
13984   Expr *build(Sema &S, SourceLocation Loc) const override {
13985     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13986         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13987   }
13988 
13989   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13990       : Base(Base), Index(Index) {}
13991 };
13992 
13993 } // end anonymous namespace
13994 
13995 /// When generating a defaulted copy or move assignment operator, if a field
13996 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13997 /// do so. This optimization only applies for arrays of scalars, and for arrays
13998 /// of class type where the selected copy/move-assignment operator is trivial.
13999 static StmtResult
14000 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14001                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
14002   // Compute the size of the memory buffer to be copied.
14003   QualType SizeType = S.Context.getSizeType();
14004   llvm::APInt Size(S.Context.getTypeSize(SizeType),
14005                    S.Context.getTypeSizeInChars(T).getQuantity());
14006 
14007   // Take the address of the field references for "from" and "to". We
14008   // directly construct UnaryOperators here because semantic analysis
14009   // does not permit us to take the address of an xvalue.
14010   Expr *From = FromB.build(S, Loc);
14011   From = UnaryOperator::Create(
14012       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14013       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14014   Expr *To = ToB.build(S, Loc);
14015   To = UnaryOperator::Create(
14016       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14017       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14018 
14019   const Type *E = T->getBaseElementTypeUnsafe();
14020   bool NeedsCollectableMemCpy =
14021       E->isRecordType() &&
14022       E->castAs<RecordType>()->getDecl()->hasObjectMember();
14023 
14024   // Create a reference to the __builtin_objc_memmove_collectable function
14025   StringRef MemCpyName = NeedsCollectableMemCpy ?
14026     "__builtin_objc_memmove_collectable" :
14027     "__builtin_memcpy";
14028   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14029                  Sema::LookupOrdinaryName);
14030   S.LookupName(R, S.TUScope, true);
14031 
14032   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14033   if (!MemCpy)
14034     // Something went horribly wrong earlier, and we will have complained
14035     // about it.
14036     return StmtError();
14037 
14038   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14039                                             VK_PRValue, Loc, nullptr);
14040   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14041 
14042   Expr *CallArgs[] = {
14043     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14044   };
14045   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14046                                     Loc, CallArgs, Loc);
14047 
14048   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14049   return Call.getAs<Stmt>();
14050 }
14051 
14052 /// Builds a statement that copies/moves the given entity from \p From to
14053 /// \c To.
14054 ///
14055 /// This routine is used to copy/move the members of a class with an
14056 /// implicitly-declared copy/move assignment operator. When the entities being
14057 /// copied are arrays, this routine builds for loops to copy them.
14058 ///
14059 /// \param S The Sema object used for type-checking.
14060 ///
14061 /// \param Loc The location where the implicit copy/move is being generated.
14062 ///
14063 /// \param T The type of the expressions being copied/moved. Both expressions
14064 /// must have this type.
14065 ///
14066 /// \param To The expression we are copying/moving to.
14067 ///
14068 /// \param From The expression we are copying/moving from.
14069 ///
14070 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14071 /// Otherwise, it's a non-static member subobject.
14072 ///
14073 /// \param Copying Whether we're copying or moving.
14074 ///
14075 /// \param Depth Internal parameter recording the depth of the recursion.
14076 ///
14077 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14078 /// if a memcpy should be used instead.
14079 static StmtResult
14080 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14081                                  const ExprBuilder &To, const ExprBuilder &From,
14082                                  bool CopyingBaseSubobject, bool Copying,
14083                                  unsigned Depth = 0) {
14084   // C++11 [class.copy]p28:
14085   //   Each subobject is assigned in the manner appropriate to its type:
14086   //
14087   //     - if the subobject is of class type, as if by a call to operator= with
14088   //       the subobject as the object expression and the corresponding
14089   //       subobject of x as a single function argument (as if by explicit
14090   //       qualification; that is, ignoring any possible virtual overriding
14091   //       functions in more derived classes);
14092   //
14093   // C++03 [class.copy]p13:
14094   //     - if the subobject is of class type, the copy assignment operator for
14095   //       the class is used (as if by explicit qualification; that is,
14096   //       ignoring any possible virtual overriding functions in more derived
14097   //       classes);
14098   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14099     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14100 
14101     // Look for operator=.
14102     DeclarationName Name
14103       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14104     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14105     S.LookupQualifiedName(OpLookup, ClassDecl, false);
14106 
14107     // Prior to C++11, filter out any result that isn't a copy/move-assignment
14108     // operator.
14109     if (!S.getLangOpts().CPlusPlus11) {
14110       LookupResult::Filter F = OpLookup.makeFilter();
14111       while (F.hasNext()) {
14112         NamedDecl *D = F.next();
14113         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14114           if (Method->isCopyAssignmentOperator() ||
14115               (!Copying && Method->isMoveAssignmentOperator()))
14116             continue;
14117 
14118         F.erase();
14119       }
14120       F.done();
14121     }
14122 
14123     // Suppress the protected check (C++ [class.protected]) for each of the
14124     // assignment operators we found. This strange dance is required when
14125     // we're assigning via a base classes's copy-assignment operator. To
14126     // ensure that we're getting the right base class subobject (without
14127     // ambiguities), we need to cast "this" to that subobject type; to
14128     // ensure that we don't go through the virtual call mechanism, we need
14129     // to qualify the operator= name with the base class (see below). However,
14130     // this means that if the base class has a protected copy assignment
14131     // operator, the protected member access check will fail. So, we
14132     // rewrite "protected" access to "public" access in this case, since we
14133     // know by construction that we're calling from a derived class.
14134     if (CopyingBaseSubobject) {
14135       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14136            L != LEnd; ++L) {
14137         if (L.getAccess() == AS_protected)
14138           L.setAccess(AS_public);
14139       }
14140     }
14141 
14142     // Create the nested-name-specifier that will be used to qualify the
14143     // reference to operator=; this is required to suppress the virtual
14144     // call mechanism.
14145     CXXScopeSpec SS;
14146     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14147     SS.MakeTrivial(S.Context,
14148                    NestedNameSpecifier::Create(S.Context, nullptr, false,
14149                                                CanonicalT),
14150                    Loc);
14151 
14152     // Create the reference to operator=.
14153     ExprResult OpEqualRef
14154       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14155                                    SS, /*TemplateKWLoc=*/SourceLocation(),
14156                                    /*FirstQualifierInScope=*/nullptr,
14157                                    OpLookup,
14158                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
14159                                    /*SuppressQualifierCheck=*/true);
14160     if (OpEqualRef.isInvalid())
14161       return StmtError();
14162 
14163     // Build the call to the assignment operator.
14164 
14165     Expr *FromInst = From.build(S, Loc);
14166     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14167                                                   OpEqualRef.getAs<Expr>(),
14168                                                   Loc, FromInst, Loc);
14169     if (Call.isInvalid())
14170       return StmtError();
14171 
14172     // If we built a call to a trivial 'operator=' while copying an array,
14173     // bail out. We'll replace the whole shebang with a memcpy.
14174     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14175     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14176       return StmtResult((Stmt*)nullptr);
14177 
14178     // Convert to an expression-statement, and clean up any produced
14179     // temporaries.
14180     return S.ActOnExprStmt(Call);
14181   }
14182 
14183   //     - if the subobject is of scalar type, the built-in assignment
14184   //       operator is used.
14185   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14186   if (!ArrayTy) {
14187     ExprResult Assignment = S.CreateBuiltinBinOp(
14188         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14189     if (Assignment.isInvalid())
14190       return StmtError();
14191     return S.ActOnExprStmt(Assignment);
14192   }
14193 
14194   //     - if the subobject is an array, each element is assigned, in the
14195   //       manner appropriate to the element type;
14196 
14197   // Construct a loop over the array bounds, e.g.,
14198   //
14199   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14200   //
14201   // that will copy each of the array elements.
14202   QualType SizeType = S.Context.getSizeType();
14203 
14204   // Create the iteration variable.
14205   IdentifierInfo *IterationVarName = nullptr;
14206   {
14207     SmallString<8> Str;
14208     llvm::raw_svector_ostream OS(Str);
14209     OS << "__i" << Depth;
14210     IterationVarName = &S.Context.Idents.get(OS.str());
14211   }
14212   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14213                                           IterationVarName, SizeType,
14214                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14215                                           SC_None);
14216 
14217   // Initialize the iteration variable to zero.
14218   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14219   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14220 
14221   // Creates a reference to the iteration variable.
14222   RefBuilder IterationVarRef(IterationVar, SizeType);
14223   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14224 
14225   // Create the DeclStmt that holds the iteration variable.
14226   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14227 
14228   // Subscript the "from" and "to" expressions with the iteration variable.
14229   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14230   MoveCastBuilder FromIndexMove(FromIndexCopy);
14231   const ExprBuilder *FromIndex;
14232   if (Copying)
14233     FromIndex = &FromIndexCopy;
14234   else
14235     FromIndex = &FromIndexMove;
14236 
14237   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14238 
14239   // Build the copy/move for an individual element of the array.
14240   StmtResult Copy =
14241     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14242                                      ToIndex, *FromIndex, CopyingBaseSubobject,
14243                                      Copying, Depth + 1);
14244   // Bail out if copying fails or if we determined that we should use memcpy.
14245   if (Copy.isInvalid() || !Copy.get())
14246     return Copy;
14247 
14248   // Create the comparison against the array bound.
14249   llvm::APInt Upper
14250     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14251   Expr *Comparison = BinaryOperator::Create(
14252       S.Context, IterationVarRefRVal.build(S, Loc),
14253       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14254       S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14255       S.CurFPFeatureOverrides());
14256 
14257   // Create the pre-increment of the iteration variable. We can determine
14258   // whether the increment will overflow based on the value of the array
14259   // bound.
14260   Expr *Increment = UnaryOperator::Create(
14261       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14262       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14263 
14264   // Construct the loop that copies all elements of this array.
14265   return S.ActOnForStmt(
14266       Loc, Loc, InitStmt,
14267       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14268       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14269 }
14270 
14271 static StmtResult
14272 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14273                       const ExprBuilder &To, const ExprBuilder &From,
14274                       bool CopyingBaseSubobject, bool Copying) {
14275   // Maybe we should use a memcpy?
14276   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14277       T.isTriviallyCopyableType(S.Context))
14278     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14279 
14280   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14281                                                      CopyingBaseSubobject,
14282                                                      Copying, 0));
14283 
14284   // If we ended up picking a trivial assignment operator for an array of a
14285   // non-trivially-copyable class type, just emit a memcpy.
14286   if (!Result.isInvalid() && !Result.get())
14287     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14288 
14289   return Result;
14290 }
14291 
14292 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14293   // Note: The following rules are largely analoguous to the copy
14294   // constructor rules. Note that virtual bases are not taken into account
14295   // for determining the argument type of the operator. Note also that
14296   // operators taking an object instead of a reference are allowed.
14297   assert(ClassDecl->needsImplicitCopyAssignment());
14298 
14299   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14300   if (DSM.isAlreadyBeingDeclared())
14301     return nullptr;
14302 
14303   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14304   LangAS AS = getDefaultCXXMethodAddrSpace();
14305   if (AS != LangAS::Default)
14306     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14307   QualType RetType = Context.getLValueReferenceType(ArgType);
14308   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14309   if (Const)
14310     ArgType = ArgType.withConst();
14311 
14312   ArgType = Context.getLValueReferenceType(ArgType);
14313 
14314   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14315                                                      CXXCopyAssignment,
14316                                                      Const);
14317 
14318   //   An implicitly-declared copy assignment operator is an inline public
14319   //   member of its class.
14320   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14321   SourceLocation ClassLoc = ClassDecl->getLocation();
14322   DeclarationNameInfo NameInfo(Name, ClassLoc);
14323   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14324       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14325       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14326       getCurFPFeatures().isFPConstrained(),
14327       /*isInline=*/true,
14328       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14329       SourceLocation());
14330   CopyAssignment->setAccess(AS_public);
14331   CopyAssignment->setDefaulted();
14332   CopyAssignment->setImplicit();
14333 
14334   if (getLangOpts().CUDA) {
14335     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14336                                             CopyAssignment,
14337                                             /* ConstRHS */ Const,
14338                                             /* Diagnose */ false);
14339   }
14340 
14341   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14342 
14343   // Add the parameter to the operator.
14344   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14345                                                ClassLoc, ClassLoc,
14346                                                /*Id=*/nullptr, ArgType,
14347                                                /*TInfo=*/nullptr, SC_None,
14348                                                nullptr);
14349   CopyAssignment->setParams(FromParam);
14350 
14351   CopyAssignment->setTrivial(
14352     ClassDecl->needsOverloadResolutionForCopyAssignment()
14353       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14354       : ClassDecl->hasTrivialCopyAssignment());
14355 
14356   // Note that we have added this copy-assignment operator.
14357   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14358 
14359   Scope *S = getScopeForContext(ClassDecl);
14360   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14361 
14362   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14363     ClassDecl->setImplicitCopyAssignmentIsDeleted();
14364     SetDeclDeleted(CopyAssignment, ClassLoc);
14365   }
14366 
14367   if (S)
14368     PushOnScopeChains(CopyAssignment, S, false);
14369   ClassDecl->addDecl(CopyAssignment);
14370 
14371   return CopyAssignment;
14372 }
14373 
14374 /// Diagnose an implicit copy operation for a class which is odr-used, but
14375 /// which is deprecated because the class has a user-declared copy constructor,
14376 /// copy assignment operator, or destructor.
14377 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14378   assert(CopyOp->isImplicit());
14379 
14380   CXXRecordDecl *RD = CopyOp->getParent();
14381   CXXMethodDecl *UserDeclaredOperation = nullptr;
14382 
14383   // In Microsoft mode, assignment operations don't affect constructors and
14384   // vice versa.
14385   if (RD->hasUserDeclaredDestructor()) {
14386     UserDeclaredOperation = RD->getDestructor();
14387   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14388              RD->hasUserDeclaredCopyConstructor() &&
14389              !S.getLangOpts().MSVCCompat) {
14390     // Find any user-declared copy constructor.
14391     for (auto *I : RD->ctors()) {
14392       if (I->isCopyConstructor()) {
14393         UserDeclaredOperation = I;
14394         break;
14395       }
14396     }
14397     assert(UserDeclaredOperation);
14398   } else if (isa<CXXConstructorDecl>(CopyOp) &&
14399              RD->hasUserDeclaredCopyAssignment() &&
14400              !S.getLangOpts().MSVCCompat) {
14401     // Find any user-declared move assignment operator.
14402     for (auto *I : RD->methods()) {
14403       if (I->isCopyAssignmentOperator()) {
14404         UserDeclaredOperation = I;
14405         break;
14406       }
14407     }
14408     assert(UserDeclaredOperation);
14409   }
14410 
14411   if (UserDeclaredOperation) {
14412     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14413     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14414     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14415     unsigned DiagID =
14416         (UDOIsUserProvided && UDOIsDestructor)
14417             ? diag::warn_deprecated_copy_with_user_provided_dtor
14418         : (UDOIsUserProvided && !UDOIsDestructor)
14419             ? diag::warn_deprecated_copy_with_user_provided_copy
14420         : (!UDOIsUserProvided && UDOIsDestructor)
14421             ? diag::warn_deprecated_copy_with_dtor
14422             : diag::warn_deprecated_copy;
14423     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14424         << RD << IsCopyAssignment;
14425   }
14426 }
14427 
14428 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14429                                         CXXMethodDecl *CopyAssignOperator) {
14430   assert((CopyAssignOperator->isDefaulted() &&
14431           CopyAssignOperator->isOverloadedOperator() &&
14432           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14433           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14434           !CopyAssignOperator->isDeleted()) &&
14435          "DefineImplicitCopyAssignment called for wrong function");
14436   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14437     return;
14438 
14439   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14440   if (ClassDecl->isInvalidDecl()) {
14441     CopyAssignOperator->setInvalidDecl();
14442     return;
14443   }
14444 
14445   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14446 
14447   // The exception specification is needed because we are defining the
14448   // function.
14449   ResolveExceptionSpec(CurrentLocation,
14450                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14451 
14452   // Add a context note for diagnostics produced after this point.
14453   Scope.addContextNote(CurrentLocation);
14454 
14455   // C++11 [class.copy]p18:
14456   //   The [definition of an implicitly declared copy assignment operator] is
14457   //   deprecated if the class has a user-declared copy constructor or a
14458   //   user-declared destructor.
14459   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14460     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14461 
14462   // C++0x [class.copy]p30:
14463   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14464   //   for a non-union class X performs memberwise copy assignment of its
14465   //   subobjects. The direct base classes of X are assigned first, in the
14466   //   order of their declaration in the base-specifier-list, and then the
14467   //   immediate non-static data members of X are assigned, in the order in
14468   //   which they were declared in the class definition.
14469 
14470   // The statements that form the synthesized function body.
14471   SmallVector<Stmt*, 8> Statements;
14472 
14473   // The parameter for the "other" object, which we are copying from.
14474   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14475   Qualifiers OtherQuals = Other->getType().getQualifiers();
14476   QualType OtherRefType = Other->getType();
14477   if (const LValueReferenceType *OtherRef
14478                                 = OtherRefType->getAs<LValueReferenceType>()) {
14479     OtherRefType = OtherRef->getPointeeType();
14480     OtherQuals = OtherRefType.getQualifiers();
14481   }
14482 
14483   // Our location for everything implicitly-generated.
14484   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14485                            ? CopyAssignOperator->getEndLoc()
14486                            : CopyAssignOperator->getLocation();
14487 
14488   // Builds a DeclRefExpr for the "other" object.
14489   RefBuilder OtherRef(Other, OtherRefType);
14490 
14491   // Builds the "this" pointer.
14492   ThisBuilder This;
14493 
14494   // Assign base classes.
14495   bool Invalid = false;
14496   for (auto &Base : ClassDecl->bases()) {
14497     // Form the assignment:
14498     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14499     QualType BaseType = Base.getType().getUnqualifiedType();
14500     if (!BaseType->isRecordType()) {
14501       Invalid = true;
14502       continue;
14503     }
14504 
14505     CXXCastPath BasePath;
14506     BasePath.push_back(&Base);
14507 
14508     // Construct the "from" expression, which is an implicit cast to the
14509     // appropriately-qualified base type.
14510     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14511                      VK_LValue, BasePath);
14512 
14513     // Dereference "this".
14514     DerefBuilder DerefThis(This);
14515     CastBuilder To(DerefThis,
14516                    Context.getQualifiedType(
14517                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14518                    VK_LValue, BasePath);
14519 
14520     // Build the copy.
14521     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14522                                             To, From,
14523                                             /*CopyingBaseSubobject=*/true,
14524                                             /*Copying=*/true);
14525     if (Copy.isInvalid()) {
14526       CopyAssignOperator->setInvalidDecl();
14527       return;
14528     }
14529 
14530     // Success! Record the copy.
14531     Statements.push_back(Copy.getAs<Expr>());
14532   }
14533 
14534   // Assign non-static members.
14535   for (auto *Field : ClassDecl->fields()) {
14536     // FIXME: We should form some kind of AST representation for the implied
14537     // memcpy in a union copy operation.
14538     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14539       continue;
14540 
14541     if (Field->isInvalidDecl()) {
14542       Invalid = true;
14543       continue;
14544     }
14545 
14546     // Check for members of reference type; we can't copy those.
14547     if (Field->getType()->isReferenceType()) {
14548       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14549         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14550       Diag(Field->getLocation(), diag::note_declared_at);
14551       Invalid = true;
14552       continue;
14553     }
14554 
14555     // Check for members of const-qualified, non-class type.
14556     QualType BaseType = Context.getBaseElementType(Field->getType());
14557     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14558       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14559         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14560       Diag(Field->getLocation(), diag::note_declared_at);
14561       Invalid = true;
14562       continue;
14563     }
14564 
14565     // Suppress assigning zero-width bitfields.
14566     if (Field->isZeroLengthBitField(Context))
14567       continue;
14568 
14569     QualType FieldType = Field->getType().getNonReferenceType();
14570     if (FieldType->isIncompleteArrayType()) {
14571       assert(ClassDecl->hasFlexibleArrayMember() &&
14572              "Incomplete array type is not valid");
14573       continue;
14574     }
14575 
14576     // Build references to the field in the object we're copying from and to.
14577     CXXScopeSpec SS; // Intentionally empty
14578     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14579                               LookupMemberName);
14580     MemberLookup.addDecl(Field);
14581     MemberLookup.resolveKind();
14582 
14583     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14584 
14585     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14586 
14587     // Build the copy of this field.
14588     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14589                                             To, From,
14590                                             /*CopyingBaseSubobject=*/false,
14591                                             /*Copying=*/true);
14592     if (Copy.isInvalid()) {
14593       CopyAssignOperator->setInvalidDecl();
14594       return;
14595     }
14596 
14597     // Success! Record the copy.
14598     Statements.push_back(Copy.getAs<Stmt>());
14599   }
14600 
14601   if (!Invalid) {
14602     // Add a "return *this;"
14603     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14604 
14605     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14606     if (Return.isInvalid())
14607       Invalid = true;
14608     else
14609       Statements.push_back(Return.getAs<Stmt>());
14610   }
14611 
14612   if (Invalid) {
14613     CopyAssignOperator->setInvalidDecl();
14614     return;
14615   }
14616 
14617   StmtResult Body;
14618   {
14619     CompoundScopeRAII CompoundScope(*this);
14620     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14621                              /*isStmtExpr=*/false);
14622     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14623   }
14624   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14625   CopyAssignOperator->markUsed(Context);
14626 
14627   if (ASTMutationListener *L = getASTMutationListener()) {
14628     L->CompletedImplicitDefinition(CopyAssignOperator);
14629   }
14630 }
14631 
14632 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14633   assert(ClassDecl->needsImplicitMoveAssignment());
14634 
14635   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14636   if (DSM.isAlreadyBeingDeclared())
14637     return nullptr;
14638 
14639   // Note: The following rules are largely analoguous to the move
14640   // constructor rules.
14641 
14642   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14643   LangAS AS = getDefaultCXXMethodAddrSpace();
14644   if (AS != LangAS::Default)
14645     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14646   QualType RetType = Context.getLValueReferenceType(ArgType);
14647   ArgType = Context.getRValueReferenceType(ArgType);
14648 
14649   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14650                                                      CXXMoveAssignment,
14651                                                      false);
14652 
14653   //   An implicitly-declared move assignment operator is an inline public
14654   //   member of its class.
14655   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14656   SourceLocation ClassLoc = ClassDecl->getLocation();
14657   DeclarationNameInfo NameInfo(Name, ClassLoc);
14658   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14659       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14660       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14661       getCurFPFeatures().isFPConstrained(),
14662       /*isInline=*/true,
14663       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14664       SourceLocation());
14665   MoveAssignment->setAccess(AS_public);
14666   MoveAssignment->setDefaulted();
14667   MoveAssignment->setImplicit();
14668 
14669   if (getLangOpts().CUDA) {
14670     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14671                                             MoveAssignment,
14672                                             /* ConstRHS */ false,
14673                                             /* Diagnose */ false);
14674   }
14675 
14676   setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14677 
14678   // Add the parameter to the operator.
14679   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14680                                                ClassLoc, ClassLoc,
14681                                                /*Id=*/nullptr, ArgType,
14682                                                /*TInfo=*/nullptr, SC_None,
14683                                                nullptr);
14684   MoveAssignment->setParams(FromParam);
14685 
14686   MoveAssignment->setTrivial(
14687     ClassDecl->needsOverloadResolutionForMoveAssignment()
14688       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14689       : ClassDecl->hasTrivialMoveAssignment());
14690 
14691   // Note that we have added this copy-assignment operator.
14692   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14693 
14694   Scope *S = getScopeForContext(ClassDecl);
14695   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14696 
14697   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14698     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14699     SetDeclDeleted(MoveAssignment, ClassLoc);
14700   }
14701 
14702   if (S)
14703     PushOnScopeChains(MoveAssignment, S, false);
14704   ClassDecl->addDecl(MoveAssignment);
14705 
14706   return MoveAssignment;
14707 }
14708 
14709 /// Check if we're implicitly defining a move assignment operator for a class
14710 /// with virtual bases. Such a move assignment might move-assign the virtual
14711 /// base multiple times.
14712 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14713                                                SourceLocation CurrentLocation) {
14714   assert(!Class->isDependentContext() && "should not define dependent move");
14715 
14716   // Only a virtual base could get implicitly move-assigned multiple times.
14717   // Only a non-trivial move assignment can observe this. We only want to
14718   // diagnose if we implicitly define an assignment operator that assigns
14719   // two base classes, both of which move-assign the same virtual base.
14720   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14721       Class->getNumBases() < 2)
14722     return;
14723 
14724   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14725   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14726   VBaseMap VBases;
14727 
14728   for (auto &BI : Class->bases()) {
14729     Worklist.push_back(&BI);
14730     while (!Worklist.empty()) {
14731       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14732       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14733 
14734       // If the base has no non-trivial move assignment operators,
14735       // we don't care about moves from it.
14736       if (!Base->hasNonTrivialMoveAssignment())
14737         continue;
14738 
14739       // If there's nothing virtual here, skip it.
14740       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14741         continue;
14742 
14743       // If we're not actually going to call a move assignment for this base,
14744       // or the selected move assignment is trivial, skip it.
14745       Sema::SpecialMemberOverloadResult SMOR =
14746         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14747                               /*ConstArg*/false, /*VolatileArg*/false,
14748                               /*RValueThis*/true, /*ConstThis*/false,
14749                               /*VolatileThis*/false);
14750       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14751           !SMOR.getMethod()->isMoveAssignmentOperator())
14752         continue;
14753 
14754       if (BaseSpec->isVirtual()) {
14755         // We're going to move-assign this virtual base, and its move
14756         // assignment operator is not trivial. If this can happen for
14757         // multiple distinct direct bases of Class, diagnose it. (If it
14758         // only happens in one base, we'll diagnose it when synthesizing
14759         // that base class's move assignment operator.)
14760         CXXBaseSpecifier *&Existing =
14761             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14762                 .first->second;
14763         if (Existing && Existing != &BI) {
14764           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14765             << Class << Base;
14766           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14767               << (Base->getCanonicalDecl() ==
14768                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14769               << Base << Existing->getType() << Existing->getSourceRange();
14770           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14771               << (Base->getCanonicalDecl() ==
14772                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14773               << Base << BI.getType() << BaseSpec->getSourceRange();
14774 
14775           // Only diagnose each vbase once.
14776           Existing = nullptr;
14777         }
14778       } else {
14779         // Only walk over bases that have defaulted move assignment operators.
14780         // We assume that any user-provided move assignment operator handles
14781         // the multiple-moves-of-vbase case itself somehow.
14782         if (!SMOR.getMethod()->isDefaulted())
14783           continue;
14784 
14785         // We're going to move the base classes of Base. Add them to the list.
14786         llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
14787       }
14788     }
14789   }
14790 }
14791 
14792 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14793                                         CXXMethodDecl *MoveAssignOperator) {
14794   assert((MoveAssignOperator->isDefaulted() &&
14795           MoveAssignOperator->isOverloadedOperator() &&
14796           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14797           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14798           !MoveAssignOperator->isDeleted()) &&
14799          "DefineImplicitMoveAssignment called for wrong function");
14800   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14801     return;
14802 
14803   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14804   if (ClassDecl->isInvalidDecl()) {
14805     MoveAssignOperator->setInvalidDecl();
14806     return;
14807   }
14808 
14809   // C++0x [class.copy]p28:
14810   //   The implicitly-defined or move assignment operator for a non-union class
14811   //   X performs memberwise move assignment of its subobjects. The direct base
14812   //   classes of X are assigned first, in the order of their declaration in the
14813   //   base-specifier-list, and then the immediate non-static data members of X
14814   //   are assigned, in the order in which they were declared in the class
14815   //   definition.
14816 
14817   // Issue a warning if our implicit move assignment operator will move
14818   // from a virtual base more than once.
14819   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14820 
14821   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14822 
14823   // The exception specification is needed because we are defining the
14824   // function.
14825   ResolveExceptionSpec(CurrentLocation,
14826                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14827 
14828   // Add a context note for diagnostics produced after this point.
14829   Scope.addContextNote(CurrentLocation);
14830 
14831   // The statements that form the synthesized function body.
14832   SmallVector<Stmt*, 8> Statements;
14833 
14834   // The parameter for the "other" object, which we are move from.
14835   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14836   QualType OtherRefType =
14837       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14838 
14839   // Our location for everything implicitly-generated.
14840   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14841                            ? MoveAssignOperator->getEndLoc()
14842                            : MoveAssignOperator->getLocation();
14843 
14844   // Builds a reference to the "other" object.
14845   RefBuilder OtherRef(Other, OtherRefType);
14846   // Cast to rvalue.
14847   MoveCastBuilder MoveOther(OtherRef);
14848 
14849   // Builds the "this" pointer.
14850   ThisBuilder This;
14851 
14852   // Assign base classes.
14853   bool Invalid = false;
14854   for (auto &Base : ClassDecl->bases()) {
14855     // C++11 [class.copy]p28:
14856     //   It is unspecified whether subobjects representing virtual base classes
14857     //   are assigned more than once by the implicitly-defined copy assignment
14858     //   operator.
14859     // FIXME: Do not assign to a vbase that will be assigned by some other base
14860     // class. For a move-assignment, this can result in the vbase being moved
14861     // multiple times.
14862 
14863     // Form the assignment:
14864     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14865     QualType BaseType = Base.getType().getUnqualifiedType();
14866     if (!BaseType->isRecordType()) {
14867       Invalid = true;
14868       continue;
14869     }
14870 
14871     CXXCastPath BasePath;
14872     BasePath.push_back(&Base);
14873 
14874     // Construct the "from" expression, which is an implicit cast to the
14875     // appropriately-qualified base type.
14876     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14877 
14878     // Dereference "this".
14879     DerefBuilder DerefThis(This);
14880 
14881     // Implicitly cast "this" to the appropriately-qualified base type.
14882     CastBuilder To(DerefThis,
14883                    Context.getQualifiedType(
14884                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14885                    VK_LValue, BasePath);
14886 
14887     // Build the move.
14888     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14889                                             To, From,
14890                                             /*CopyingBaseSubobject=*/true,
14891                                             /*Copying=*/false);
14892     if (Move.isInvalid()) {
14893       MoveAssignOperator->setInvalidDecl();
14894       return;
14895     }
14896 
14897     // Success! Record the move.
14898     Statements.push_back(Move.getAs<Expr>());
14899   }
14900 
14901   // Assign non-static members.
14902   for (auto *Field : ClassDecl->fields()) {
14903     // FIXME: We should form some kind of AST representation for the implied
14904     // memcpy in a union copy operation.
14905     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14906       continue;
14907 
14908     if (Field->isInvalidDecl()) {
14909       Invalid = true;
14910       continue;
14911     }
14912 
14913     // Check for members of reference type; we can't move those.
14914     if (Field->getType()->isReferenceType()) {
14915       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14916         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14917       Diag(Field->getLocation(), diag::note_declared_at);
14918       Invalid = true;
14919       continue;
14920     }
14921 
14922     // Check for members of const-qualified, non-class type.
14923     QualType BaseType = Context.getBaseElementType(Field->getType());
14924     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14925       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14926         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14927       Diag(Field->getLocation(), diag::note_declared_at);
14928       Invalid = true;
14929       continue;
14930     }
14931 
14932     // Suppress assigning zero-width bitfields.
14933     if (Field->isZeroLengthBitField(Context))
14934       continue;
14935 
14936     QualType FieldType = Field->getType().getNonReferenceType();
14937     if (FieldType->isIncompleteArrayType()) {
14938       assert(ClassDecl->hasFlexibleArrayMember() &&
14939              "Incomplete array type is not valid");
14940       continue;
14941     }
14942 
14943     // Build references to the field in the object we're copying from and to.
14944     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14945                               LookupMemberName);
14946     MemberLookup.addDecl(Field);
14947     MemberLookup.resolveKind();
14948     MemberBuilder From(MoveOther, OtherRefType,
14949                        /*IsArrow=*/false, MemberLookup);
14950     MemberBuilder To(This, getCurrentThisType(),
14951                      /*IsArrow=*/true, MemberLookup);
14952 
14953     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14954         "Member reference with rvalue base must be rvalue except for reference "
14955         "members, which aren't allowed for move assignment.");
14956 
14957     // Build the move of this field.
14958     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14959                                             To, From,
14960                                             /*CopyingBaseSubobject=*/false,
14961                                             /*Copying=*/false);
14962     if (Move.isInvalid()) {
14963       MoveAssignOperator->setInvalidDecl();
14964       return;
14965     }
14966 
14967     // Success! Record the copy.
14968     Statements.push_back(Move.getAs<Stmt>());
14969   }
14970 
14971   if (!Invalid) {
14972     // Add a "return *this;"
14973     ExprResult ThisObj =
14974         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14975 
14976     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14977     if (Return.isInvalid())
14978       Invalid = true;
14979     else
14980       Statements.push_back(Return.getAs<Stmt>());
14981   }
14982 
14983   if (Invalid) {
14984     MoveAssignOperator->setInvalidDecl();
14985     return;
14986   }
14987 
14988   StmtResult Body;
14989   {
14990     CompoundScopeRAII CompoundScope(*this);
14991     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14992                              /*isStmtExpr=*/false);
14993     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14994   }
14995   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14996   MoveAssignOperator->markUsed(Context);
14997 
14998   if (ASTMutationListener *L = getASTMutationListener()) {
14999     L->CompletedImplicitDefinition(MoveAssignOperator);
15000   }
15001 }
15002 
15003 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15004                                                     CXXRecordDecl *ClassDecl) {
15005   // C++ [class.copy]p4:
15006   //   If the class definition does not explicitly declare a copy
15007   //   constructor, one is declared implicitly.
15008   assert(ClassDecl->needsImplicitCopyConstructor());
15009 
15010   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15011   if (DSM.isAlreadyBeingDeclared())
15012     return nullptr;
15013 
15014   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15015   QualType ArgType = ClassType;
15016   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15017   if (Const)
15018     ArgType = ArgType.withConst();
15019 
15020   LangAS AS = getDefaultCXXMethodAddrSpace();
15021   if (AS != LangAS::Default)
15022     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15023 
15024   ArgType = Context.getLValueReferenceType(ArgType);
15025 
15026   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15027                                                      CXXCopyConstructor,
15028                                                      Const);
15029 
15030   DeclarationName Name
15031     = Context.DeclarationNames.getCXXConstructorName(
15032                                            Context.getCanonicalType(ClassType));
15033   SourceLocation ClassLoc = ClassDecl->getLocation();
15034   DeclarationNameInfo NameInfo(Name, ClassLoc);
15035 
15036   //   An implicitly-declared copy constructor is an inline public
15037   //   member of its class.
15038   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15039       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15040       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15041       /*isInline=*/true,
15042       /*isImplicitlyDeclared=*/true,
15043       Constexpr ? ConstexprSpecKind::Constexpr
15044                 : ConstexprSpecKind::Unspecified);
15045   CopyConstructor->setAccess(AS_public);
15046   CopyConstructor->setDefaulted();
15047 
15048   if (getLangOpts().CUDA) {
15049     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15050                                             CopyConstructor,
15051                                             /* ConstRHS */ Const,
15052                                             /* Diagnose */ false);
15053   }
15054 
15055   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
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   if (getLangOpts().CUDA) {
15189     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15190                                             MoveConstructor,
15191                                             /* ConstRHS */ false,
15192                                             /* Diagnose */ false);
15193   }
15194 
15195   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15196 
15197   // Add the parameter to the constructor.
15198   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15199                                                ClassLoc, ClassLoc,
15200                                                /*IdentifierInfo=*/nullptr,
15201                                                ArgType, /*TInfo=*/nullptr,
15202                                                SC_None, nullptr);
15203   MoveConstructor->setParams(FromParam);
15204 
15205   MoveConstructor->setTrivial(
15206       ClassDecl->needsOverloadResolutionForMoveConstructor()
15207           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15208           : ClassDecl->hasTrivialMoveConstructor());
15209 
15210   MoveConstructor->setTrivialForCall(
15211       ClassDecl->hasAttr<TrivialABIAttr>() ||
15212       (ClassDecl->needsOverloadResolutionForMoveConstructor()
15213            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15214                                     TAH_ConsiderTrivialABI)
15215            : ClassDecl->hasTrivialMoveConstructorForCall()));
15216 
15217   // Note that we have declared this constructor.
15218   ++getASTContext().NumImplicitMoveConstructorsDeclared;
15219 
15220   Scope *S = getScopeForContext(ClassDecl);
15221   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15222 
15223   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15224     ClassDecl->setImplicitMoveConstructorIsDeleted();
15225     SetDeclDeleted(MoveConstructor, ClassLoc);
15226   }
15227 
15228   if (S)
15229     PushOnScopeChains(MoveConstructor, S, false);
15230   ClassDecl->addDecl(MoveConstructor);
15231 
15232   return MoveConstructor;
15233 }
15234 
15235 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15236                                          CXXConstructorDecl *MoveConstructor) {
15237   assert((MoveConstructor->isDefaulted() &&
15238           MoveConstructor->isMoveConstructor() &&
15239           !MoveConstructor->doesThisDeclarationHaveABody() &&
15240           !MoveConstructor->isDeleted()) &&
15241          "DefineImplicitMoveConstructor - call it for implicit move ctor");
15242   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15243     return;
15244 
15245   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15246   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15247 
15248   SynthesizedFunctionScope Scope(*this, MoveConstructor);
15249 
15250   // The exception specification is needed because we are defining the
15251   // function.
15252   ResolveExceptionSpec(CurrentLocation,
15253                        MoveConstructor->getType()->castAs<FunctionProtoType>());
15254   MarkVTableUsed(CurrentLocation, ClassDecl);
15255 
15256   // Add a context note for diagnostics produced after this point.
15257   Scope.addContextNote(CurrentLocation);
15258 
15259   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15260     MoveConstructor->setInvalidDecl();
15261   } else {
15262     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15263                              ? MoveConstructor->getEndLoc()
15264                              : MoveConstructor->getLocation();
15265     Sema::CompoundScopeRAII CompoundScope(*this);
15266     MoveConstructor->setBody(ActOnCompoundStmt(
15267         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
15268     MoveConstructor->markUsed(Context);
15269   }
15270 
15271   if (ASTMutationListener *L = getASTMutationListener()) {
15272     L->CompletedImplicitDefinition(MoveConstructor);
15273   }
15274 }
15275 
15276 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15277   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15278 }
15279 
15280 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15281                             SourceLocation CurrentLocation,
15282                             CXXConversionDecl *Conv) {
15283   SynthesizedFunctionScope Scope(*this, Conv);
15284   assert(!Conv->getReturnType()->isUndeducedType());
15285 
15286   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15287   CallingConv CC =
15288       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15289 
15290   CXXRecordDecl *Lambda = Conv->getParent();
15291   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15292   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
15293 
15294   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15295     CallOp = InstantiateFunctionDeclaration(
15296         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15297     if (!CallOp)
15298       return;
15299 
15300     Invoker = InstantiateFunctionDeclaration(
15301         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15302     if (!Invoker)
15303       return;
15304   }
15305 
15306   if (CallOp->isInvalidDecl())
15307     return;
15308 
15309   // Mark the call operator referenced (and add to pending instantiations
15310   // if necessary).
15311   // For both the conversion and static-invoker template specializations
15312   // we construct their body's in this function, so no need to add them
15313   // to the PendingInstantiations.
15314   MarkFunctionReferenced(CurrentLocation, CallOp);
15315 
15316   // Fill in the __invoke function with a dummy implementation. IR generation
15317   // will fill in the actual details. Update its type in case it contained
15318   // an 'auto'.
15319   Invoker->markUsed(Context);
15320   Invoker->setReferenced();
15321   Invoker->setType(Conv->getReturnType()->getPointeeType());
15322   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15323 
15324   // Construct the body of the conversion function { return __invoke; }.
15325   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
15326                                        VK_LValue, Conv->getLocation());
15327   assert(FunctionRef && "Can't refer to __invoke function?");
15328   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15329   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
15330                                      Conv->getLocation()));
15331   Conv->markUsed(Context);
15332   Conv->setReferenced();
15333 
15334   if (ASTMutationListener *L = getASTMutationListener()) {
15335     L->CompletedImplicitDefinition(Conv);
15336     L->CompletedImplicitDefinition(Invoker);
15337   }
15338 }
15339 
15340 
15341 
15342 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15343        SourceLocation CurrentLocation,
15344        CXXConversionDecl *Conv)
15345 {
15346   assert(!Conv->getParent()->isGenericLambda());
15347 
15348   SynthesizedFunctionScope Scope(*this, Conv);
15349 
15350   // Copy-initialize the lambda object as needed to capture it.
15351   Expr *This = ActOnCXXThis(CurrentLocation).get();
15352   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15353 
15354   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15355                                                         Conv->getLocation(),
15356                                                         Conv, DerefThis);
15357 
15358   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15359   // behavior.  Note that only the general conversion function does this
15360   // (since it's unusable otherwise); in the case where we inline the
15361   // block literal, it has block literal lifetime semantics.
15362   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15363     BuildBlock = ImplicitCastExpr::Create(
15364         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15365         BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15366 
15367   if (BuildBlock.isInvalid()) {
15368     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15369     Conv->setInvalidDecl();
15370     return;
15371   }
15372 
15373   // Create the return statement that returns the block from the conversion
15374   // function.
15375   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15376   if (Return.isInvalid()) {
15377     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15378     Conv->setInvalidDecl();
15379     return;
15380   }
15381 
15382   // Set the body of the conversion function.
15383   Stmt *ReturnS = Return.get();
15384   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
15385                                      Conv->getLocation()));
15386   Conv->markUsed(Context);
15387 
15388   // We're done; notify the mutation listener, if any.
15389   if (ASTMutationListener *L = getASTMutationListener()) {
15390     L->CompletedImplicitDefinition(Conv);
15391   }
15392 }
15393 
15394 /// Determine whether the given list arguments contains exactly one
15395 /// "real" (non-default) argument.
15396 static bool hasOneRealArgument(MultiExprArg Args) {
15397   switch (Args.size()) {
15398   case 0:
15399     return false;
15400 
15401   default:
15402     if (!Args[1]->isDefaultArgument())
15403       return false;
15404 
15405     LLVM_FALLTHROUGH;
15406   case 1:
15407     return !Args[0]->isDefaultArgument();
15408   }
15409 
15410   return false;
15411 }
15412 
15413 ExprResult
15414 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15415                             NamedDecl *FoundDecl,
15416                             CXXConstructorDecl *Constructor,
15417                             MultiExprArg ExprArgs,
15418                             bool HadMultipleCandidates,
15419                             bool IsListInitialization,
15420                             bool IsStdInitListInitialization,
15421                             bool RequiresZeroInit,
15422                             unsigned ConstructKind,
15423                             SourceRange ParenRange) {
15424   bool Elidable = false;
15425 
15426   // C++0x [class.copy]p34:
15427   //   When certain criteria are met, an implementation is allowed to
15428   //   omit the copy/move construction of a class object, even if the
15429   //   copy/move constructor and/or destructor for the object have
15430   //   side effects. [...]
15431   //     - when a temporary class object that has not been bound to a
15432   //       reference (12.2) would be copied/moved to a class object
15433   //       with the same cv-unqualified type, the copy/move operation
15434   //       can be omitted by constructing the temporary object
15435   //       directly into the target of the omitted copy/move
15436   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15437       // FIXME: Converting constructors should also be accepted.
15438       // But to fix this, the logic that digs down into a CXXConstructExpr
15439       // to find the source object needs to handle it.
15440       // Right now it assumes the source object is passed directly as the
15441       // first argument.
15442       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15443     Expr *SubExpr = ExprArgs[0];
15444     // FIXME: Per above, this is also incorrect if we want to accept
15445     //        converting constructors, as isTemporaryObject will
15446     //        reject temporaries with different type from the
15447     //        CXXRecord itself.
15448     Elidable = SubExpr->isTemporaryObject(
15449         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15450   }
15451 
15452   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15453                                FoundDecl, Constructor,
15454                                Elidable, ExprArgs, HadMultipleCandidates,
15455                                IsListInitialization,
15456                                IsStdInitListInitialization, RequiresZeroInit,
15457                                ConstructKind, ParenRange);
15458 }
15459 
15460 ExprResult
15461 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15462                             NamedDecl *FoundDecl,
15463                             CXXConstructorDecl *Constructor,
15464                             bool Elidable,
15465                             MultiExprArg ExprArgs,
15466                             bool HadMultipleCandidates,
15467                             bool IsListInitialization,
15468                             bool IsStdInitListInitialization,
15469                             bool RequiresZeroInit,
15470                             unsigned ConstructKind,
15471                             SourceRange ParenRange) {
15472   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15473     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15474     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15475       return ExprError();
15476   }
15477 
15478   return BuildCXXConstructExpr(
15479       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15480       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15481       RequiresZeroInit, ConstructKind, ParenRange);
15482 }
15483 
15484 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15485 /// including handling of its default argument expressions.
15486 ExprResult
15487 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15488                             CXXConstructorDecl *Constructor,
15489                             bool Elidable,
15490                             MultiExprArg ExprArgs,
15491                             bool HadMultipleCandidates,
15492                             bool IsListInitialization,
15493                             bool IsStdInitListInitialization,
15494                             bool RequiresZeroInit,
15495                             unsigned ConstructKind,
15496                             SourceRange ParenRange) {
15497   assert(declaresSameEntity(
15498              Constructor->getParent(),
15499              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15500          "given constructor for wrong type");
15501   MarkFunctionReferenced(ConstructLoc, Constructor);
15502   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15503     return ExprError();
15504   if (getLangOpts().SYCLIsDevice &&
15505       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15506     return ExprError();
15507 
15508   return CheckForImmediateInvocation(
15509       CXXConstructExpr::Create(
15510           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15511           HadMultipleCandidates, IsListInitialization,
15512           IsStdInitListInitialization, RequiresZeroInit,
15513           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15514           ParenRange),
15515       Constructor);
15516 }
15517 
15518 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15519   assert(Field->hasInClassInitializer());
15520 
15521   // If we already have the in-class initializer nothing needs to be done.
15522   if (Field->getInClassInitializer())
15523     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15524 
15525   // If we might have already tried and failed to instantiate, don't try again.
15526   if (Field->isInvalidDecl())
15527     return ExprError();
15528 
15529   // Maybe we haven't instantiated the in-class initializer. Go check the
15530   // pattern FieldDecl to see if it has one.
15531   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15532 
15533   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15534     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15535     DeclContext::lookup_result Lookup =
15536         ClassPattern->lookup(Field->getDeclName());
15537 
15538     FieldDecl *Pattern = nullptr;
15539     for (auto L : Lookup) {
15540       if (isa<FieldDecl>(L)) {
15541         Pattern = cast<FieldDecl>(L);
15542         break;
15543       }
15544     }
15545     assert(Pattern && "We must have set the Pattern!");
15546 
15547     if (!Pattern->hasInClassInitializer() ||
15548         InstantiateInClassInitializer(Loc, Field, Pattern,
15549                                       getTemplateInstantiationArgs(Field))) {
15550       // Don't diagnose this again.
15551       Field->setInvalidDecl();
15552       return ExprError();
15553     }
15554     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15555   }
15556 
15557   // DR1351:
15558   //   If the brace-or-equal-initializer of a non-static data member
15559   //   invokes a defaulted default constructor of its class or of an
15560   //   enclosing class in a potentially evaluated subexpression, the
15561   //   program is ill-formed.
15562   //
15563   // This resolution is unworkable: the exception specification of the
15564   // default constructor can be needed in an unevaluated context, in
15565   // particular, in the operand of a noexcept-expression, and we can be
15566   // unable to compute an exception specification for an enclosed class.
15567   //
15568   // Any attempt to resolve the exception specification of a defaulted default
15569   // constructor before the initializer is lexically complete will ultimately
15570   // come here at which point we can diagnose it.
15571   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15572   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15573       << OutermostClass << Field;
15574   Diag(Field->getEndLoc(),
15575        diag::note_default_member_initializer_not_yet_parsed);
15576   // Recover by marking the field invalid, unless we're in a SFINAE context.
15577   if (!isSFINAEContext())
15578     Field->setInvalidDecl();
15579   return ExprError();
15580 }
15581 
15582 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15583   if (VD->isInvalidDecl()) return;
15584   // If initializing the variable failed, don't also diagnose problems with
15585   // the destructor, they're likely related.
15586   if (VD->getInit() && VD->getInit()->containsErrors())
15587     return;
15588 
15589   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15590   if (ClassDecl->isInvalidDecl()) return;
15591   if (ClassDecl->hasIrrelevantDestructor()) return;
15592   if (ClassDecl->isDependentContext()) return;
15593 
15594   if (VD->isNoDestroy(getASTContext()))
15595     return;
15596 
15597   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15598 
15599   // If this is an array, we'll require the destructor during initialization, so
15600   // we can skip over this. We still want to emit exit-time destructor warnings
15601   // though.
15602   if (!VD->getType()->isArrayType()) {
15603     MarkFunctionReferenced(VD->getLocation(), Destructor);
15604     CheckDestructorAccess(VD->getLocation(), Destructor,
15605                           PDiag(diag::err_access_dtor_var)
15606                               << VD->getDeclName() << VD->getType());
15607     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15608   }
15609 
15610   if (Destructor->isTrivial()) return;
15611 
15612   // If the destructor is constexpr, check whether the variable has constant
15613   // destruction now.
15614   if (Destructor->isConstexpr()) {
15615     bool HasConstantInit = false;
15616     if (VD->getInit() && !VD->getInit()->isValueDependent())
15617       HasConstantInit = VD->evaluateValue();
15618     SmallVector<PartialDiagnosticAt, 8> Notes;
15619     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15620         HasConstantInit) {
15621       Diag(VD->getLocation(),
15622            diag::err_constexpr_var_requires_const_destruction) << VD;
15623       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15624         Diag(Notes[I].first, Notes[I].second);
15625     }
15626   }
15627 
15628   if (!VD->hasGlobalStorage()) return;
15629 
15630   // Emit warning for non-trivial dtor in global scope (a real global,
15631   // class-static, function-static).
15632   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15633 
15634   // TODO: this should be re-enabled for static locals by !CXAAtExit
15635   if (!VD->isStaticLocal())
15636     Diag(VD->getLocation(), diag::warn_global_destructor);
15637 }
15638 
15639 /// Given a constructor and the set of arguments provided for the
15640 /// constructor, convert the arguments and add any required default arguments
15641 /// to form a proper call to this constructor.
15642 ///
15643 /// \returns true if an error occurred, false otherwise.
15644 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15645                                    QualType DeclInitType, MultiExprArg ArgsPtr,
15646                                    SourceLocation Loc,
15647                                    SmallVectorImpl<Expr *> &ConvertedArgs,
15648                                    bool AllowExplicit,
15649                                    bool IsListInitialization) {
15650   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15651   unsigned NumArgs = ArgsPtr.size();
15652   Expr **Args = ArgsPtr.data();
15653 
15654   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15655   unsigned NumParams = Proto->getNumParams();
15656 
15657   // If too few arguments are available, we'll fill in the rest with defaults.
15658   if (NumArgs < NumParams)
15659     ConvertedArgs.reserve(NumParams);
15660   else
15661     ConvertedArgs.reserve(NumArgs);
15662 
15663   VariadicCallType CallType =
15664     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15665   SmallVector<Expr *, 8> AllArgs;
15666   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15667                                         Proto, 0,
15668                                         llvm::makeArrayRef(Args, NumArgs),
15669                                         AllArgs,
15670                                         CallType, AllowExplicit,
15671                                         IsListInitialization);
15672   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15673 
15674   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15675 
15676   CheckConstructorCall(Constructor, DeclInitType,
15677                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15678                        Proto, Loc);
15679 
15680   return Invalid;
15681 }
15682 
15683 static inline bool
15684 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15685                                        const FunctionDecl *FnDecl) {
15686   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15687   if (isa<NamespaceDecl>(DC)) {
15688     return SemaRef.Diag(FnDecl->getLocation(),
15689                         diag::err_operator_new_delete_declared_in_namespace)
15690       << FnDecl->getDeclName();
15691   }
15692 
15693   if (isa<TranslationUnitDecl>(DC) &&
15694       FnDecl->getStorageClass() == SC_Static) {
15695     return SemaRef.Diag(FnDecl->getLocation(),
15696                         diag::err_operator_new_delete_declared_static)
15697       << FnDecl->getDeclName();
15698   }
15699 
15700   return false;
15701 }
15702 
15703 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15704                                              const PointerType *PtrTy) {
15705   auto &Ctx = SemaRef.Context;
15706   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15707   PtrQuals.removeAddressSpace();
15708   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15709       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15710 }
15711 
15712 static inline bool
15713 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15714                             CanQualType ExpectedResultType,
15715                             CanQualType ExpectedFirstParamType,
15716                             unsigned DependentParamTypeDiag,
15717                             unsigned InvalidParamTypeDiag) {
15718   QualType ResultType =
15719       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15720 
15721   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15722     // The operator is valid on any address space for OpenCL.
15723     // Drop address space from actual and expected result types.
15724     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15725       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15726 
15727     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15728       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15729   }
15730 
15731   // Check that the result type is what we expect.
15732   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15733     // Reject even if the type is dependent; an operator delete function is
15734     // required to have a non-dependent result type.
15735     return SemaRef.Diag(
15736                FnDecl->getLocation(),
15737                ResultType->isDependentType()
15738                    ? diag::err_operator_new_delete_dependent_result_type
15739                    : diag::err_operator_new_delete_invalid_result_type)
15740            << FnDecl->getDeclName() << ExpectedResultType;
15741   }
15742 
15743   // A function template must have at least 2 parameters.
15744   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15745     return SemaRef.Diag(FnDecl->getLocation(),
15746                       diag::err_operator_new_delete_template_too_few_parameters)
15747         << FnDecl->getDeclName();
15748 
15749   // The function decl must have at least 1 parameter.
15750   if (FnDecl->getNumParams() == 0)
15751     return SemaRef.Diag(FnDecl->getLocation(),
15752                         diag::err_operator_new_delete_too_few_parameters)
15753       << FnDecl->getDeclName();
15754 
15755   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15756   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15757     // The operator is valid on any address space for OpenCL.
15758     // Drop address space from actual and expected first parameter types.
15759     if (const auto *PtrTy =
15760             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15761       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15762 
15763     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15764       ExpectedFirstParamType =
15765           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15766   }
15767 
15768   // Check that the first parameter type is what we expect.
15769   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15770       ExpectedFirstParamType) {
15771     // The first parameter type is not allowed to be dependent. As a tentative
15772     // DR resolution, we allow a dependent parameter type if it is the right
15773     // type anyway, to allow destroying operator delete in class templates.
15774     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15775                                                    ? DependentParamTypeDiag
15776                                                    : InvalidParamTypeDiag)
15777            << FnDecl->getDeclName() << ExpectedFirstParamType;
15778   }
15779 
15780   return false;
15781 }
15782 
15783 static bool
15784 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15785   // C++ [basic.stc.dynamic.allocation]p1:
15786   //   A program is ill-formed if an allocation function is declared in a
15787   //   namespace scope other than global scope or declared static in global
15788   //   scope.
15789   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15790     return true;
15791 
15792   CanQualType SizeTy =
15793     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15794 
15795   // C++ [basic.stc.dynamic.allocation]p1:
15796   //  The return type shall be void*. The first parameter shall have type
15797   //  std::size_t.
15798   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15799                                   SizeTy,
15800                                   diag::err_operator_new_dependent_param_type,
15801                                   diag::err_operator_new_param_type))
15802     return true;
15803 
15804   // C++ [basic.stc.dynamic.allocation]p1:
15805   //  The first parameter shall not have an associated default argument.
15806   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15807     return SemaRef.Diag(FnDecl->getLocation(),
15808                         diag::err_operator_new_default_arg)
15809       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15810 
15811   return false;
15812 }
15813 
15814 static bool
15815 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15816   // C++ [basic.stc.dynamic.deallocation]p1:
15817   //   A program is ill-formed if deallocation functions are declared in a
15818   //   namespace scope other than global scope or declared static in global
15819   //   scope.
15820   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15821     return true;
15822 
15823   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15824 
15825   // C++ P0722:
15826   //   Within a class C, the first parameter of a destroying operator delete
15827   //   shall be of type C *. The first parameter of any other deallocation
15828   //   function shall be of type void *.
15829   CanQualType ExpectedFirstParamType =
15830       MD && MD->isDestroyingOperatorDelete()
15831           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15832                 SemaRef.Context.getRecordType(MD->getParent())))
15833           : SemaRef.Context.VoidPtrTy;
15834 
15835   // C++ [basic.stc.dynamic.deallocation]p2:
15836   //   Each deallocation function shall return void
15837   if (CheckOperatorNewDeleteTypes(
15838           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15839           diag::err_operator_delete_dependent_param_type,
15840           diag::err_operator_delete_param_type))
15841     return true;
15842 
15843   // C++ P0722:
15844   //   A destroying operator delete shall be a usual deallocation function.
15845   if (MD && !MD->getParent()->isDependentContext() &&
15846       MD->isDestroyingOperatorDelete() &&
15847       !SemaRef.isUsualDeallocationFunction(MD)) {
15848     SemaRef.Diag(MD->getLocation(),
15849                  diag::err_destroying_operator_delete_not_usual);
15850     return true;
15851   }
15852 
15853   return false;
15854 }
15855 
15856 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15857 /// of this overloaded operator is well-formed. If so, returns false;
15858 /// otherwise, emits appropriate diagnostics and returns true.
15859 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15860   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15861          "Expected an overloaded operator declaration");
15862 
15863   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15864 
15865   // C++ [over.oper]p5:
15866   //   The allocation and deallocation functions, operator new,
15867   //   operator new[], operator delete and operator delete[], are
15868   //   described completely in 3.7.3. The attributes and restrictions
15869   //   found in the rest of this subclause do not apply to them unless
15870   //   explicitly stated in 3.7.3.
15871   if (Op == OO_Delete || Op == OO_Array_Delete)
15872     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15873 
15874   if (Op == OO_New || Op == OO_Array_New)
15875     return CheckOperatorNewDeclaration(*this, FnDecl);
15876 
15877   // C++ [over.oper]p6:
15878   //   An operator function shall either be a non-static member
15879   //   function or be a non-member function and have at least one
15880   //   parameter whose type is a class, a reference to a class, an
15881   //   enumeration, or a reference to an enumeration.
15882   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15883     if (MethodDecl->isStatic())
15884       return Diag(FnDecl->getLocation(),
15885                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15886   } else {
15887     bool ClassOrEnumParam = false;
15888     for (auto Param : FnDecl->parameters()) {
15889       QualType ParamType = Param->getType().getNonReferenceType();
15890       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15891           ParamType->isEnumeralType()) {
15892         ClassOrEnumParam = true;
15893         break;
15894       }
15895     }
15896 
15897     if (!ClassOrEnumParam)
15898       return Diag(FnDecl->getLocation(),
15899                   diag::err_operator_overload_needs_class_or_enum)
15900         << FnDecl->getDeclName();
15901   }
15902 
15903   // C++ [over.oper]p8:
15904   //   An operator function cannot have default arguments (8.3.6),
15905   //   except where explicitly stated below.
15906   //
15907   // Only the function-call operator (C++ [over.call]p1) and the subscript
15908   // operator (CWG2507) allow default arguments.
15909   if (Op != OO_Call) {
15910     ParmVarDecl *FirstDefaultedParam = nullptr;
15911     for (auto Param : FnDecl->parameters()) {
15912       if (Param->hasDefaultArg()) {
15913         FirstDefaultedParam = Param;
15914         break;
15915       }
15916     }
15917     if (FirstDefaultedParam) {
15918       if (Op == OO_Subscript) {
15919         Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15920                                         ? diag::ext_subscript_overload
15921                                         : diag::error_subscript_overload)
15922             << FnDecl->getDeclName() << 1
15923             << FirstDefaultedParam->getDefaultArgRange();
15924       } else {
15925         return Diag(FirstDefaultedParam->getLocation(),
15926                     diag::err_operator_overload_default_arg)
15927                << FnDecl->getDeclName()
15928                << FirstDefaultedParam->getDefaultArgRange();
15929       }
15930     }
15931   }
15932 
15933   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15934     { false, false, false }
15935 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15936     , { Unary, Binary, MemberOnly }
15937 #include "clang/Basic/OperatorKinds.def"
15938   };
15939 
15940   bool CanBeUnaryOperator = OperatorUses[Op][0];
15941   bool CanBeBinaryOperator = OperatorUses[Op][1];
15942   bool MustBeMemberOperator = OperatorUses[Op][2];
15943 
15944   // C++ [over.oper]p8:
15945   //   [...] Operator functions cannot have more or fewer parameters
15946   //   than the number required for the corresponding operator, as
15947   //   described in the rest of this subclause.
15948   unsigned NumParams = FnDecl->getNumParams()
15949                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15950   if (Op != OO_Call && Op != OO_Subscript &&
15951       ((NumParams == 1 && !CanBeUnaryOperator) ||
15952        (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
15953        (NumParams > 2))) {
15954     // We have the wrong number of parameters.
15955     unsigned ErrorKind;
15956     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15957       ErrorKind = 2;  // 2 -> unary or binary.
15958     } else if (CanBeUnaryOperator) {
15959       ErrorKind = 0;  // 0 -> unary
15960     } else {
15961       assert(CanBeBinaryOperator &&
15962              "All non-call overloaded operators are unary or binary!");
15963       ErrorKind = 1;  // 1 -> binary
15964     }
15965     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15966       << FnDecl->getDeclName() << NumParams << ErrorKind;
15967   }
15968 
15969   if (Op == OO_Subscript && NumParams != 2) {
15970     Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15971                                     ? diag::ext_subscript_overload
15972                                     : diag::error_subscript_overload)
15973         << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
15974   }
15975 
15976   // Overloaded operators other than operator() and operator[] cannot be
15977   // variadic.
15978   if (Op != OO_Call &&
15979       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15980     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15981            << FnDecl->getDeclName();
15982   }
15983 
15984   // Some operators must be non-static member functions.
15985   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15986     return Diag(FnDecl->getLocation(),
15987                 diag::err_operator_overload_must_be_member)
15988       << FnDecl->getDeclName();
15989   }
15990 
15991   // C++ [over.inc]p1:
15992   //   The user-defined function called operator++ implements the
15993   //   prefix and postfix ++ operator. If this function is a member
15994   //   function with no parameters, or a non-member function with one
15995   //   parameter of class or enumeration type, it defines the prefix
15996   //   increment operator ++ for objects of that type. If the function
15997   //   is a member function with one parameter (which shall be of type
15998   //   int) or a non-member function with two parameters (the second
15999   //   of which shall be of type int), it defines the postfix
16000   //   increment operator ++ for objects of that type.
16001   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16002     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16003     QualType ParamType = LastParam->getType();
16004 
16005     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16006         !ParamType->isDependentType())
16007       return Diag(LastParam->getLocation(),
16008                   diag::err_operator_overload_post_incdec_must_be_int)
16009         << LastParam->getType() << (Op == OO_MinusMinus);
16010   }
16011 
16012   return false;
16013 }
16014 
16015 static bool
16016 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16017                                           FunctionTemplateDecl *TpDecl) {
16018   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16019 
16020   // Must have one or two template parameters.
16021   if (TemplateParams->size() == 1) {
16022     NonTypeTemplateParmDecl *PmDecl =
16023         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16024 
16025     // The template parameter must be a char parameter pack.
16026     if (PmDecl && PmDecl->isTemplateParameterPack() &&
16027         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16028       return false;
16029 
16030     // C++20 [over.literal]p5:
16031     //   A string literal operator template is a literal operator template
16032     //   whose template-parameter-list comprises a single non-type
16033     //   template-parameter of class type.
16034     //
16035     // As a DR resolution, we also allow placeholders for deduced class
16036     // template specializations.
16037     if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16038         !PmDecl->isTemplateParameterPack() &&
16039         (PmDecl->getType()->isRecordType() ||
16040          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16041       return false;
16042   } else if (TemplateParams->size() == 2) {
16043     TemplateTypeParmDecl *PmType =
16044         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16045     NonTypeTemplateParmDecl *PmArgs =
16046         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16047 
16048     // The second template parameter must be a parameter pack with the
16049     // first template parameter as its type.
16050     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16051         PmArgs->isTemplateParameterPack()) {
16052       const TemplateTypeParmType *TArgs =
16053           PmArgs->getType()->getAs<TemplateTypeParmType>();
16054       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16055           TArgs->getIndex() == PmType->getIndex()) {
16056         if (!SemaRef.inTemplateInstantiation())
16057           SemaRef.Diag(TpDecl->getLocation(),
16058                        diag::ext_string_literal_operator_template);
16059         return false;
16060       }
16061     }
16062   }
16063 
16064   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16065                diag::err_literal_operator_template)
16066       << TpDecl->getTemplateParameters()->getSourceRange();
16067   return true;
16068 }
16069 
16070 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16071 /// of this literal operator function is well-formed. If so, returns
16072 /// false; otherwise, emits appropriate diagnostics and returns true.
16073 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16074   if (isa<CXXMethodDecl>(FnDecl)) {
16075     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16076       << FnDecl->getDeclName();
16077     return true;
16078   }
16079 
16080   if (FnDecl->isExternC()) {
16081     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16082     if (const LinkageSpecDecl *LSD =
16083             FnDecl->getDeclContext()->getExternCContext())
16084       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16085     return true;
16086   }
16087 
16088   // This might be the definition of a literal operator template.
16089   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16090 
16091   // This might be a specialization of a literal operator template.
16092   if (!TpDecl)
16093     TpDecl = FnDecl->getPrimaryTemplate();
16094 
16095   // template <char...> type operator "" name() and
16096   // template <class T, T...> type operator "" name() are the only valid
16097   // template signatures, and the only valid signatures with no parameters.
16098   //
16099   // C++20 also allows template <SomeClass T> type operator "" name().
16100   if (TpDecl) {
16101     if (FnDecl->param_size() != 0) {
16102       Diag(FnDecl->getLocation(),
16103            diag::err_literal_operator_template_with_params);
16104       return true;
16105     }
16106 
16107     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16108       return true;
16109 
16110   } else if (FnDecl->param_size() == 1) {
16111     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16112 
16113     QualType ParamType = Param->getType().getUnqualifiedType();
16114 
16115     // Only unsigned long long int, long double, any character type, and const
16116     // char * are allowed as the only parameters.
16117     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16118         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16119         Context.hasSameType(ParamType, Context.CharTy) ||
16120         Context.hasSameType(ParamType, Context.WideCharTy) ||
16121         Context.hasSameType(ParamType, Context.Char8Ty) ||
16122         Context.hasSameType(ParamType, Context.Char16Ty) ||
16123         Context.hasSameType(ParamType, Context.Char32Ty)) {
16124     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16125       QualType InnerType = Ptr->getPointeeType();
16126 
16127       // Pointer parameter must be a const char *.
16128       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16129                                 Context.CharTy) &&
16130             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16131         Diag(Param->getSourceRange().getBegin(),
16132              diag::err_literal_operator_param)
16133             << ParamType << "'const char *'" << Param->getSourceRange();
16134         return true;
16135       }
16136 
16137     } else if (ParamType->isRealFloatingType()) {
16138       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16139           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16140       return true;
16141 
16142     } else if (ParamType->isIntegerType()) {
16143       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16144           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16145       return true;
16146 
16147     } else {
16148       Diag(Param->getSourceRange().getBegin(),
16149            diag::err_literal_operator_invalid_param)
16150           << ParamType << Param->getSourceRange();
16151       return true;
16152     }
16153 
16154   } else if (FnDecl->param_size() == 2) {
16155     FunctionDecl::param_iterator Param = FnDecl->param_begin();
16156 
16157     // First, verify that the first parameter is correct.
16158 
16159     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16160 
16161     // Two parameter function must have a pointer to const as a
16162     // first parameter; let's strip those qualifiers.
16163     const PointerType *PT = FirstParamType->getAs<PointerType>();
16164 
16165     if (!PT) {
16166       Diag((*Param)->getSourceRange().getBegin(),
16167            diag::err_literal_operator_param)
16168           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16169       return true;
16170     }
16171 
16172     QualType PointeeType = PT->getPointeeType();
16173     // First parameter must be const
16174     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16175       Diag((*Param)->getSourceRange().getBegin(),
16176            diag::err_literal_operator_param)
16177           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16178       return true;
16179     }
16180 
16181     QualType InnerType = PointeeType.getUnqualifiedType();
16182     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16183     // const char32_t* are allowed as the first parameter to a two-parameter
16184     // function
16185     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16186           Context.hasSameType(InnerType, Context.WideCharTy) ||
16187           Context.hasSameType(InnerType, Context.Char8Ty) ||
16188           Context.hasSameType(InnerType, Context.Char16Ty) ||
16189           Context.hasSameType(InnerType, Context.Char32Ty))) {
16190       Diag((*Param)->getSourceRange().getBegin(),
16191            diag::err_literal_operator_param)
16192           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16193       return true;
16194     }
16195 
16196     // Move on to the second and final parameter.
16197     ++Param;
16198 
16199     // The second parameter must be a std::size_t.
16200     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16201     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16202       Diag((*Param)->getSourceRange().getBegin(),
16203            diag::err_literal_operator_param)
16204           << SecondParamType << Context.getSizeType()
16205           << (*Param)->getSourceRange();
16206       return true;
16207     }
16208   } else {
16209     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16210     return true;
16211   }
16212 
16213   // Parameters are good.
16214 
16215   // A parameter-declaration-clause containing a default argument is not
16216   // equivalent to any of the permitted forms.
16217   for (auto Param : FnDecl->parameters()) {
16218     if (Param->hasDefaultArg()) {
16219       Diag(Param->getDefaultArgRange().getBegin(),
16220            diag::err_literal_operator_default_argument)
16221         << Param->getDefaultArgRange();
16222       break;
16223     }
16224   }
16225 
16226   StringRef LiteralName
16227     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16228   if (LiteralName[0] != '_' &&
16229       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16230     // C++11 [usrlit.suffix]p1:
16231     //   Literal suffix identifiers that do not start with an underscore
16232     //   are reserved for future standardization.
16233     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16234       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16235   }
16236 
16237   return false;
16238 }
16239 
16240 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16241 /// linkage specification, including the language and (if present)
16242 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16243 /// language string literal. LBraceLoc, if valid, provides the location of
16244 /// the '{' brace. Otherwise, this linkage specification does not
16245 /// have any braces.
16246 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16247                                            Expr *LangStr,
16248                                            SourceLocation LBraceLoc) {
16249   StringLiteral *Lit = cast<StringLiteral>(LangStr);
16250   if (!Lit->isAscii()) {
16251     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16252       << LangStr->getSourceRange();
16253     return nullptr;
16254   }
16255 
16256   StringRef Lang = Lit->getString();
16257   LinkageSpecDecl::LanguageIDs Language;
16258   if (Lang == "C")
16259     Language = LinkageSpecDecl::lang_c;
16260   else if (Lang == "C++")
16261     Language = LinkageSpecDecl::lang_cxx;
16262   else {
16263     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16264       << LangStr->getSourceRange();
16265     return nullptr;
16266   }
16267 
16268   // FIXME: Add all the various semantics of linkage specifications
16269 
16270   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16271                                                LangStr->getExprLoc(), Language,
16272                                                LBraceLoc.isValid());
16273 
16274   /// C++ [module.unit]p7.2.3
16275   /// - Otherwise, if the declaration
16276   ///   - ...
16277   ///   - ...
16278   ///   - appears within a linkage-specification,
16279   ///   it is attached to the global module.
16280   ///
16281   /// If the declaration is already in global module fragment, we don't
16282   /// need to attach it again.
16283   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16284     Module *GlobalModule =
16285         PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
16286     D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16287     D->setLocalOwningModule(GlobalModule);
16288   }
16289 
16290   CurContext->addDecl(D);
16291   PushDeclContext(S, D);
16292   return D;
16293 }
16294 
16295 /// ActOnFinishLinkageSpecification - Complete the definition of
16296 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16297 /// valid, it's the position of the closing '}' brace in a linkage
16298 /// specification that uses braces.
16299 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16300                                             Decl *LinkageSpec,
16301                                             SourceLocation RBraceLoc) {
16302   if (RBraceLoc.isValid()) {
16303     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16304     LSDecl->setRBraceLoc(RBraceLoc);
16305   }
16306 
16307   // If the current module doesn't has Parent, it implies that the
16308   // LinkageSpec isn't in the module created by itself. So we don't
16309   // need to pop it.
16310   if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16311       getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
16312     PopGlobalModuleFragment();
16313 
16314   PopDeclContext();
16315   return LinkageSpec;
16316 }
16317 
16318 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16319                                   const ParsedAttributesView &AttrList,
16320                                   SourceLocation SemiLoc) {
16321   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16322   // Attribute declarations appertain to empty declaration so we handle
16323   // them here.
16324   ProcessDeclAttributeList(S, ED, AttrList);
16325 
16326   CurContext->addDecl(ED);
16327   return ED;
16328 }
16329 
16330 /// Perform semantic analysis for the variable declaration that
16331 /// occurs within a C++ catch clause, returning the newly-created
16332 /// variable.
16333 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16334                                          TypeSourceInfo *TInfo,
16335                                          SourceLocation StartLoc,
16336                                          SourceLocation Loc,
16337                                          IdentifierInfo *Name) {
16338   bool Invalid = false;
16339   QualType ExDeclType = TInfo->getType();
16340 
16341   // Arrays and functions decay.
16342   if (ExDeclType->isArrayType())
16343     ExDeclType = Context.getArrayDecayedType(ExDeclType);
16344   else if (ExDeclType->isFunctionType())
16345     ExDeclType = Context.getPointerType(ExDeclType);
16346 
16347   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16348   // The exception-declaration shall not denote a pointer or reference to an
16349   // incomplete type, other than [cv] void*.
16350   // N2844 forbids rvalue references.
16351   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16352     Diag(Loc, diag::err_catch_rvalue_ref);
16353     Invalid = true;
16354   }
16355 
16356   if (ExDeclType->isVariablyModifiedType()) {
16357     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16358     Invalid = true;
16359   }
16360 
16361   QualType BaseType = ExDeclType;
16362   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16363   unsigned DK = diag::err_catch_incomplete;
16364   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16365     BaseType = Ptr->getPointeeType();
16366     Mode = 1;
16367     DK = diag::err_catch_incomplete_ptr;
16368   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16369     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16370     BaseType = Ref->getPointeeType();
16371     Mode = 2;
16372     DK = diag::err_catch_incomplete_ref;
16373   }
16374   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16375       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16376     Invalid = true;
16377 
16378   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16379     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16380     Invalid = true;
16381   }
16382 
16383   if (!Invalid && !ExDeclType->isDependentType() &&
16384       RequireNonAbstractType(Loc, ExDeclType,
16385                              diag::err_abstract_type_in_decl,
16386                              AbstractVariableType))
16387     Invalid = true;
16388 
16389   // Only the non-fragile NeXT runtime currently supports C++ catches
16390   // of ObjC types, and no runtime supports catching ObjC types by value.
16391   if (!Invalid && getLangOpts().ObjC) {
16392     QualType T = ExDeclType;
16393     if (const ReferenceType *RT = T->getAs<ReferenceType>())
16394       T = RT->getPointeeType();
16395 
16396     if (T->isObjCObjectType()) {
16397       Diag(Loc, diag::err_objc_object_catch);
16398       Invalid = true;
16399     } else if (T->isObjCObjectPointerType()) {
16400       // FIXME: should this be a test for macosx-fragile specifically?
16401       if (getLangOpts().ObjCRuntime.isFragile())
16402         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16403     }
16404   }
16405 
16406   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16407                                     ExDeclType, TInfo, SC_None);
16408   ExDecl->setExceptionVariable(true);
16409 
16410   // In ARC, infer 'retaining' for variables of retainable type.
16411   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16412     Invalid = true;
16413 
16414   if (!Invalid && !ExDeclType->isDependentType()) {
16415     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16416       // Insulate this from anything else we might currently be parsing.
16417       EnterExpressionEvaluationContext scope(
16418           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16419 
16420       // C++ [except.handle]p16:
16421       //   The object declared in an exception-declaration or, if the
16422       //   exception-declaration does not specify a name, a temporary (12.2) is
16423       //   copy-initialized (8.5) from the exception object. [...]
16424       //   The object is destroyed when the handler exits, after the destruction
16425       //   of any automatic objects initialized within the handler.
16426       //
16427       // We just pretend to initialize the object with itself, then make sure
16428       // it can be destroyed later.
16429       QualType initType = Context.getExceptionObjectType(ExDeclType);
16430 
16431       InitializedEntity entity =
16432         InitializedEntity::InitializeVariable(ExDecl);
16433       InitializationKind initKind =
16434         InitializationKind::CreateCopy(Loc, SourceLocation());
16435 
16436       Expr *opaqueValue =
16437         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16438       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16439       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16440       if (result.isInvalid())
16441         Invalid = true;
16442       else {
16443         // If the constructor used was non-trivial, set this as the
16444         // "initializer".
16445         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16446         if (!construct->getConstructor()->isTrivial()) {
16447           Expr *init = MaybeCreateExprWithCleanups(construct);
16448           ExDecl->setInit(init);
16449         }
16450 
16451         // And make sure it's destructable.
16452         FinalizeVarWithDestructor(ExDecl, recordType);
16453       }
16454     }
16455   }
16456 
16457   if (Invalid)
16458     ExDecl->setInvalidDecl();
16459 
16460   return ExDecl;
16461 }
16462 
16463 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16464 /// handler.
16465 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16466   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16467   bool Invalid = D.isInvalidType();
16468 
16469   // Check for unexpanded parameter packs.
16470   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16471                                       UPPC_ExceptionType)) {
16472     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16473                                              D.getIdentifierLoc());
16474     Invalid = true;
16475   }
16476 
16477   IdentifierInfo *II = D.getIdentifier();
16478   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16479                                              LookupOrdinaryName,
16480                                              ForVisibleRedeclaration)) {
16481     // The scope should be freshly made just for us. There is just no way
16482     // it contains any previous declaration, except for function parameters in
16483     // a function-try-block's catch statement.
16484     assert(!S->isDeclScope(PrevDecl));
16485     if (isDeclInScope(PrevDecl, CurContext, S)) {
16486       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16487         << D.getIdentifier();
16488       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16489       Invalid = true;
16490     } else if (PrevDecl->isTemplateParameter())
16491       // Maybe we will complain about the shadowed template parameter.
16492       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16493   }
16494 
16495   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16496     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16497       << D.getCXXScopeSpec().getRange();
16498     Invalid = true;
16499   }
16500 
16501   VarDecl *ExDecl = BuildExceptionDeclaration(
16502       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16503   if (Invalid)
16504     ExDecl->setInvalidDecl();
16505 
16506   // Add the exception declaration into this scope.
16507   if (II)
16508     PushOnScopeChains(ExDecl, S);
16509   else
16510     CurContext->addDecl(ExDecl);
16511 
16512   ProcessDeclAttributes(S, ExDecl, D);
16513   return ExDecl;
16514 }
16515 
16516 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16517                                          Expr *AssertExpr,
16518                                          Expr *AssertMessageExpr,
16519                                          SourceLocation RParenLoc) {
16520   StringLiteral *AssertMessage =
16521       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16522 
16523   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16524     return nullptr;
16525 
16526   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16527                                       AssertMessage, RParenLoc, false);
16528 }
16529 
16530 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16531                                          Expr *AssertExpr,
16532                                          StringLiteral *AssertMessage,
16533                                          SourceLocation RParenLoc,
16534                                          bool Failed) {
16535   assert(AssertExpr != nullptr && "Expected non-null condition");
16536   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16537       !Failed) {
16538     // In a static_assert-declaration, the constant-expression shall be a
16539     // constant expression that can be contextually converted to bool.
16540     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16541     if (Converted.isInvalid())
16542       Failed = true;
16543 
16544     ExprResult FullAssertExpr =
16545         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16546                             /*DiscardedValue*/ false,
16547                             /*IsConstexpr*/ true);
16548     if (FullAssertExpr.isInvalid())
16549       Failed = true;
16550     else
16551       AssertExpr = FullAssertExpr.get();
16552 
16553     llvm::APSInt Cond;
16554     if (!Failed && VerifyIntegerConstantExpression(
16555                        AssertExpr, &Cond,
16556                        diag::err_static_assert_expression_is_not_constant)
16557                        .isInvalid())
16558       Failed = true;
16559 
16560     if (!Failed && !Cond) {
16561       SmallString<256> MsgBuffer;
16562       llvm::raw_svector_ostream Msg(MsgBuffer);
16563       if (AssertMessage)
16564         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16565 
16566       Expr *InnerCond = nullptr;
16567       std::string InnerCondDescription;
16568       std::tie(InnerCond, InnerCondDescription) =
16569         findFailedBooleanCondition(Converted.get());
16570       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16571         // Drill down into concept specialization expressions to see why they
16572         // weren't satisfied.
16573         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16574           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16575         ConstraintSatisfaction Satisfaction;
16576         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16577           DiagnoseUnsatisfiedConstraint(Satisfaction);
16578       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16579                            && !isa<IntegerLiteral>(InnerCond)) {
16580         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16581           << InnerCondDescription << !AssertMessage
16582           << Msg.str() << InnerCond->getSourceRange();
16583       } else {
16584         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16585           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16586       }
16587       Failed = true;
16588     }
16589   } else {
16590     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16591                                                     /*DiscardedValue*/false,
16592                                                     /*IsConstexpr*/true);
16593     if (FullAssertExpr.isInvalid())
16594       Failed = true;
16595     else
16596       AssertExpr = FullAssertExpr.get();
16597   }
16598 
16599   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16600                                         AssertExpr, AssertMessage, RParenLoc,
16601                                         Failed);
16602 
16603   CurContext->addDecl(Decl);
16604   return Decl;
16605 }
16606 
16607 /// Perform semantic analysis of the given friend type declaration.
16608 ///
16609 /// \returns A friend declaration that.
16610 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16611                                       SourceLocation FriendLoc,
16612                                       TypeSourceInfo *TSInfo) {
16613   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16614 
16615   QualType T = TSInfo->getType();
16616   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16617 
16618   // C++03 [class.friend]p2:
16619   //   An elaborated-type-specifier shall be used in a friend declaration
16620   //   for a class.*
16621   //
16622   //   * The class-key of the elaborated-type-specifier is required.
16623   if (!CodeSynthesisContexts.empty()) {
16624     // Do not complain about the form of friend template types during any kind
16625     // of code synthesis. For template instantiation, we will have complained
16626     // when the template was defined.
16627   } else {
16628     if (!T->isElaboratedTypeSpecifier()) {
16629       // If we evaluated the type to a record type, suggest putting
16630       // a tag in front.
16631       if (const RecordType *RT = T->getAs<RecordType>()) {
16632         RecordDecl *RD = RT->getDecl();
16633 
16634         SmallString<16> InsertionText(" ");
16635         InsertionText += RD->getKindName();
16636 
16637         Diag(TypeRange.getBegin(),
16638              getLangOpts().CPlusPlus11 ?
16639                diag::warn_cxx98_compat_unelaborated_friend_type :
16640                diag::ext_unelaborated_friend_type)
16641           << (unsigned) RD->getTagKind()
16642           << T
16643           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16644                                         InsertionText);
16645       } else {
16646         Diag(FriendLoc,
16647              getLangOpts().CPlusPlus11 ?
16648                diag::warn_cxx98_compat_nonclass_type_friend :
16649                diag::ext_nonclass_type_friend)
16650           << T
16651           << TypeRange;
16652       }
16653     } else if (T->getAs<EnumType>()) {
16654       Diag(FriendLoc,
16655            getLangOpts().CPlusPlus11 ?
16656              diag::warn_cxx98_compat_enum_friend :
16657              diag::ext_enum_friend)
16658         << T
16659         << TypeRange;
16660     }
16661 
16662     // C++11 [class.friend]p3:
16663     //   A friend declaration that does not declare a function shall have one
16664     //   of the following forms:
16665     //     friend elaborated-type-specifier ;
16666     //     friend simple-type-specifier ;
16667     //     friend typename-specifier ;
16668     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16669       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16670   }
16671 
16672   //   If the type specifier in a friend declaration designates a (possibly
16673   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16674   //   the friend declaration is ignored.
16675   return FriendDecl::Create(Context, CurContext,
16676                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16677                             FriendLoc);
16678 }
16679 
16680 /// Handle a friend tag declaration where the scope specifier was
16681 /// templated.
16682 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16683                                     unsigned TagSpec, SourceLocation TagLoc,
16684                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16685                                     SourceLocation NameLoc,
16686                                     const ParsedAttributesView &Attr,
16687                                     MultiTemplateParamsArg TempParamLists) {
16688   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16689 
16690   bool IsMemberSpecialization = false;
16691   bool Invalid = false;
16692 
16693   if (TemplateParameterList *TemplateParams =
16694           MatchTemplateParametersToScopeSpecifier(
16695               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16696               IsMemberSpecialization, Invalid)) {
16697     if (TemplateParams->size() > 0) {
16698       // This is a declaration of a class template.
16699       if (Invalid)
16700         return nullptr;
16701 
16702       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16703                                 NameLoc, Attr, TemplateParams, AS_public,
16704                                 /*ModulePrivateLoc=*/SourceLocation(),
16705                                 FriendLoc, TempParamLists.size() - 1,
16706                                 TempParamLists.data()).get();
16707     } else {
16708       // The "template<>" header is extraneous.
16709       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16710         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16711       IsMemberSpecialization = true;
16712     }
16713   }
16714 
16715   if (Invalid) return nullptr;
16716 
16717   bool isAllExplicitSpecializations = true;
16718   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16719     if (TempParamLists[I]->size()) {
16720       isAllExplicitSpecializations = false;
16721       break;
16722     }
16723   }
16724 
16725   // FIXME: don't ignore attributes.
16726 
16727   // If it's explicit specializations all the way down, just forget
16728   // about the template header and build an appropriate non-templated
16729   // friend.  TODO: for source fidelity, remember the headers.
16730   if (isAllExplicitSpecializations) {
16731     if (SS.isEmpty()) {
16732       bool Owned = false;
16733       bool IsDependent = false;
16734       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16735                       Attr, AS_public,
16736                       /*ModulePrivateLoc=*/SourceLocation(),
16737                       MultiTemplateParamsArg(), Owned, IsDependent,
16738                       /*ScopedEnumKWLoc=*/SourceLocation(),
16739                       /*ScopedEnumUsesClassTag=*/false,
16740                       /*UnderlyingType=*/TypeResult(),
16741                       /*IsTypeSpecifier=*/false,
16742                       /*IsTemplateParamOrArg=*/false);
16743     }
16744 
16745     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16746     ElaboratedTypeKeyword Keyword
16747       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16748     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16749                                    *Name, NameLoc);
16750     if (T.isNull())
16751       return nullptr;
16752 
16753     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16754     if (isa<DependentNameType>(T)) {
16755       DependentNameTypeLoc TL =
16756           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16757       TL.setElaboratedKeywordLoc(TagLoc);
16758       TL.setQualifierLoc(QualifierLoc);
16759       TL.setNameLoc(NameLoc);
16760     } else {
16761       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16762       TL.setElaboratedKeywordLoc(TagLoc);
16763       TL.setQualifierLoc(QualifierLoc);
16764       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16765     }
16766 
16767     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16768                                             TSI, FriendLoc, TempParamLists);
16769     Friend->setAccess(AS_public);
16770     CurContext->addDecl(Friend);
16771     return Friend;
16772   }
16773 
16774   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16775 
16776 
16777 
16778   // Handle the case of a templated-scope friend class.  e.g.
16779   //   template <class T> class A<T>::B;
16780   // FIXME: we don't support these right now.
16781   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16782     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16783   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16784   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16785   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16786   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16787   TL.setElaboratedKeywordLoc(TagLoc);
16788   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16789   TL.setNameLoc(NameLoc);
16790 
16791   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16792                                           TSI, FriendLoc, TempParamLists);
16793   Friend->setAccess(AS_public);
16794   Friend->setUnsupportedFriend(true);
16795   CurContext->addDecl(Friend);
16796   return Friend;
16797 }
16798 
16799 /// Handle a friend type declaration.  This works in tandem with
16800 /// ActOnTag.
16801 ///
16802 /// Notes on friend class templates:
16803 ///
16804 /// We generally treat friend class declarations as if they were
16805 /// declaring a class.  So, for example, the elaborated type specifier
16806 /// in a friend declaration is required to obey the restrictions of a
16807 /// class-head (i.e. no typedefs in the scope chain), template
16808 /// parameters are required to match up with simple template-ids, &c.
16809 /// However, unlike when declaring a template specialization, it's
16810 /// okay to refer to a template specialization without an empty
16811 /// template parameter declaration, e.g.
16812 ///   friend class A<T>::B<unsigned>;
16813 /// We permit this as a special case; if there are any template
16814 /// parameters present at all, require proper matching, i.e.
16815 ///   template <> template \<class T> friend class A<int>::B;
16816 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16817                                 MultiTemplateParamsArg TempParams) {
16818   SourceLocation Loc = DS.getBeginLoc();
16819 
16820   assert(DS.isFriendSpecified());
16821   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16822 
16823   // C++ [class.friend]p3:
16824   // A friend declaration that does not declare a function shall have one of
16825   // the following forms:
16826   //     friend elaborated-type-specifier ;
16827   //     friend simple-type-specifier ;
16828   //     friend typename-specifier ;
16829   //
16830   // Any declaration with a type qualifier does not have that form. (It's
16831   // legal to specify a qualified type as a friend, you just can't write the
16832   // keywords.)
16833   if (DS.getTypeQualifiers()) {
16834     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16835       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16836     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16837       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16838     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16839       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16840     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16841       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16842     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16843       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16844   }
16845 
16846   // Try to convert the decl specifier to a type.  This works for
16847   // friend templates because ActOnTag never produces a ClassTemplateDecl
16848   // for a TUK_Friend.
16849   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16850   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16851   QualType T = TSI->getType();
16852   if (TheDeclarator.isInvalidType())
16853     return nullptr;
16854 
16855   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16856     return nullptr;
16857 
16858   // This is definitely an error in C++98.  It's probably meant to
16859   // be forbidden in C++0x, too, but the specification is just
16860   // poorly written.
16861   //
16862   // The problem is with declarations like the following:
16863   //   template <T> friend A<T>::foo;
16864   // where deciding whether a class C is a friend or not now hinges
16865   // on whether there exists an instantiation of A that causes
16866   // 'foo' to equal C.  There are restrictions on class-heads
16867   // (which we declare (by fiat) elaborated friend declarations to
16868   // be) that makes this tractable.
16869   //
16870   // FIXME: handle "template <> friend class A<T>;", which
16871   // is possibly well-formed?  Who even knows?
16872   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16873     Diag(Loc, diag::err_tagless_friend_type_template)
16874       << DS.getSourceRange();
16875     return nullptr;
16876   }
16877 
16878   // C++98 [class.friend]p1: A friend of a class is a function
16879   //   or class that is not a member of the class . . .
16880   // This is fixed in DR77, which just barely didn't make the C++03
16881   // deadline.  It's also a very silly restriction that seriously
16882   // affects inner classes and which nobody else seems to implement;
16883   // thus we never diagnose it, not even in -pedantic.
16884   //
16885   // But note that we could warn about it: it's always useless to
16886   // friend one of your own members (it's not, however, worthless to
16887   // friend a member of an arbitrary specialization of your template).
16888 
16889   Decl *D;
16890   if (!TempParams.empty())
16891     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16892                                    TempParams,
16893                                    TSI,
16894                                    DS.getFriendSpecLoc());
16895   else
16896     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16897 
16898   if (!D)
16899     return nullptr;
16900 
16901   D->setAccess(AS_public);
16902   CurContext->addDecl(D);
16903 
16904   return D;
16905 }
16906 
16907 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16908                                         MultiTemplateParamsArg TemplateParams) {
16909   const DeclSpec &DS = D.getDeclSpec();
16910 
16911   assert(DS.isFriendSpecified());
16912   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16913 
16914   SourceLocation Loc = D.getIdentifierLoc();
16915   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16916 
16917   // C++ [class.friend]p1
16918   //   A friend of a class is a function or class....
16919   // Note that this sees through typedefs, which is intended.
16920   // It *doesn't* see through dependent types, which is correct
16921   // according to [temp.arg.type]p3:
16922   //   If a declaration acquires a function type through a
16923   //   type dependent on a template-parameter and this causes
16924   //   a declaration that does not use the syntactic form of a
16925   //   function declarator to have a function type, the program
16926   //   is ill-formed.
16927   if (!TInfo->getType()->isFunctionType()) {
16928     Diag(Loc, diag::err_unexpected_friend);
16929 
16930     // It might be worthwhile to try to recover by creating an
16931     // appropriate declaration.
16932     return nullptr;
16933   }
16934 
16935   // C++ [namespace.memdef]p3
16936   //  - If a friend declaration in a non-local class first declares a
16937   //    class or function, the friend class or function is a member
16938   //    of the innermost enclosing namespace.
16939   //  - The name of the friend is not found by simple name lookup
16940   //    until a matching declaration is provided in that namespace
16941   //    scope (either before or after the class declaration granting
16942   //    friendship).
16943   //  - If a friend function is called, its name may be found by the
16944   //    name lookup that considers functions from namespaces and
16945   //    classes associated with the types of the function arguments.
16946   //  - When looking for a prior declaration of a class or a function
16947   //    declared as a friend, scopes outside the innermost enclosing
16948   //    namespace scope are not considered.
16949 
16950   CXXScopeSpec &SS = D.getCXXScopeSpec();
16951   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16952   assert(NameInfo.getName());
16953 
16954   // Check for unexpanded parameter packs.
16955   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16956       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16957       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16958     return nullptr;
16959 
16960   // The context we found the declaration in, or in which we should
16961   // create the declaration.
16962   DeclContext *DC;
16963   Scope *DCScope = S;
16964   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16965                         ForExternalRedeclaration);
16966 
16967   // There are five cases here.
16968   //   - There's no scope specifier and we're in a local class. Only look
16969   //     for functions declared in the immediately-enclosing block scope.
16970   // We recover from invalid scope qualifiers as if they just weren't there.
16971   FunctionDecl *FunctionContainingLocalClass = nullptr;
16972   if ((SS.isInvalid() || !SS.isSet()) &&
16973       (FunctionContainingLocalClass =
16974            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16975     // C++11 [class.friend]p11:
16976     //   If a friend declaration appears in a local class and the name
16977     //   specified is an unqualified name, a prior declaration is
16978     //   looked up without considering scopes that are outside the
16979     //   innermost enclosing non-class scope. For a friend function
16980     //   declaration, if there is no prior declaration, the program is
16981     //   ill-formed.
16982 
16983     // Find the innermost enclosing non-class scope. This is the block
16984     // scope containing the local class definition (or for a nested class,
16985     // the outer local class).
16986     DCScope = S->getFnParent();
16987 
16988     // Look up the function name in the scope.
16989     Previous.clear(LookupLocalFriendName);
16990     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16991 
16992     if (!Previous.empty()) {
16993       // All possible previous declarations must have the same context:
16994       // either they were declared at block scope or they are members of
16995       // one of the enclosing local classes.
16996       DC = Previous.getRepresentativeDecl()->getDeclContext();
16997     } else {
16998       // This is ill-formed, but provide the context that we would have
16999       // declared the function in, if we were permitted to, for error recovery.
17000       DC = FunctionContainingLocalClass;
17001     }
17002     adjustContextForLocalExternDecl(DC);
17003 
17004     // C++ [class.friend]p6:
17005     //   A function can be defined in a friend declaration of a class if and
17006     //   only if the class is a non-local class (9.8), the function name is
17007     //   unqualified, and the function has namespace scope.
17008     if (D.isFunctionDefinition()) {
17009       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17010     }
17011 
17012   //   - There's no scope specifier, in which case we just go to the
17013   //     appropriate scope and look for a function or function template
17014   //     there as appropriate.
17015   } else if (SS.isInvalid() || !SS.isSet()) {
17016     // C++11 [namespace.memdef]p3:
17017     //   If the name in a friend declaration is neither qualified nor
17018     //   a template-id and the declaration is a function or an
17019     //   elaborated-type-specifier, the lookup to determine whether
17020     //   the entity has been previously declared shall not consider
17021     //   any scopes outside the innermost enclosing namespace.
17022     bool isTemplateId =
17023         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17024 
17025     // Find the appropriate context according to the above.
17026     DC = CurContext;
17027 
17028     // Skip class contexts.  If someone can cite chapter and verse
17029     // for this behavior, that would be nice --- it's what GCC and
17030     // EDG do, and it seems like a reasonable intent, but the spec
17031     // really only says that checks for unqualified existing
17032     // declarations should stop at the nearest enclosing namespace,
17033     // not that they should only consider the nearest enclosing
17034     // namespace.
17035     while (DC->isRecord())
17036       DC = DC->getParent();
17037 
17038     DeclContext *LookupDC = DC->getNonTransparentContext();
17039     while (true) {
17040       LookupQualifiedName(Previous, LookupDC);
17041 
17042       if (!Previous.empty()) {
17043         DC = LookupDC;
17044         break;
17045       }
17046 
17047       if (isTemplateId) {
17048         if (isa<TranslationUnitDecl>(LookupDC)) break;
17049       } else {
17050         if (LookupDC->isFileContext()) break;
17051       }
17052       LookupDC = LookupDC->getParent();
17053     }
17054 
17055     DCScope = getScopeForDeclContext(S, DC);
17056 
17057   //   - There's a non-dependent scope specifier, in which case we
17058   //     compute it and do a previous lookup there for a function
17059   //     or function template.
17060   } else if (!SS.getScopeRep()->isDependent()) {
17061     DC = computeDeclContext(SS);
17062     if (!DC) return nullptr;
17063 
17064     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17065 
17066     LookupQualifiedName(Previous, DC);
17067 
17068     // C++ [class.friend]p1: A friend of a class is a function or
17069     //   class that is not a member of the class . . .
17070     if (DC->Equals(CurContext))
17071       Diag(DS.getFriendSpecLoc(),
17072            getLangOpts().CPlusPlus11 ?
17073              diag::warn_cxx98_compat_friend_is_member :
17074              diag::err_friend_is_member);
17075 
17076     if (D.isFunctionDefinition()) {
17077       // C++ [class.friend]p6:
17078       //   A function can be defined in a friend declaration of a class if and
17079       //   only if the class is a non-local class (9.8), the function name is
17080       //   unqualified, and the function has namespace scope.
17081       //
17082       // FIXME: We should only do this if the scope specifier names the
17083       // innermost enclosing namespace; otherwise the fixit changes the
17084       // meaning of the code.
17085       SemaDiagnosticBuilder DB
17086         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17087 
17088       DB << SS.getScopeRep();
17089       if (DC->isFileContext())
17090         DB << FixItHint::CreateRemoval(SS.getRange());
17091       SS.clear();
17092     }
17093 
17094   //   - There's a scope specifier that does not match any template
17095   //     parameter lists, in which case we use some arbitrary context,
17096   //     create a method or method template, and wait for instantiation.
17097   //   - There's a scope specifier that does match some template
17098   //     parameter lists, which we don't handle right now.
17099   } else {
17100     if (D.isFunctionDefinition()) {
17101       // C++ [class.friend]p6:
17102       //   A function can be defined in a friend declaration of a class if and
17103       //   only if the class is a non-local class (9.8), the function name is
17104       //   unqualified, and the function has namespace scope.
17105       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17106         << SS.getScopeRep();
17107     }
17108 
17109     DC = CurContext;
17110     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17111   }
17112 
17113   if (!DC->isRecord()) {
17114     int DiagArg = -1;
17115     switch (D.getName().getKind()) {
17116     case UnqualifiedIdKind::IK_ConstructorTemplateId:
17117     case UnqualifiedIdKind::IK_ConstructorName:
17118       DiagArg = 0;
17119       break;
17120     case UnqualifiedIdKind::IK_DestructorName:
17121       DiagArg = 1;
17122       break;
17123     case UnqualifiedIdKind::IK_ConversionFunctionId:
17124       DiagArg = 2;
17125       break;
17126     case UnqualifiedIdKind::IK_DeductionGuideName:
17127       DiagArg = 3;
17128       break;
17129     case UnqualifiedIdKind::IK_Identifier:
17130     case UnqualifiedIdKind::IK_ImplicitSelfParam:
17131     case UnqualifiedIdKind::IK_LiteralOperatorId:
17132     case UnqualifiedIdKind::IK_OperatorFunctionId:
17133     case UnqualifiedIdKind::IK_TemplateId:
17134       break;
17135     }
17136     // This implies that it has to be an operator or function.
17137     if (DiagArg >= 0) {
17138       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17139       return nullptr;
17140     }
17141   }
17142 
17143   // FIXME: This is an egregious hack to cope with cases where the scope stack
17144   // does not contain the declaration context, i.e., in an out-of-line
17145   // definition of a class.
17146   Scope FakeDCScope(S, Scope::DeclScope, Diags);
17147   if (!DCScope) {
17148     FakeDCScope.setEntity(DC);
17149     DCScope = &FakeDCScope;
17150   }
17151 
17152   bool AddToScope = true;
17153   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17154                                           TemplateParams, AddToScope);
17155   if (!ND) return nullptr;
17156 
17157   assert(ND->getLexicalDeclContext() == CurContext);
17158 
17159   // If we performed typo correction, we might have added a scope specifier
17160   // and changed the decl context.
17161   DC = ND->getDeclContext();
17162 
17163   // Add the function declaration to the appropriate lookup tables,
17164   // adjusting the redeclarations list as necessary.  We don't
17165   // want to do this yet if the friending class is dependent.
17166   //
17167   // Also update the scope-based lookup if the target context's
17168   // lookup context is in lexical scope.
17169   if (!CurContext->isDependentContext()) {
17170     DC = DC->getRedeclContext();
17171     DC->makeDeclVisibleInContext(ND);
17172     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17173       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17174   }
17175 
17176   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17177                                        D.getIdentifierLoc(), ND,
17178                                        DS.getFriendSpecLoc());
17179   FrD->setAccess(AS_public);
17180   CurContext->addDecl(FrD);
17181 
17182   if (ND->isInvalidDecl()) {
17183     FrD->setInvalidDecl();
17184   } else {
17185     if (DC->isRecord()) CheckFriendAccess(ND);
17186 
17187     FunctionDecl *FD;
17188     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17189       FD = FTD->getTemplatedDecl();
17190     else
17191       FD = cast<FunctionDecl>(ND);
17192 
17193     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17194     // default argument expression, that declaration shall be a definition
17195     // and shall be the only declaration of the function or function
17196     // template in the translation unit.
17197     if (functionDeclHasDefaultArgument(FD)) {
17198       // We can't look at FD->getPreviousDecl() because it may not have been set
17199       // if we're in a dependent context. If the function is known to be a
17200       // redeclaration, we will have narrowed Previous down to the right decl.
17201       if (D.isRedeclaration()) {
17202         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17203         Diag(Previous.getRepresentativeDecl()->getLocation(),
17204              diag::note_previous_declaration);
17205       } else if (!D.isFunctionDefinition())
17206         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17207     }
17208 
17209     // Mark templated-scope function declarations as unsupported.
17210     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17211       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17212         << SS.getScopeRep() << SS.getRange()
17213         << cast<CXXRecordDecl>(CurContext);
17214       FrD->setUnsupportedFriend(true);
17215     }
17216   }
17217 
17218   warnOnReservedIdentifier(ND);
17219 
17220   return ND;
17221 }
17222 
17223 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17224   AdjustDeclIfTemplate(Dcl);
17225 
17226   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17227   if (!Fn) {
17228     Diag(DelLoc, diag::err_deleted_non_function);
17229     return;
17230   }
17231 
17232   // Deleted function does not have a body.
17233   Fn->setWillHaveBody(false);
17234 
17235   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17236     // Don't consider the implicit declaration we generate for explicit
17237     // specializations. FIXME: Do not generate these implicit declarations.
17238     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17239          Prev->getPreviousDecl()) &&
17240         !Prev->isDefined()) {
17241       Diag(DelLoc, diag::err_deleted_decl_not_first);
17242       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17243            Prev->isImplicit() ? diag::note_previous_implicit_declaration
17244                               : diag::note_previous_declaration);
17245       // We can't recover from this; the declaration might have already
17246       // been used.
17247       Fn->setInvalidDecl();
17248       return;
17249     }
17250 
17251     // To maintain the invariant that functions are only deleted on their first
17252     // declaration, mark the implicitly-instantiated declaration of the
17253     // explicitly-specialized function as deleted instead of marking the
17254     // instantiated redeclaration.
17255     Fn = Fn->getCanonicalDecl();
17256   }
17257 
17258   // dllimport/dllexport cannot be deleted.
17259   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17260     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17261     Fn->setInvalidDecl();
17262   }
17263 
17264   // C++11 [basic.start.main]p3:
17265   //   A program that defines main as deleted [...] is ill-formed.
17266   if (Fn->isMain())
17267     Diag(DelLoc, diag::err_deleted_main);
17268 
17269   // C++11 [dcl.fct.def.delete]p4:
17270   //  A deleted function is implicitly inline.
17271   Fn->setImplicitlyInline();
17272   Fn->setDeletedAsWritten();
17273 }
17274 
17275 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17276   if (!Dcl || Dcl->isInvalidDecl())
17277     return;
17278 
17279   auto *FD = dyn_cast<FunctionDecl>(Dcl);
17280   if (!FD) {
17281     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17282       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17283         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17284         return;
17285       }
17286     }
17287 
17288     Diag(DefaultLoc, diag::err_default_special_members)
17289         << getLangOpts().CPlusPlus20;
17290     return;
17291   }
17292 
17293   // Reject if this can't possibly be a defaultable function.
17294   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17295   if (!DefKind &&
17296       // A dependent function that doesn't locally look defaultable can
17297       // still instantiate to a defaultable function if it's a constructor
17298       // or assignment operator.
17299       (!FD->isDependentContext() ||
17300        (!isa<CXXConstructorDecl>(FD) &&
17301         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17302     Diag(DefaultLoc, diag::err_default_special_members)
17303         << getLangOpts().CPlusPlus20;
17304     return;
17305   }
17306 
17307   // Issue compatibility warning. We already warned if the operator is
17308   // 'operator<=>' when parsing the '<=>' token.
17309   if (DefKind.isComparison() &&
17310       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17311     Diag(DefaultLoc, getLangOpts().CPlusPlus20
17312                          ? diag::warn_cxx17_compat_defaulted_comparison
17313                          : diag::ext_defaulted_comparison);
17314   }
17315 
17316   FD->setDefaulted();
17317   FD->setExplicitlyDefaulted();
17318 
17319   // Defer checking functions that are defaulted in a dependent context.
17320   if (FD->isDependentContext())
17321     return;
17322 
17323   // Unset that we will have a body for this function. We might not,
17324   // if it turns out to be trivial, and we don't need this marking now
17325   // that we've marked it as defaulted.
17326   FD->setWillHaveBody(false);
17327 
17328   if (DefKind.isComparison()) {
17329     // If this comparison's defaulting occurs within the definition of its
17330     // lexical class context, we have to do the checking when complete.
17331     if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17332       if (!RD->isCompleteDefinition())
17333         return;
17334   }
17335 
17336   // If this member fn was defaulted on its first declaration, we will have
17337   // already performed the checking in CheckCompletedCXXClass. Such a
17338   // declaration doesn't trigger an implicit definition.
17339   if (isa<CXXMethodDecl>(FD)) {
17340     const FunctionDecl *Primary = FD;
17341     if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17342       // Ask the template instantiation pattern that actually had the
17343       // '= default' on it.
17344       Primary = Pattern;
17345     if (Primary->getCanonicalDecl()->isDefaulted())
17346       return;
17347   }
17348 
17349   if (DefKind.isComparison()) {
17350     if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17351       FD->setInvalidDecl();
17352     else
17353       DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17354   } else {
17355     auto *MD = cast<CXXMethodDecl>(FD);
17356 
17357     if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
17358       MD->setInvalidDecl();
17359     else
17360       DefineDefaultedFunction(*this, MD, DefaultLoc);
17361   }
17362 }
17363 
17364 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17365   for (Stmt *SubStmt : S->children()) {
17366     if (!SubStmt)
17367       continue;
17368     if (isa<ReturnStmt>(SubStmt))
17369       Self.Diag(SubStmt->getBeginLoc(),
17370                 diag::err_return_in_constructor_handler);
17371     if (!isa<Expr>(SubStmt))
17372       SearchForReturnInStmt(Self, SubStmt);
17373   }
17374 }
17375 
17376 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17377   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17378     CXXCatchStmt *Handler = TryBlock->getHandler(I);
17379     SearchForReturnInStmt(*this, Handler);
17380   }
17381 }
17382 
17383 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17384                                              const CXXMethodDecl *Old) {
17385   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17386   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17387 
17388   if (OldFT->hasExtParameterInfos()) {
17389     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17390       // A parameter of the overriding method should be annotated with noescape
17391       // if the corresponding parameter of the overridden method is annotated.
17392       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17393           !NewFT->getExtParameterInfo(I).isNoEscape()) {
17394         Diag(New->getParamDecl(I)->getLocation(),
17395              diag::warn_overriding_method_missing_noescape);
17396         Diag(Old->getParamDecl(I)->getLocation(),
17397              diag::note_overridden_marked_noescape);
17398       }
17399   }
17400 
17401   // Virtual overrides must have the same code_seg.
17402   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17403   const auto *NewCSA = New->getAttr<CodeSegAttr>();
17404   if ((NewCSA || OldCSA) &&
17405       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17406     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17407     Diag(Old->getLocation(), diag::note_previous_declaration);
17408     return true;
17409   }
17410 
17411   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17412 
17413   // If the calling conventions match, everything is fine
17414   if (NewCC == OldCC)
17415     return false;
17416 
17417   // If the calling conventions mismatch because the new function is static,
17418   // suppress the calling convention mismatch error; the error about static
17419   // function override (err_static_overrides_virtual from
17420   // Sema::CheckFunctionDeclaration) is more clear.
17421   if (New->getStorageClass() == SC_Static)
17422     return false;
17423 
17424   Diag(New->getLocation(),
17425        diag::err_conflicting_overriding_cc_attributes)
17426     << New->getDeclName() << New->getType() << Old->getType();
17427   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17428   return true;
17429 }
17430 
17431 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17432                                              const CXXMethodDecl *Old) {
17433   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17434   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17435 
17436   if (Context.hasSameType(NewTy, OldTy) ||
17437       NewTy->isDependentType() || OldTy->isDependentType())
17438     return false;
17439 
17440   // Check if the return types are covariant
17441   QualType NewClassTy, OldClassTy;
17442 
17443   /// Both types must be pointers or references to classes.
17444   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17445     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17446       NewClassTy = NewPT->getPointeeType();
17447       OldClassTy = OldPT->getPointeeType();
17448     }
17449   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17450     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17451       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17452         NewClassTy = NewRT->getPointeeType();
17453         OldClassTy = OldRT->getPointeeType();
17454       }
17455     }
17456   }
17457 
17458   // The return types aren't either both pointers or references to a class type.
17459   if (NewClassTy.isNull()) {
17460     Diag(New->getLocation(),
17461          diag::err_different_return_type_for_overriding_virtual_function)
17462         << New->getDeclName() << NewTy << OldTy
17463         << New->getReturnTypeSourceRange();
17464     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17465         << Old->getReturnTypeSourceRange();
17466 
17467     return true;
17468   }
17469 
17470   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17471     // C++14 [class.virtual]p8:
17472     //   If the class type in the covariant return type of D::f differs from
17473     //   that of B::f, the class type in the return type of D::f shall be
17474     //   complete at the point of declaration of D::f or shall be the class
17475     //   type D.
17476     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17477       if (!RT->isBeingDefined() &&
17478           RequireCompleteType(New->getLocation(), NewClassTy,
17479                               diag::err_covariant_return_incomplete,
17480                               New->getDeclName()))
17481         return true;
17482     }
17483 
17484     // Check if the new class derives from the old class.
17485     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17486       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17487           << New->getDeclName() << NewTy << OldTy
17488           << New->getReturnTypeSourceRange();
17489       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17490           << Old->getReturnTypeSourceRange();
17491       return true;
17492     }
17493 
17494     // Check if we the conversion from derived to base is valid.
17495     if (CheckDerivedToBaseConversion(
17496             NewClassTy, OldClassTy,
17497             diag::err_covariant_return_inaccessible_base,
17498             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17499             New->getLocation(), New->getReturnTypeSourceRange(),
17500             New->getDeclName(), nullptr)) {
17501       // FIXME: this note won't trigger for delayed access control
17502       // diagnostics, and it's impossible to get an undelayed error
17503       // here from access control during the original parse because
17504       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17505       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17506           << Old->getReturnTypeSourceRange();
17507       return true;
17508     }
17509   }
17510 
17511   // The qualifiers of the return types must be the same.
17512   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17513     Diag(New->getLocation(),
17514          diag::err_covariant_return_type_different_qualifications)
17515         << New->getDeclName() << NewTy << OldTy
17516         << New->getReturnTypeSourceRange();
17517     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17518         << Old->getReturnTypeSourceRange();
17519     return true;
17520   }
17521 
17522 
17523   // The new class type must have the same or less qualifiers as the old type.
17524   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17525     Diag(New->getLocation(),
17526          diag::err_covariant_return_type_class_type_more_qualified)
17527         << New->getDeclName() << NewTy << OldTy
17528         << New->getReturnTypeSourceRange();
17529     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17530         << Old->getReturnTypeSourceRange();
17531     return true;
17532   }
17533 
17534   return false;
17535 }
17536 
17537 /// Mark the given method pure.
17538 ///
17539 /// \param Method the method to be marked pure.
17540 ///
17541 /// \param InitRange the source range that covers the "0" initializer.
17542 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17543   SourceLocation EndLoc = InitRange.getEnd();
17544   if (EndLoc.isValid())
17545     Method->setRangeEnd(EndLoc);
17546 
17547   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17548     Method->setPure();
17549     return false;
17550   }
17551 
17552   if (!Method->isInvalidDecl())
17553     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17554       << Method->getDeclName() << InitRange;
17555   return true;
17556 }
17557 
17558 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17559   if (D->getFriendObjectKind())
17560     Diag(D->getLocation(), diag::err_pure_friend);
17561   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17562     CheckPureMethod(M, ZeroLoc);
17563   else
17564     Diag(D->getLocation(), diag::err_illegal_initializer);
17565 }
17566 
17567 /// Determine whether the given declaration is a global variable or
17568 /// static data member.
17569 static bool isNonlocalVariable(const Decl *D) {
17570   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17571     return Var->hasGlobalStorage();
17572 
17573   return false;
17574 }
17575 
17576 /// Invoked when we are about to parse an initializer for the declaration
17577 /// 'Dcl'.
17578 ///
17579 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17580 /// static data member of class X, names should be looked up in the scope of
17581 /// class X. If the declaration had a scope specifier, a scope will have
17582 /// been created and passed in for this purpose. Otherwise, S will be null.
17583 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17584   // If there is no declaration, there was an error parsing it.
17585   if (!D || D->isInvalidDecl())
17586     return;
17587 
17588   // We will always have a nested name specifier here, but this declaration
17589   // might not be out of line if the specifier names the current namespace:
17590   //   extern int n;
17591   //   int ::n = 0;
17592   if (S && D->isOutOfLine())
17593     EnterDeclaratorContext(S, D->getDeclContext());
17594 
17595   // If we are parsing the initializer for a static data member, push a
17596   // new expression evaluation context that is associated with this static
17597   // data member.
17598   if (isNonlocalVariable(D))
17599     PushExpressionEvaluationContext(
17600         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17601 }
17602 
17603 /// Invoked after we are finished parsing an initializer for the declaration D.
17604 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17605   // If there is no declaration, there was an error parsing it.
17606   if (!D || D->isInvalidDecl())
17607     return;
17608 
17609   if (isNonlocalVariable(D))
17610     PopExpressionEvaluationContext();
17611 
17612   if (S && D->isOutOfLine())
17613     ExitDeclaratorContext(S);
17614 }
17615 
17616 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17617 /// C++ if/switch/while/for statement.
17618 /// e.g: "if (int x = f()) {...}"
17619 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17620   // C++ 6.4p2:
17621   // The declarator shall not specify a function or an array.
17622   // The type-specifier-seq shall not contain typedef and shall not declare a
17623   // new class or enumeration.
17624   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17625          "Parser allowed 'typedef' as storage class of condition decl.");
17626 
17627   Decl *Dcl = ActOnDeclarator(S, D);
17628   if (!Dcl)
17629     return true;
17630 
17631   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17632     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17633       << D.getSourceRange();
17634     return true;
17635   }
17636 
17637   return Dcl;
17638 }
17639 
17640 void Sema::LoadExternalVTableUses() {
17641   if (!ExternalSource)
17642     return;
17643 
17644   SmallVector<ExternalVTableUse, 4> VTables;
17645   ExternalSource->ReadUsedVTables(VTables);
17646   SmallVector<VTableUse, 4> NewUses;
17647   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17648     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17649       = VTablesUsed.find(VTables[I].Record);
17650     // Even if a definition wasn't required before, it may be required now.
17651     if (Pos != VTablesUsed.end()) {
17652       if (!Pos->second && VTables[I].DefinitionRequired)
17653         Pos->second = true;
17654       continue;
17655     }
17656 
17657     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17658     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17659   }
17660 
17661   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17662 }
17663 
17664 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17665                           bool DefinitionRequired) {
17666   // Ignore any vtable uses in unevaluated operands or for classes that do
17667   // not have a vtable.
17668   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17669       CurContext->isDependentContext() || isUnevaluatedContext())
17670     return;
17671   // Do not mark as used if compiling for the device outside of the target
17672   // region.
17673   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17674       !isInOpenMPDeclareTargetContext() &&
17675       !isInOpenMPTargetExecutionDirective()) {
17676     if (!DefinitionRequired)
17677       MarkVirtualMembersReferenced(Loc, Class);
17678     return;
17679   }
17680 
17681   // Try to insert this class into the map.
17682   LoadExternalVTableUses();
17683   Class = Class->getCanonicalDecl();
17684   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17685     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17686   if (!Pos.second) {
17687     // If we already had an entry, check to see if we are promoting this vtable
17688     // to require a definition. If so, we need to reappend to the VTableUses
17689     // list, since we may have already processed the first entry.
17690     if (DefinitionRequired && !Pos.first->second) {
17691       Pos.first->second = true;
17692     } else {
17693       // Otherwise, we can early exit.
17694       return;
17695     }
17696   } else {
17697     // The Microsoft ABI requires that we perform the destructor body
17698     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17699     // the deleting destructor is emitted with the vtable, not with the
17700     // destructor definition as in the Itanium ABI.
17701     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17702       CXXDestructorDecl *DD = Class->getDestructor();
17703       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17704         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17705           // If this is an out-of-line declaration, marking it referenced will
17706           // not do anything. Manually call CheckDestructor to look up operator
17707           // delete().
17708           ContextRAII SavedContext(*this, DD);
17709           CheckDestructor(DD);
17710         } else {
17711           MarkFunctionReferenced(Loc, Class->getDestructor());
17712         }
17713       }
17714     }
17715   }
17716 
17717   // Local classes need to have their virtual members marked
17718   // immediately. For all other classes, we mark their virtual members
17719   // at the end of the translation unit.
17720   if (Class->isLocalClass())
17721     MarkVirtualMembersReferenced(Loc, Class);
17722   else
17723     VTableUses.push_back(std::make_pair(Class, Loc));
17724 }
17725 
17726 bool Sema::DefineUsedVTables() {
17727   LoadExternalVTableUses();
17728   if (VTableUses.empty())
17729     return false;
17730 
17731   // Note: The VTableUses vector could grow as a result of marking
17732   // the members of a class as "used", so we check the size each
17733   // time through the loop and prefer indices (which are stable) to
17734   // iterators (which are not).
17735   bool DefinedAnything = false;
17736   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17737     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17738     if (!Class)
17739       continue;
17740     TemplateSpecializationKind ClassTSK =
17741         Class->getTemplateSpecializationKind();
17742 
17743     SourceLocation Loc = VTableUses[I].second;
17744 
17745     bool DefineVTable = true;
17746 
17747     // If this class has a key function, but that key function is
17748     // defined in another translation unit, we don't need to emit the
17749     // vtable even though we're using it.
17750     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17751     if (KeyFunction && !KeyFunction->hasBody()) {
17752       // The key function is in another translation unit.
17753       DefineVTable = false;
17754       TemplateSpecializationKind TSK =
17755           KeyFunction->getTemplateSpecializationKind();
17756       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17757              TSK != TSK_ImplicitInstantiation &&
17758              "Instantiations don't have key functions");
17759       (void)TSK;
17760     } else if (!KeyFunction) {
17761       // If we have a class with no key function that is the subject
17762       // of an explicit instantiation declaration, suppress the
17763       // vtable; it will live with the explicit instantiation
17764       // definition.
17765       bool IsExplicitInstantiationDeclaration =
17766           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17767       for (auto R : Class->redecls()) {
17768         TemplateSpecializationKind TSK
17769           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17770         if (TSK == TSK_ExplicitInstantiationDeclaration)
17771           IsExplicitInstantiationDeclaration = true;
17772         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17773           IsExplicitInstantiationDeclaration = false;
17774           break;
17775         }
17776       }
17777 
17778       if (IsExplicitInstantiationDeclaration)
17779         DefineVTable = false;
17780     }
17781 
17782     // The exception specifications for all virtual members may be needed even
17783     // if we are not providing an authoritative form of the vtable in this TU.
17784     // We may choose to emit it available_externally anyway.
17785     if (!DefineVTable) {
17786       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17787       continue;
17788     }
17789 
17790     // Mark all of the virtual members of this class as referenced, so
17791     // that we can build a vtable. Then, tell the AST consumer that a
17792     // vtable for this class is required.
17793     DefinedAnything = true;
17794     MarkVirtualMembersReferenced(Loc, Class);
17795     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17796     if (VTablesUsed[Canonical])
17797       Consumer.HandleVTable(Class);
17798 
17799     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17800     // no key function or the key function is inlined. Don't warn in C++ ABIs
17801     // that lack key functions, since the user won't be able to make one.
17802     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17803         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
17804         ClassTSK != TSK_ExplicitInstantiationDefinition) {
17805       const FunctionDecl *KeyFunctionDef = nullptr;
17806       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17807                            KeyFunctionDef->isInlined()))
17808         Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
17809     }
17810   }
17811   VTableUses.clear();
17812 
17813   return DefinedAnything;
17814 }
17815 
17816 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17817                                                  const CXXRecordDecl *RD) {
17818   for (const auto *I : RD->methods())
17819     if (I->isVirtual() && !I->isPure())
17820       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17821 }
17822 
17823 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17824                                         const CXXRecordDecl *RD,
17825                                         bool ConstexprOnly) {
17826   // Mark all functions which will appear in RD's vtable as used.
17827   CXXFinalOverriderMap FinalOverriders;
17828   RD->getFinalOverriders(FinalOverriders);
17829   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17830                                             E = FinalOverriders.end();
17831        I != E; ++I) {
17832     for (OverridingMethods::const_iterator OI = I->second.begin(),
17833                                            OE = I->second.end();
17834          OI != OE; ++OI) {
17835       assert(OI->second.size() > 0 && "no final overrider");
17836       CXXMethodDecl *Overrider = OI->second.front().Method;
17837 
17838       // C++ [basic.def.odr]p2:
17839       //   [...] A virtual member function is used if it is not pure. [...]
17840       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17841         MarkFunctionReferenced(Loc, Overrider);
17842     }
17843   }
17844 
17845   // Only classes that have virtual bases need a VTT.
17846   if (RD->getNumVBases() == 0)
17847     return;
17848 
17849   for (const auto &I : RD->bases()) {
17850     const auto *Base =
17851         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17852     if (Base->getNumVBases() == 0)
17853       continue;
17854     MarkVirtualMembersReferenced(Loc, Base);
17855   }
17856 }
17857 
17858 /// SetIvarInitializers - This routine builds initialization ASTs for the
17859 /// Objective-C implementation whose ivars need be initialized.
17860 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17861   if (!getLangOpts().CPlusPlus)
17862     return;
17863   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17864     SmallVector<ObjCIvarDecl*, 8> ivars;
17865     CollectIvarsToConstructOrDestruct(OID, ivars);
17866     if (ivars.empty())
17867       return;
17868     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17869     for (unsigned i = 0; i < ivars.size(); i++) {
17870       FieldDecl *Field = ivars[i];
17871       if (Field->isInvalidDecl())
17872         continue;
17873 
17874       CXXCtorInitializer *Member;
17875       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17876       InitializationKind InitKind =
17877         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17878 
17879       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17880       ExprResult MemberInit =
17881         InitSeq.Perform(*this, InitEntity, InitKind, None);
17882       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17883       // Note, MemberInit could actually come back empty if no initialization
17884       // is required (e.g., because it would call a trivial default constructor)
17885       if (!MemberInit.get() || MemberInit.isInvalid())
17886         continue;
17887 
17888       Member =
17889         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17890                                          SourceLocation(),
17891                                          MemberInit.getAs<Expr>(),
17892                                          SourceLocation());
17893       AllToInit.push_back(Member);
17894 
17895       // Be sure that the destructor is accessible and is marked as referenced.
17896       if (const RecordType *RecordTy =
17897               Context.getBaseElementType(Field->getType())
17898                   ->getAs<RecordType>()) {
17899         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17900         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17901           MarkFunctionReferenced(Field->getLocation(), Destructor);
17902           CheckDestructorAccess(Field->getLocation(), Destructor,
17903                             PDiag(diag::err_access_dtor_ivar)
17904                               << Context.getBaseElementType(Field->getType()));
17905         }
17906       }
17907     }
17908     ObjCImplementation->setIvarInitializers(Context,
17909                                             AllToInit.data(), AllToInit.size());
17910   }
17911 }
17912 
17913 static
17914 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17915                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17916                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17917                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17918                            Sema &S) {
17919   if (Ctor->isInvalidDecl())
17920     return;
17921 
17922   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17923 
17924   // Target may not be determinable yet, for instance if this is a dependent
17925   // call in an uninstantiated template.
17926   if (Target) {
17927     const FunctionDecl *FNTarget = nullptr;
17928     (void)Target->hasBody(FNTarget);
17929     Target = const_cast<CXXConstructorDecl*>(
17930       cast_or_null<CXXConstructorDecl>(FNTarget));
17931   }
17932 
17933   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17934                      // Avoid dereferencing a null pointer here.
17935                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17936 
17937   if (!Current.insert(Canonical).second)
17938     return;
17939 
17940   // We know that beyond here, we aren't chaining into a cycle.
17941   if (!Target || !Target->isDelegatingConstructor() ||
17942       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17943     Valid.insert(Current.begin(), Current.end());
17944     Current.clear();
17945   // We've hit a cycle.
17946   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17947              Current.count(TCanonical)) {
17948     // If we haven't diagnosed this cycle yet, do so now.
17949     if (!Invalid.count(TCanonical)) {
17950       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17951              diag::warn_delegating_ctor_cycle)
17952         << Ctor;
17953 
17954       // Don't add a note for a function delegating directly to itself.
17955       if (TCanonical != Canonical)
17956         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17957 
17958       CXXConstructorDecl *C = Target;
17959       while (C->getCanonicalDecl() != Canonical) {
17960         const FunctionDecl *FNTarget = nullptr;
17961         (void)C->getTargetConstructor()->hasBody(FNTarget);
17962         assert(FNTarget && "Ctor cycle through bodiless function");
17963 
17964         C = const_cast<CXXConstructorDecl*>(
17965           cast<CXXConstructorDecl>(FNTarget));
17966         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17967       }
17968     }
17969 
17970     Invalid.insert(Current.begin(), Current.end());
17971     Current.clear();
17972   } else {
17973     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17974   }
17975 }
17976 
17977 
17978 void Sema::CheckDelegatingCtorCycles() {
17979   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17980 
17981   for (DelegatingCtorDeclsType::iterator
17982          I = DelegatingCtorDecls.begin(ExternalSource),
17983          E = DelegatingCtorDecls.end();
17984        I != E; ++I)
17985     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17986 
17987   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17988     (*CI)->setInvalidDecl();
17989 }
17990 
17991 namespace {
17992   /// AST visitor that finds references to the 'this' expression.
17993   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17994     Sema &S;
17995 
17996   public:
17997     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17998 
17999     bool VisitCXXThisExpr(CXXThisExpr *E) {
18000       S.Diag(E->getLocation(), diag::err_this_static_member_func)
18001         << E->isImplicit();
18002       return false;
18003     }
18004   };
18005 }
18006 
18007 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18008   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18009   if (!TSInfo)
18010     return false;
18011 
18012   TypeLoc TL = TSInfo->getTypeLoc();
18013   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18014   if (!ProtoTL)
18015     return false;
18016 
18017   // C++11 [expr.prim.general]p3:
18018   //   [The expression this] shall not appear before the optional
18019   //   cv-qualifier-seq and it shall not appear within the declaration of a
18020   //   static member function (although its type and value category are defined
18021   //   within a static member function as they are within a non-static member
18022   //   function). [ Note: this is because declaration matching does not occur
18023   //  until the complete declarator is known. - end note ]
18024   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18025   FindCXXThisExpr Finder(*this);
18026 
18027   // If the return type came after the cv-qualifier-seq, check it now.
18028   if (Proto->hasTrailingReturn() &&
18029       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18030     return true;
18031 
18032   // Check the exception specification.
18033   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18034     return true;
18035 
18036   // Check the trailing requires clause
18037   if (Expr *E = Method->getTrailingRequiresClause())
18038     if (!Finder.TraverseStmt(E))
18039       return true;
18040 
18041   return checkThisInStaticMemberFunctionAttributes(Method);
18042 }
18043 
18044 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18045   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18046   if (!TSInfo)
18047     return false;
18048 
18049   TypeLoc TL = TSInfo->getTypeLoc();
18050   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18051   if (!ProtoTL)
18052     return false;
18053 
18054   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18055   FindCXXThisExpr Finder(*this);
18056 
18057   switch (Proto->getExceptionSpecType()) {
18058   case EST_Unparsed:
18059   case EST_Uninstantiated:
18060   case EST_Unevaluated:
18061   case EST_BasicNoexcept:
18062   case EST_NoThrow:
18063   case EST_DynamicNone:
18064   case EST_MSAny:
18065   case EST_None:
18066     break;
18067 
18068   case EST_DependentNoexcept:
18069   case EST_NoexceptFalse:
18070   case EST_NoexceptTrue:
18071     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18072       return true;
18073     LLVM_FALLTHROUGH;
18074 
18075   case EST_Dynamic:
18076     for (const auto &E : Proto->exceptions()) {
18077       if (!Finder.TraverseType(E))
18078         return true;
18079     }
18080     break;
18081   }
18082 
18083   return false;
18084 }
18085 
18086 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
18087   FindCXXThisExpr Finder(*this);
18088 
18089   // Check attributes.
18090   for (const auto *A : Method->attrs()) {
18091     // FIXME: This should be emitted by tblgen.
18092     Expr *Arg = nullptr;
18093     ArrayRef<Expr *> Args;
18094     if (const auto *G = dyn_cast<GuardedByAttr>(A))
18095       Arg = G->getArg();
18096     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18097       Arg = G->getArg();
18098     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18099       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
18100     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18101       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
18102     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18103       Arg = ETLF->getSuccessValue();
18104       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
18105     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18106       Arg = STLF->getSuccessValue();
18107       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
18108     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18109       Arg = LR->getArg();
18110     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18111       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
18112     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18113       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18114     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18115       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18116     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18117       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18118     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18119       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18120 
18121     if (Arg && !Finder.TraverseStmt(Arg))
18122       return true;
18123 
18124     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18125       if (!Finder.TraverseStmt(Args[I]))
18126         return true;
18127     }
18128   }
18129 
18130   return false;
18131 }
18132 
18133 void Sema::checkExceptionSpecification(
18134     bool IsTopLevel, ExceptionSpecificationType EST,
18135     ArrayRef<ParsedType> DynamicExceptions,
18136     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18137     SmallVectorImpl<QualType> &Exceptions,
18138     FunctionProtoType::ExceptionSpecInfo &ESI) {
18139   Exceptions.clear();
18140   ESI.Type = EST;
18141   if (EST == EST_Dynamic) {
18142     Exceptions.reserve(DynamicExceptions.size());
18143     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18144       // FIXME: Preserve type source info.
18145       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18146 
18147       if (IsTopLevel) {
18148         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
18149         collectUnexpandedParameterPacks(ET, Unexpanded);
18150         if (!Unexpanded.empty()) {
18151           DiagnoseUnexpandedParameterPacks(
18152               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18153               Unexpanded);
18154           continue;
18155         }
18156       }
18157 
18158       // Check that the type is valid for an exception spec, and
18159       // drop it if not.
18160       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18161         Exceptions.push_back(ET);
18162     }
18163     ESI.Exceptions = Exceptions;
18164     return;
18165   }
18166 
18167   if (isComputedNoexcept(EST)) {
18168     assert((NoexceptExpr->isTypeDependent() ||
18169             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18170             Context.BoolTy) &&
18171            "Parser should have made sure that the expression is boolean");
18172     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18173       ESI.Type = EST_BasicNoexcept;
18174       return;
18175     }
18176 
18177     ESI.NoexceptExpr = NoexceptExpr;
18178     return;
18179   }
18180 }
18181 
18182 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
18183              ExceptionSpecificationType EST,
18184              SourceRange SpecificationRange,
18185              ArrayRef<ParsedType> DynamicExceptions,
18186              ArrayRef<SourceRange> DynamicExceptionRanges,
18187              Expr *NoexceptExpr) {
18188   if (!MethodD)
18189     return;
18190 
18191   // Dig out the method we're referring to.
18192   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18193     MethodD = FunTmpl->getTemplatedDecl();
18194 
18195   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18196   if (!Method)
18197     return;
18198 
18199   // Check the exception specification.
18200   llvm::SmallVector<QualType, 4> Exceptions;
18201   FunctionProtoType::ExceptionSpecInfo ESI;
18202   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18203                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
18204                               ESI);
18205 
18206   // Update the exception specification on the function type.
18207   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18208 
18209   if (Method->isStatic())
18210     checkThisInStaticMemberFunctionExceptionSpec(Method);
18211 
18212   if (Method->isVirtual()) {
18213     // Check overrides, which we previously had to delay.
18214     for (const CXXMethodDecl *O : Method->overridden_methods())
18215       CheckOverridingFunctionExceptionSpec(Method, O);
18216   }
18217 }
18218 
18219 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18220 ///
18221 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18222                                        SourceLocation DeclStart, Declarator &D,
18223                                        Expr *BitWidth,
18224                                        InClassInitStyle InitStyle,
18225                                        AccessSpecifier AS,
18226                                        const ParsedAttr &MSPropertyAttr) {
18227   IdentifierInfo *II = D.getIdentifier();
18228   if (!II) {
18229     Diag(DeclStart, diag::err_anonymous_property);
18230     return nullptr;
18231   }
18232   SourceLocation Loc = D.getIdentifierLoc();
18233 
18234   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18235   QualType T = TInfo->getType();
18236   if (getLangOpts().CPlusPlus) {
18237     CheckExtraCXXDefaultArguments(D);
18238 
18239     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18240                                         UPPC_DataMemberType)) {
18241       D.setInvalidType();
18242       T = Context.IntTy;
18243       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18244     }
18245   }
18246 
18247   DiagnoseFunctionSpecifiers(D.getDeclSpec());
18248 
18249   if (D.getDeclSpec().isInlineSpecified())
18250     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18251         << getLangOpts().CPlusPlus17;
18252   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18253     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18254          diag::err_invalid_thread)
18255       << DeclSpec::getSpecifierName(TSCS);
18256 
18257   // Check to see if this name was declared as a member previously
18258   NamedDecl *PrevDecl = nullptr;
18259   LookupResult Previous(*this, II, Loc, LookupMemberName,
18260                         ForVisibleRedeclaration);
18261   LookupName(Previous, S);
18262   switch (Previous.getResultKind()) {
18263   case LookupResult::Found:
18264   case LookupResult::FoundUnresolvedValue:
18265     PrevDecl = Previous.getAsSingle<NamedDecl>();
18266     break;
18267 
18268   case LookupResult::FoundOverloaded:
18269     PrevDecl = Previous.getRepresentativeDecl();
18270     break;
18271 
18272   case LookupResult::NotFound:
18273   case LookupResult::NotFoundInCurrentInstantiation:
18274   case LookupResult::Ambiguous:
18275     break;
18276   }
18277 
18278   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18279     // Maybe we will complain about the shadowed template parameter.
18280     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18281     // Just pretend that we didn't see the previous declaration.
18282     PrevDecl = nullptr;
18283   }
18284 
18285   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18286     PrevDecl = nullptr;
18287 
18288   SourceLocation TSSL = D.getBeginLoc();
18289   MSPropertyDecl *NewPD =
18290       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18291                              MSPropertyAttr.getPropertyDataGetter(),
18292                              MSPropertyAttr.getPropertyDataSetter());
18293   ProcessDeclAttributes(TUScope, NewPD, D);
18294   NewPD->setAccess(AS);
18295 
18296   if (NewPD->isInvalidDecl())
18297     Record->setInvalidDecl();
18298 
18299   if (D.getDeclSpec().isModulePrivateSpecified())
18300     NewPD->setModulePrivate();
18301 
18302   if (NewPD->isInvalidDecl() && PrevDecl) {
18303     // Don't introduce NewFD into scope; there's already something
18304     // with the same name in the same scope.
18305   } else if (II) {
18306     PushOnScopeChains(NewPD, S);
18307   } else
18308     Record->addDecl(NewPD);
18309 
18310   return NewPD;
18311 }
18312 
18313 void Sema::ActOnStartFunctionDeclarationDeclarator(
18314     Declarator &Declarator, unsigned TemplateParameterDepth) {
18315   auto &Info = InventedParameterInfos.emplace_back();
18316   TemplateParameterList *ExplicitParams = nullptr;
18317   ArrayRef<TemplateParameterList *> ExplicitLists =
18318       Declarator.getTemplateParameterLists();
18319   if (!ExplicitLists.empty()) {
18320     bool IsMemberSpecialization, IsInvalid;
18321     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18322         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18323         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18324         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18325         /*SuppressDiagnostic=*/true);
18326   }
18327   if (ExplicitParams) {
18328     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18329     llvm::append_range(Info.TemplateParams, *ExplicitParams);
18330     Info.NumExplicitTemplateParams = ExplicitParams->size();
18331   } else {
18332     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18333     Info.NumExplicitTemplateParams = 0;
18334   }
18335 }
18336 
18337 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18338   auto &FSI = InventedParameterInfos.back();
18339   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18340     if (FSI.NumExplicitTemplateParams != 0) {
18341       TemplateParameterList *ExplicitParams =
18342           Declarator.getTemplateParameterLists().back();
18343       Declarator.setInventedTemplateParameterList(
18344           TemplateParameterList::Create(
18345               Context, ExplicitParams->getTemplateLoc(),
18346               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18347               ExplicitParams->getRAngleLoc(),
18348               ExplicitParams->getRequiresClause()));
18349     } else {
18350       Declarator.setInventedTemplateParameterList(
18351           TemplateParameterList::Create(
18352               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18353               SourceLocation(), /*RequiresClause=*/nullptr));
18354     }
18355   }
18356   InventedParameterInfos.pop_back();
18357 }
18358