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/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "clang/Sema/Template.h"
41 #include "llvm/ADT/ScopeExit.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include <map>
46 #include <set>
47 
48 using namespace clang;
49 
50 //===----------------------------------------------------------------------===//
51 // CheckDefaultArgumentVisitor
52 //===----------------------------------------------------------------------===//
53 
54 namespace {
55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
56 /// the default argument of a parameter to determine whether it
57 /// contains any ill-formed subexpressions. For example, this will
58 /// diagnose the use of local variables or parameters within the
59 /// default argument expression.
60 class CheckDefaultArgumentVisitor
61     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
62   Sema &S;
63   const Expr *DefaultArg;
64 
65 public:
66   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
67       : S(S), DefaultArg(DefaultArg) {}
68 
69   bool VisitExpr(const Expr *Node);
70   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
71   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
72   bool VisitLambdaExpr(const LambdaExpr *Lambda);
73   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
74 };
75 
76 /// VisitExpr - Visit all of the children of this expression.
77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
78   bool IsInvalid = false;
79   for (const Stmt *SubStmt : Node->children())
80     IsInvalid |= Visit(SubStmt);
81   return IsInvalid;
82 }
83 
84 /// VisitDeclRefExpr - Visit a reference to a declaration, to
85 /// determine whether this declaration can be used in the default
86 /// argument expression.
87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
88   const NamedDecl *Decl = DRE->getDecl();
89   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
90     // C++ [dcl.fct.default]p9:
91     //   [...] parameters of a function shall not be used in default
92     //   argument expressions, even if they are not evaluated. [...]
93     //
94     // C++17 [dcl.fct.default]p9 (by CWG 2082):
95     //   [...] A parameter shall not appear as a potentially-evaluated
96     //   expression in a default argument. [...]
97     //
98     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
99       return S.Diag(DRE->getBeginLoc(),
100                     diag::err_param_default_argument_references_param)
101              << Param->getDeclName() << DefaultArg->getSourceRange();
102   } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
103     // C++ [dcl.fct.default]p7:
104     //   Local variables shall not be used in default argument
105     //   expressions.
106     //
107     // C++17 [dcl.fct.default]p7 (by CWG 2082):
108     //   A local variable shall not appear as a potentially-evaluated
109     //   expression in a default argument.
110     //
111     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
112     //   Note: A local variable cannot be odr-used (6.3) in a default argument.
113     //
114     if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
115       return S.Diag(DRE->getBeginLoc(),
116                     diag::err_param_default_argument_references_local)
117              << VDecl->getDeclName() << DefaultArg->getSourceRange();
118   }
119 
120   return false;
121 }
122 
123 /// VisitCXXThisExpr - Visit a C++ "this" expression.
124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
125   // C++ [dcl.fct.default]p8:
126   //   The keyword this shall not be used in a default argument of a
127   //   member function.
128   return S.Diag(ThisE->getBeginLoc(),
129                 diag::err_param_default_argument_references_this)
130          << ThisE->getSourceRange();
131 }
132 
133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
134     const PseudoObjectExpr *POE) {
135   bool Invalid = false;
136   for (const Expr *E : POE->semantics()) {
137     // Look through bindings.
138     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
139       E = OVE->getSourceExpr();
140       assert(E && "pseudo-object binding without source expression?");
141     }
142 
143     Invalid |= Visit(E);
144   }
145   return Invalid;
146 }
147 
148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
149   // C++11 [expr.lambda.prim]p13:
150   //   A lambda-expression appearing in a default argument shall not
151   //   implicitly or explicitly capture any entity.
152   if (Lambda->capture_begin() == Lambda->capture_end())
153     return false;
154 
155   return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
156 }
157 } // namespace
158 
159 void
160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
161                                                  const CXXMethodDecl *Method) {
162   // If we have an MSAny spec already, don't bother.
163   if (!Method || ComputedEST == EST_MSAny)
164     return;
165 
166   const FunctionProtoType *Proto
167     = Method->getType()->getAs<FunctionProtoType>();
168   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
169   if (!Proto)
170     return;
171 
172   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
173 
174   // If we have a throw-all spec at this point, ignore the function.
175   if (ComputedEST == EST_None)
176     return;
177 
178   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
179     EST = EST_BasicNoexcept;
180 
181   switch (EST) {
182   case EST_Unparsed:
183   case EST_Uninstantiated:
184   case EST_Unevaluated:
185     llvm_unreachable("should not see unresolved exception specs here");
186 
187   // If this function can throw any exceptions, make a note of that.
188   case EST_MSAny:
189   case EST_None:
190     // FIXME: Whichever we see last of MSAny and None determines our result.
191     // We should make a consistent, order-independent choice here.
192     ClearExceptions();
193     ComputedEST = EST;
194     return;
195   case EST_NoexceptFalse:
196     ClearExceptions();
197     ComputedEST = EST_None;
198     return;
199   // FIXME: If the call to this decl is using any of its default arguments, we
200   // need to search them for potentially-throwing calls.
201   // If this function has a basic noexcept, it doesn't affect the outcome.
202   case EST_BasicNoexcept:
203   case EST_NoexceptTrue:
204   case EST_NoThrow:
205     return;
206   // If we're still at noexcept(true) and there's a throw() callee,
207   // change to that specification.
208   case EST_DynamicNone:
209     if (ComputedEST == EST_BasicNoexcept)
210       ComputedEST = EST_DynamicNone;
211     return;
212   case EST_DependentNoexcept:
213     llvm_unreachable(
214         "should not generate implicit declarations for dependent cases");
215   case EST_Dynamic:
216     break;
217   }
218   assert(EST == EST_Dynamic && "EST case not considered earlier.");
219   assert(ComputedEST != EST_None &&
220          "Shouldn't collect exceptions when throw-all is guaranteed.");
221   ComputedEST = EST_Dynamic;
222   // Record the exceptions in this function's exception specification.
223   for (const auto &E : Proto->exceptions())
224     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
225       Exceptions.push_back(E);
226 }
227 
228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
229   if (!S || ComputedEST == EST_MSAny)
230     return;
231 
232   // FIXME:
233   //
234   // C++0x [except.spec]p14:
235   //   [An] implicit exception-specification specifies the type-id T if and
236   // only if T is allowed by the exception-specification of a function directly
237   // invoked by f's implicit definition; f shall allow all exceptions if any
238   // function it directly invokes allows all exceptions, and f shall allow no
239   // exceptions if every function it directly invokes allows no exceptions.
240   //
241   // Note in particular that if an implicit exception-specification is generated
242   // for a function containing a throw-expression, that specification can still
243   // be noexcept(true).
244   //
245   // Note also that 'directly invoked' is not defined in the standard, and there
246   // is no indication that we should only consider potentially-evaluated calls.
247   //
248   // Ultimately we should implement the intent of the standard: the exception
249   // specification should be the set of exceptions which can be thrown by the
250   // implicit definition. For now, we assume that any non-nothrow expression can
251   // throw any exception.
252 
253   if (Self->canThrow(S))
254     ComputedEST = EST_None;
255 }
256 
257 ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param,
258                                              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_RValue));
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)
385                        OpaqueValueExpr(EqualLoc,
386                                        Param->getType().getNonReferenceType(),
387                                        VK_RValue));
388 }
389 
390 /// CheckExtraCXXDefaultArguments - Check for any extra default
391 /// arguments in the declarator, which is not a function declaration
392 /// or definition and therefore is not permitted to have default
393 /// arguments. This routine should be invoked for every declarator
394 /// that is not a function declaration or definition.
395 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
396   // C++ [dcl.fct.default]p3
397   //   A default argument expression shall be specified only in the
398   //   parameter-declaration-clause of a function declaration or in a
399   //   template-parameter (14.1). It shall not be specified for a
400   //   parameter pack. If it is specified in a
401   //   parameter-declaration-clause, it shall not occur within a
402   //   declarator or abstract-declarator of a parameter-declaration.
403   bool MightBeFunction = D.isFunctionDeclarationContext();
404   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
405     DeclaratorChunk &chunk = D.getTypeObject(i);
406     if (chunk.Kind == DeclaratorChunk::Function) {
407       if (MightBeFunction) {
408         // This is a function declaration. It can have default arguments, but
409         // keep looking in case its return type is a function type with default
410         // arguments.
411         MightBeFunction = false;
412         continue;
413       }
414       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
415            ++argIdx) {
416         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
417         if (Param->hasUnparsedDefaultArg()) {
418           std::unique_ptr<CachedTokens> Toks =
419               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
420           SourceRange SR;
421           if (Toks->size() > 1)
422             SR = SourceRange((*Toks)[1].getLocation(),
423                              Toks->back().getLocation());
424           else
425             SR = UnparsedDefaultArgLocs[Param];
426           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
427             << SR;
428         } else if (Param->getDefaultArg()) {
429           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
430             << Param->getDefaultArg()->getSourceRange();
431           Param->setDefaultArg(nullptr);
432         }
433       }
434     } else if (chunk.Kind != DeclaratorChunk::Paren) {
435       MightBeFunction = false;
436     }
437   }
438 }
439 
440 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
441   return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) {
442     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
443   });
444 }
445 
446 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
447 /// function, once we already know that they have the same
448 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
449 /// error, false otherwise.
450 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
451                                 Scope *S) {
452   bool Invalid = false;
453 
454   // The declaration context corresponding to the scope is the semantic
455   // parent, unless this is a local function declaration, in which case
456   // it is that surrounding function.
457   DeclContext *ScopeDC = New->isLocalExternDecl()
458                              ? New->getLexicalDeclContext()
459                              : New->getDeclContext();
460 
461   // Find the previous declaration for the purpose of default arguments.
462   FunctionDecl *PrevForDefaultArgs = Old;
463   for (/**/; PrevForDefaultArgs;
464        // Don't bother looking back past the latest decl if this is a local
465        // extern declaration; nothing else could work.
466        PrevForDefaultArgs = New->isLocalExternDecl()
467                                 ? nullptr
468                                 : PrevForDefaultArgs->getPreviousDecl()) {
469     // Ignore hidden declarations.
470     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
471       continue;
472 
473     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
474         !New->isCXXClassMember()) {
475       // Ignore default arguments of old decl if they are not in
476       // the same scope and this is not an out-of-line definition of
477       // a member function.
478       continue;
479     }
480 
481     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
482       // If only one of these is a local function declaration, then they are
483       // declared in different scopes, even though isDeclInScope may think
484       // they're in the same scope. (If both are local, the scope check is
485       // sufficient, and if neither is local, then they are in the same scope.)
486       continue;
487     }
488 
489     // We found the right previous declaration.
490     break;
491   }
492 
493   // C++ [dcl.fct.default]p4:
494   //   For non-template functions, default arguments can be added in
495   //   later declarations of a function in the same
496   //   scope. Declarations in different scopes have completely
497   //   distinct sets of default arguments. That is, declarations in
498   //   inner scopes do not acquire default arguments from
499   //   declarations in outer scopes, and vice versa. In a given
500   //   function declaration, all parameters subsequent to a
501   //   parameter with a default argument shall have default
502   //   arguments supplied in this or previous declarations. A
503   //   default argument shall not be redefined by a later
504   //   declaration (not even to the same value).
505   //
506   // C++ [dcl.fct.default]p6:
507   //   Except for member functions of class templates, the default arguments
508   //   in a member function definition that appears outside of the class
509   //   definition are added to the set of default arguments provided by the
510   //   member function declaration in the class definition.
511   for (unsigned p = 0, NumParams = PrevForDefaultArgs
512                                        ? PrevForDefaultArgs->getNumParams()
513                                        : 0;
514        p < NumParams; ++p) {
515     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
516     ParmVarDecl *NewParam = New->getParamDecl(p);
517 
518     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
519     bool NewParamHasDfl = NewParam->hasDefaultArg();
520 
521     if (OldParamHasDfl && NewParamHasDfl) {
522       unsigned DiagDefaultParamID =
523         diag::err_param_default_argument_redefinition;
524 
525       // MSVC accepts that default parameters be redefined for member functions
526       // of template class. The new default parameter's value is ignored.
527       Invalid = true;
528       if (getLangOpts().MicrosoftExt) {
529         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
530         if (MD && MD->getParent()->getDescribedClassTemplate()) {
531           // Merge the old default argument into the new parameter.
532           NewParam->setHasInheritedDefaultArg();
533           if (OldParam->hasUninstantiatedDefaultArg())
534             NewParam->setUninstantiatedDefaultArg(
535                                       OldParam->getUninstantiatedDefaultArg());
536           else
537             NewParam->setDefaultArg(OldParam->getInit());
538           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
539           Invalid = false;
540         }
541       }
542 
543       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
544       // hint here. Alternatively, we could walk the type-source information
545       // for NewParam to find the last source location in the type... but it
546       // isn't worth the effort right now. This is the kind of test case that
547       // is hard to get right:
548       //   int f(int);
549       //   void g(int (*fp)(int) = f);
550       //   void g(int (*fp)(int) = &f);
551       Diag(NewParam->getLocation(), DiagDefaultParamID)
552         << NewParam->getDefaultArgRange();
553 
554       // Look for the function declaration where the default argument was
555       // actually written, which may be a declaration prior to Old.
556       for (auto Older = PrevForDefaultArgs;
557            OldParam->hasInheritedDefaultArg(); /**/) {
558         Older = Older->getPreviousDecl();
559         OldParam = Older->getParamDecl(p);
560       }
561 
562       Diag(OldParam->getLocation(), diag::note_previous_definition)
563         << OldParam->getDefaultArgRange();
564     } else if (OldParamHasDfl) {
565       // Merge the old default argument into the new parameter unless the new
566       // function is a friend declaration in a template class. In the latter
567       // case the default arguments will be inherited when the friend
568       // declaration will be instantiated.
569       if (New->getFriendObjectKind() == Decl::FOK_None ||
570           !New->getLexicalDeclContext()->isDependentContext()) {
571         // It's important to use getInit() here;  getDefaultArg()
572         // strips off any top-level ExprWithCleanups.
573         NewParam->setHasInheritedDefaultArg();
574         if (OldParam->hasUnparsedDefaultArg())
575           NewParam->setUnparsedDefaultArg();
576         else if (OldParam->hasUninstantiatedDefaultArg())
577           NewParam->setUninstantiatedDefaultArg(
578                                        OldParam->getUninstantiatedDefaultArg());
579         else
580           NewParam->setDefaultArg(OldParam->getInit());
581       }
582     } else if (NewParamHasDfl) {
583       if (New->getDescribedFunctionTemplate()) {
584         // Paragraph 4, quoted above, only applies to non-template functions.
585         Diag(NewParam->getLocation(),
586              diag::err_param_default_argument_template_redecl)
587           << NewParam->getDefaultArgRange();
588         Diag(PrevForDefaultArgs->getLocation(),
589              diag::note_template_prev_declaration)
590             << false;
591       } else if (New->getTemplateSpecializationKind()
592                    != TSK_ImplicitInstantiation &&
593                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
594         // C++ [temp.expr.spec]p21:
595         //   Default function arguments shall not be specified in a declaration
596         //   or a definition for one of the following explicit specializations:
597         //     - the explicit specialization of a function template;
598         //     - the explicit specialization of a member function template;
599         //     - the explicit specialization of a member function of a class
600         //       template where the class template specialization to which the
601         //       member function specialization belongs is implicitly
602         //       instantiated.
603         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
604           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
605           << New->getDeclName()
606           << NewParam->getDefaultArgRange();
607       } else if (New->getDeclContext()->isDependentContext()) {
608         // C++ [dcl.fct.default]p6 (DR217):
609         //   Default arguments for a member function of a class template shall
610         //   be specified on the initial declaration of the member function
611         //   within the class template.
612         //
613         // Reading the tea leaves a bit in DR217 and its reference to DR205
614         // leads me to the conclusion that one cannot add default function
615         // arguments for an out-of-line definition of a member function of a
616         // dependent type.
617         int WhichKind = 2;
618         if (CXXRecordDecl *Record
619               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
620           if (Record->getDescribedClassTemplate())
621             WhichKind = 0;
622           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
623             WhichKind = 1;
624           else
625             WhichKind = 2;
626         }
627 
628         Diag(NewParam->getLocation(),
629              diag::err_param_default_argument_member_template_redecl)
630           << WhichKind
631           << NewParam->getDefaultArgRange();
632       }
633     }
634   }
635 
636   // DR1344: If a default argument is added outside a class definition and that
637   // default argument makes the function a special member function, the program
638   // is ill-formed. This can only happen for constructors.
639   if (isa<CXXConstructorDecl>(New) &&
640       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
641     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
642                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
643     if (NewSM != OldSM) {
644       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
645       assert(NewParam->hasDefaultArg());
646       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
647         << NewParam->getDefaultArgRange() << NewSM;
648       Diag(Old->getLocation(), diag::note_previous_declaration);
649     }
650   }
651 
652   const FunctionDecl *Def;
653   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
654   // template has a constexpr specifier then all its declarations shall
655   // contain the constexpr specifier.
656   if (New->getConstexprKind() != Old->getConstexprKind()) {
657     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
658         << New << static_cast<int>(New->getConstexprKind())
659         << static_cast<int>(Old->getConstexprKind());
660     Diag(Old->getLocation(), diag::note_previous_declaration);
661     Invalid = true;
662   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
663              Old->isDefined(Def) &&
664              // If a friend function is inlined but does not have 'inline'
665              // specifier, it is a definition. Do not report attribute conflict
666              // in this case, redefinition will be diagnosed later.
667              (New->isInlineSpecified() ||
668               New->getFriendObjectKind() == Decl::FOK_None)) {
669     // C++11 [dcl.fcn.spec]p4:
670     //   If the definition of a function appears in a translation unit before its
671     //   first declaration as inline, the program is ill-formed.
672     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
673     Diag(Def->getLocation(), diag::note_previous_definition);
674     Invalid = true;
675   }
676 
677   // C++17 [temp.deduct.guide]p3:
678   //   Two deduction guide declarations in the same translation unit
679   //   for the same class template shall not have equivalent
680   //   parameter-declaration-clauses.
681   if (isa<CXXDeductionGuideDecl>(New) &&
682       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
683     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
684     Diag(Old->getLocation(), diag::note_previous_declaration);
685   }
686 
687   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
688   // argument expression, that declaration shall be a definition and shall be
689   // the only declaration of the function or function template in the
690   // translation unit.
691   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
692       functionDeclHasDefaultArgument(Old)) {
693     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
694     Diag(Old->getLocation(), diag::note_previous_declaration);
695     Invalid = true;
696   }
697 
698   // C++11 [temp.friend]p4 (DR329):
699   //   When a function is defined in a friend function declaration in a class
700   //   template, the function is instantiated when the function is odr-used.
701   //   The same restrictions on multiple declarations and definitions that
702   //   apply to non-template function declarations and definitions also apply
703   //   to these implicit definitions.
704   const FunctionDecl *OldDefinition = nullptr;
705   if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
706       Old->isDefined(OldDefinition, true))
707     CheckForFunctionRedefinition(New, OldDefinition);
708 
709   return Invalid;
710 }
711 
712 NamedDecl *
713 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
714                                    MultiTemplateParamsArg TemplateParamLists) {
715   assert(D.isDecompositionDeclarator());
716   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
717 
718   // The syntax only allows a decomposition declarator as a simple-declaration,
719   // a for-range-declaration, or a condition in Clang, but we parse it in more
720   // cases than that.
721   if (!D.mayHaveDecompositionDeclarator()) {
722     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
723       << Decomp.getSourceRange();
724     return nullptr;
725   }
726 
727   if (!TemplateParamLists.empty()) {
728     // FIXME: There's no rule against this, but there are also no rules that
729     // would actually make it usable, so we reject it for now.
730     Diag(TemplateParamLists.front()->getTemplateLoc(),
731          diag::err_decomp_decl_template);
732     return nullptr;
733   }
734 
735   Diag(Decomp.getLSquareLoc(),
736        !getLangOpts().CPlusPlus17
737            ? diag::ext_decomp_decl
738            : D.getContext() == DeclaratorContext::Condition
739                  ? diag::ext_decomp_decl_cond
740                  : diag::warn_cxx14_compat_decomp_decl)
741       << Decomp.getSourceRange();
742 
743   // The semantic context is always just the current context.
744   DeclContext *const DC = CurContext;
745 
746   // C++17 [dcl.dcl]/8:
747   //   The decl-specifier-seq shall contain only the type-specifier auto
748   //   and cv-qualifiers.
749   // C++2a [dcl.dcl]/8:
750   //   If decl-specifier-seq contains any decl-specifier other than static,
751   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
752   auto &DS = D.getDeclSpec();
753   {
754     SmallVector<StringRef, 8> BadSpecifiers;
755     SmallVector<SourceLocation, 8> BadSpecifierLocs;
756     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
757     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
758     if (auto SCS = DS.getStorageClassSpec()) {
759       if (SCS == DeclSpec::SCS_static) {
760         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
761         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
762       } else {
763         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
764         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
765       }
766     }
767     if (auto TSCS = DS.getThreadStorageClassSpec()) {
768       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
769       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
770     }
771     if (DS.hasConstexprSpecifier()) {
772       BadSpecifiers.push_back(
773           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
774       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
775     }
776     if (DS.isInlineSpecified()) {
777       BadSpecifiers.push_back("inline");
778       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
779     }
780     if (!BadSpecifiers.empty()) {
781       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
782       Err << (int)BadSpecifiers.size()
783           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
784       // Don't add FixItHints to remove the specifiers; we do still respect
785       // them when building the underlying variable.
786       for (auto Loc : BadSpecifierLocs)
787         Err << SourceRange(Loc, Loc);
788     } else if (!CPlusPlus20Specifiers.empty()) {
789       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
790                          getLangOpts().CPlusPlus20
791                              ? diag::warn_cxx17_compat_decomp_decl_spec
792                              : diag::ext_decomp_decl_spec);
793       Warn << (int)CPlusPlus20Specifiers.size()
794            << llvm::join(CPlusPlus20Specifiers.begin(),
795                          CPlusPlus20Specifiers.end(), " ");
796       for (auto Loc : CPlusPlus20SpecifierLocs)
797         Warn << SourceRange(Loc, Loc);
798     }
799     // We can't recover from it being declared as a typedef.
800     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
801       return nullptr;
802   }
803 
804   // C++2a [dcl.struct.bind]p1:
805   //   A cv that includes volatile is deprecated
806   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
807       getLangOpts().CPlusPlus20)
808     Diag(DS.getVolatileSpecLoc(),
809          diag::warn_deprecated_volatile_structured_binding);
810 
811   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
812   QualType R = TInfo->getType();
813 
814   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
815                                       UPPC_DeclarationType))
816     D.setInvalidType();
817 
818   // The syntax only allows a single ref-qualifier prior to the decomposition
819   // declarator. No other declarator chunks are permitted. Also check the type
820   // specifier here.
821   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
822       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
823       (D.getNumTypeObjects() == 1 &&
824        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
825     Diag(Decomp.getLSquareLoc(),
826          (D.hasGroupingParens() ||
827           (D.getNumTypeObjects() &&
828            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
829              ? diag::err_decomp_decl_parens
830              : diag::err_decomp_decl_type)
831         << R;
832 
833     // In most cases, there's no actual problem with an explicitly-specified
834     // type, but a function type won't work here, and ActOnVariableDeclarator
835     // shouldn't be called for such a type.
836     if (R->isFunctionType())
837       D.setInvalidType();
838   }
839 
840   // Build the BindingDecls.
841   SmallVector<BindingDecl*, 8> Bindings;
842 
843   // Build the BindingDecls.
844   for (auto &B : D.getDecompositionDeclarator().bindings()) {
845     // Check for name conflicts.
846     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
847     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
848                           ForVisibleRedeclaration);
849     LookupName(Previous, S,
850                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
851 
852     // It's not permitted to shadow a template parameter name.
853     if (Previous.isSingleResult() &&
854         Previous.getFoundDecl()->isTemplateParameter()) {
855       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
856                                       Previous.getFoundDecl());
857       Previous.clear();
858     }
859 
860     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
861                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
862     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
863                          /*AllowInlineNamespace*/false);
864     if (!Previous.empty()) {
865       auto *Old = Previous.getRepresentativeDecl();
866       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
867       Diag(Old->getLocation(), diag::note_previous_definition);
868     }
869 
870     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
871     PushOnScopeChains(BD, S, true);
872     Bindings.push_back(BD);
873     ParsingInitForAutoVars.insert(BD);
874   }
875 
876   // There are no prior lookup results for the variable itself, because it
877   // is unnamed.
878   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
879                                Decomp.getLSquareLoc());
880   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
881                         ForVisibleRedeclaration);
882 
883   // Build the variable that holds the non-decomposed object.
884   bool AddToScope = true;
885   NamedDecl *New =
886       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
887                               MultiTemplateParamsArg(), AddToScope, Bindings);
888   if (AddToScope) {
889     S->AddDecl(New);
890     CurContext->addHiddenDecl(New);
891   }
892 
893   if (isInOpenMPDeclareTargetContext())
894     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
895 
896   return New;
897 }
898 
899 static bool checkSimpleDecomposition(
900     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
901     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
902     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
903   if ((int64_t)Bindings.size() != NumElems) {
904     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
905         << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
906         << (NumElems < Bindings.size());
907     return true;
908   }
909 
910   unsigned I = 0;
911   for (auto *B : Bindings) {
912     SourceLocation Loc = B->getLocation();
913     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
914     if (E.isInvalid())
915       return true;
916     E = GetInit(Loc, E.get(), I++);
917     if (E.isInvalid())
918       return true;
919     B->setBinding(ElemType, E.get());
920   }
921 
922   return false;
923 }
924 
925 static bool checkArrayLikeDecomposition(Sema &S,
926                                         ArrayRef<BindingDecl *> Bindings,
927                                         ValueDecl *Src, QualType DecompType,
928                                         const llvm::APSInt &NumElems,
929                                         QualType ElemType) {
930   return checkSimpleDecomposition(
931       S, Bindings, Src, DecompType, NumElems, ElemType,
932       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
933         ExprResult E = S.ActOnIntegerConstant(Loc, I);
934         if (E.isInvalid())
935           return ExprError();
936         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
937       });
938 }
939 
940 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
941                                     ValueDecl *Src, QualType DecompType,
942                                     const ConstantArrayType *CAT) {
943   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
944                                      llvm::APSInt(CAT->getSize()),
945                                      CAT->getElementType());
946 }
947 
948 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
949                                      ValueDecl *Src, QualType DecompType,
950                                      const VectorType *VT) {
951   return checkArrayLikeDecomposition(
952       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
953       S.Context.getQualifiedType(VT->getElementType(),
954                                  DecompType.getQualifiers()));
955 }
956 
957 static bool checkComplexDecomposition(Sema &S,
958                                       ArrayRef<BindingDecl *> Bindings,
959                                       ValueDecl *Src, QualType DecompType,
960                                       const ComplexType *CT) {
961   return checkSimpleDecomposition(
962       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
963       S.Context.getQualifiedType(CT->getElementType(),
964                                  DecompType.getQualifiers()),
965       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
966         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
967       });
968 }
969 
970 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
971                                      TemplateArgumentListInfo &Args) {
972   SmallString<128> SS;
973   llvm::raw_svector_ostream OS(SS);
974   bool First = true;
975   for (auto &Arg : Args.arguments()) {
976     if (!First)
977       OS << ", ";
978     Arg.getArgument().print(PrintingPolicy, OS);
979     First = false;
980   }
981   return std::string(OS.str());
982 }
983 
984 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
985                                      SourceLocation Loc, StringRef Trait,
986                                      TemplateArgumentListInfo &Args,
987                                      unsigned DiagID) {
988   auto DiagnoseMissing = [&] {
989     if (DiagID)
990       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
991                                                Args);
992     return true;
993   };
994 
995   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
996   NamespaceDecl *Std = S.getStdNamespace();
997   if (!Std)
998     return DiagnoseMissing();
999 
1000   // Look up the trait itself, within namespace std. We can diagnose various
1001   // problems with this lookup even if we've been asked to not diagnose a
1002   // missing specialization, because this can only fail if the user has been
1003   // declaring their own names in namespace std or we don't support the
1004   // standard library implementation in use.
1005   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1006                       Loc, Sema::LookupOrdinaryName);
1007   if (!S.LookupQualifiedName(Result, Std))
1008     return DiagnoseMissing();
1009   if (Result.isAmbiguous())
1010     return true;
1011 
1012   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1013   if (!TraitTD) {
1014     Result.suppressDiagnostics();
1015     NamedDecl *Found = *Result.begin();
1016     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1017     S.Diag(Found->getLocation(), diag::note_declared_at);
1018     return true;
1019   }
1020 
1021   // Build the template-id.
1022   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1023   if (TraitTy.isNull())
1024     return true;
1025   if (!S.isCompleteType(Loc, TraitTy)) {
1026     if (DiagID)
1027       S.RequireCompleteType(
1028           Loc, TraitTy, DiagID,
1029           printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1030     return true;
1031   }
1032 
1033   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1034   assert(RD && "specialization of class template is not a class?");
1035 
1036   // Look up the member of the trait type.
1037   S.LookupQualifiedName(TraitMemberLookup, RD);
1038   return TraitMemberLookup.isAmbiguous();
1039 }
1040 
1041 static TemplateArgumentLoc
1042 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1043                                    uint64_t I) {
1044   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1045   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1046 }
1047 
1048 static TemplateArgumentLoc
1049 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1050   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1051 }
1052 
1053 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1054 
1055 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1056                                llvm::APSInt &Size) {
1057   EnterExpressionEvaluationContext ContextRAII(
1058       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1059 
1060   DeclarationName Value = S.PP.getIdentifierInfo("value");
1061   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1062 
1063   // Form template argument list for tuple_size<T>.
1064   TemplateArgumentListInfo Args(Loc, Loc);
1065   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1066 
1067   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1068   // it's not tuple-like.
1069   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1070       R.empty())
1071     return IsTupleLike::NotTupleLike;
1072 
1073   // If we get this far, we've committed to the tuple interpretation, but
1074   // we can still fail if there actually isn't a usable ::value.
1075 
1076   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1077     LookupResult &R;
1078     TemplateArgumentListInfo &Args;
1079     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1080         : R(R), Args(Args) {}
1081     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1082                                                SourceLocation Loc) override {
1083       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1084           << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1085     }
1086   } Diagnoser(R, Args);
1087 
1088   ExprResult E =
1089       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1090   if (E.isInvalid())
1091     return IsTupleLike::Error;
1092 
1093   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1094   if (E.isInvalid())
1095     return IsTupleLike::Error;
1096 
1097   return IsTupleLike::TupleLike;
1098 }
1099 
1100 /// \return std::tuple_element<I, T>::type.
1101 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1102                                         unsigned I, QualType T) {
1103   // Form template argument list for tuple_element<I, T>.
1104   TemplateArgumentListInfo Args(Loc, Loc);
1105   Args.addArgument(
1106       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1107   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1108 
1109   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1110   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1111   if (lookupStdTypeTraitMember(
1112           S, R, Loc, "tuple_element", Args,
1113           diag::err_decomp_decl_std_tuple_element_not_specialized))
1114     return QualType();
1115 
1116   auto *TD = R.getAsSingle<TypeDecl>();
1117   if (!TD) {
1118     R.suppressDiagnostics();
1119     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1120       << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1121     if (!R.empty())
1122       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1123     return QualType();
1124   }
1125 
1126   return S.Context.getTypeDeclType(TD);
1127 }
1128 
1129 namespace {
1130 struct InitializingBinding {
1131   Sema &S;
1132   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1133     Sema::CodeSynthesisContext Ctx;
1134     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1135     Ctx.PointOfInstantiation = BD->getLocation();
1136     Ctx.Entity = BD;
1137     S.pushCodeSynthesisContext(Ctx);
1138   }
1139   ~InitializingBinding() {
1140     S.popCodeSynthesisContext();
1141   }
1142 };
1143 }
1144 
1145 static bool checkTupleLikeDecomposition(Sema &S,
1146                                         ArrayRef<BindingDecl *> Bindings,
1147                                         VarDecl *Src, QualType DecompType,
1148                                         const llvm::APSInt &TupleSize) {
1149   if ((int64_t)Bindings.size() != TupleSize) {
1150     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1151         << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1152         << (TupleSize < Bindings.size());
1153     return true;
1154   }
1155 
1156   if (Bindings.empty())
1157     return false;
1158 
1159   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1160 
1161   // [dcl.decomp]p3:
1162   //   The unqualified-id get is looked up in the scope of E by class member
1163   //   access lookup ...
1164   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1165   bool UseMemberGet = false;
1166   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1167     if (auto *RD = DecompType->getAsCXXRecordDecl())
1168       S.LookupQualifiedName(MemberGet, RD);
1169     if (MemberGet.isAmbiguous())
1170       return true;
1171     //   ... and if that finds at least one declaration that is a function
1172     //   template whose first template parameter is a non-type parameter ...
1173     for (NamedDecl *D : MemberGet) {
1174       if (FunctionTemplateDecl *FTD =
1175               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1176         TemplateParameterList *TPL = FTD->getTemplateParameters();
1177         if (TPL->size() != 0 &&
1178             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1179           //   ... the initializer is e.get<i>().
1180           UseMemberGet = true;
1181           break;
1182         }
1183       }
1184     }
1185   }
1186 
1187   unsigned I = 0;
1188   for (auto *B : Bindings) {
1189     InitializingBinding InitContext(S, B);
1190     SourceLocation Loc = B->getLocation();
1191 
1192     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1193     if (E.isInvalid())
1194       return true;
1195 
1196     //   e is an lvalue if the type of the entity is an lvalue reference and
1197     //   an xvalue otherwise
1198     if (!Src->getType()->isLValueReferenceType())
1199       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1200                                    E.get(), nullptr, VK_XValue,
1201                                    FPOptionsOverride());
1202 
1203     TemplateArgumentListInfo Args(Loc, Loc);
1204     Args.addArgument(
1205         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1206 
1207     if (UseMemberGet) {
1208       //   if [lookup of member get] finds at least one declaration, the
1209       //   initializer is e.get<i-1>().
1210       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1211                                      CXXScopeSpec(), SourceLocation(), nullptr,
1212                                      MemberGet, &Args, nullptr);
1213       if (E.isInvalid())
1214         return true;
1215 
1216       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1217     } else {
1218       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1219       //   in the associated namespaces.
1220       Expr *Get = UnresolvedLookupExpr::Create(
1221           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1222           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1223           UnresolvedSetIterator(), UnresolvedSetIterator());
1224 
1225       Expr *Arg = E.get();
1226       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1227     }
1228     if (E.isInvalid())
1229       return true;
1230     Expr *Init = E.get();
1231 
1232     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1233     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1234     if (T.isNull())
1235       return true;
1236 
1237     //   each vi is a variable of type "reference to T" initialized with the
1238     //   initializer, where the reference is an lvalue reference if the
1239     //   initializer is an lvalue and an rvalue reference otherwise
1240     QualType RefType =
1241         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1242     if (RefType.isNull())
1243       return true;
1244     auto *RefVD = VarDecl::Create(
1245         S.Context, Src->getDeclContext(), Loc, Loc,
1246         B->getDeclName().getAsIdentifierInfo(), RefType,
1247         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1248     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1249     RefVD->setTSCSpec(Src->getTSCSpec());
1250     RefVD->setImplicit();
1251     if (Src->isInlineSpecified())
1252       RefVD->setInlineSpecified();
1253     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1254 
1255     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1256     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1257     InitializationSequence Seq(S, Entity, Kind, Init);
1258     E = Seq.Perform(S, Entity, Kind, Init);
1259     if (E.isInvalid())
1260       return true;
1261     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1262     if (E.isInvalid())
1263       return true;
1264     RefVD->setInit(E.get());
1265     S.CheckCompleteVariableDeclaration(RefVD);
1266 
1267     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1268                                    DeclarationNameInfo(B->getDeclName(), Loc),
1269                                    RefVD);
1270     if (E.isInvalid())
1271       return true;
1272 
1273     B->setBinding(T, E.get());
1274     I++;
1275   }
1276 
1277   return false;
1278 }
1279 
1280 /// Find the base class to decompose in a built-in decomposition of a class type.
1281 /// This base class search is, unfortunately, not quite like any other that we
1282 /// perform anywhere else in C++.
1283 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1284                                                 const CXXRecordDecl *RD,
1285                                                 CXXCastPath &BasePath) {
1286   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1287                           CXXBasePath &Path) {
1288     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1289   };
1290 
1291   const CXXRecordDecl *ClassWithFields = nullptr;
1292   AccessSpecifier AS = AS_public;
1293   if (RD->hasDirectFields())
1294     // [dcl.decomp]p4:
1295     //   Otherwise, all of E's non-static data members shall be public direct
1296     //   members of E ...
1297     ClassWithFields = RD;
1298   else {
1299     //   ... or of ...
1300     CXXBasePaths Paths;
1301     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1302     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1303       // If no classes have fields, just decompose RD itself. (This will work
1304       // if and only if zero bindings were provided.)
1305       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1306     }
1307 
1308     CXXBasePath *BestPath = nullptr;
1309     for (auto &P : Paths) {
1310       if (!BestPath)
1311         BestPath = &P;
1312       else if (!S.Context.hasSameType(P.back().Base->getType(),
1313                                       BestPath->back().Base->getType())) {
1314         //   ... the same ...
1315         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1316           << false << RD << BestPath->back().Base->getType()
1317           << P.back().Base->getType();
1318         return DeclAccessPair();
1319       } else if (P.Access < BestPath->Access) {
1320         BestPath = &P;
1321       }
1322     }
1323 
1324     //   ... unambiguous ...
1325     QualType BaseType = BestPath->back().Base->getType();
1326     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1327       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1328         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1329       return DeclAccessPair();
1330     }
1331 
1332     //   ... [accessible, implied by other rules] base class of E.
1333     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1334                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1335     AS = BestPath->Access;
1336 
1337     ClassWithFields = BaseType->getAsCXXRecordDecl();
1338     S.BuildBasePathArray(Paths, BasePath);
1339   }
1340 
1341   // The above search did not check whether the selected class itself has base
1342   // classes with fields, so check that now.
1343   CXXBasePaths Paths;
1344   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1345     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1346       << (ClassWithFields == RD) << RD << ClassWithFields
1347       << Paths.front().back().Base->getType();
1348     return DeclAccessPair();
1349   }
1350 
1351   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1352 }
1353 
1354 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1355                                      ValueDecl *Src, QualType DecompType,
1356                                      const CXXRecordDecl *OrigRD) {
1357   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1358                             diag::err_incomplete_type))
1359     return true;
1360 
1361   CXXCastPath BasePath;
1362   DeclAccessPair BasePair =
1363       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1364   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1365   if (!RD)
1366     return true;
1367   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1368                                                  DecompType.getQualifiers());
1369 
1370   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1371     unsigned NumFields =
1372         std::count_if(RD->field_begin(), RD->field_end(),
1373                       [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1374     assert(Bindings.size() != NumFields);
1375     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1376         << DecompType << (unsigned)Bindings.size() << NumFields
1377         << (NumFields < Bindings.size());
1378     return true;
1379   };
1380 
1381   //   all of E's non-static data members shall be [...] well-formed
1382   //   when named as e.name in the context of the structured binding,
1383   //   E shall not have an anonymous union member, ...
1384   unsigned I = 0;
1385   for (auto *FD : RD->fields()) {
1386     if (FD->isUnnamedBitfield())
1387       continue;
1388 
1389     // All the non-static data members are required to be nameable, so they
1390     // must all have names.
1391     if (!FD->getDeclName()) {
1392       if (RD->isLambda()) {
1393         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1394         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1395         return true;
1396       }
1397 
1398       if (FD->isAnonymousStructOrUnion()) {
1399         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1400           << DecompType << FD->getType()->isUnionType();
1401         S.Diag(FD->getLocation(), diag::note_declared_at);
1402         return true;
1403       }
1404 
1405       // FIXME: Are there any other ways we could have an anonymous member?
1406     }
1407 
1408     // We have a real field to bind.
1409     if (I >= Bindings.size())
1410       return DiagnoseBadNumberOfBindings();
1411     auto *B = Bindings[I++];
1412     SourceLocation Loc = B->getLocation();
1413 
1414     // The field must be accessible in the context of the structured binding.
1415     // We already checked that the base class is accessible.
1416     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1417     // const_cast here.
1418     S.CheckStructuredBindingMemberAccess(
1419         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1420         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1421                                      BasePair.getAccess(), FD->getAccess())));
1422 
1423     // Initialize the binding to Src.FD.
1424     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1425     if (E.isInvalid())
1426       return true;
1427     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1428                             VK_LValue, &BasePath);
1429     if (E.isInvalid())
1430       return true;
1431     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1432                                   CXXScopeSpec(), FD,
1433                                   DeclAccessPair::make(FD, FD->getAccess()),
1434                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1435     if (E.isInvalid())
1436       return true;
1437 
1438     // If the type of the member is T, the referenced type is cv T, where cv is
1439     // the cv-qualification of the decomposition expression.
1440     //
1441     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1442     // 'const' to the type of the field.
1443     Qualifiers Q = DecompType.getQualifiers();
1444     if (FD->isMutable())
1445       Q.removeConst();
1446     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1447   }
1448 
1449   if (I != Bindings.size())
1450     return DiagnoseBadNumberOfBindings();
1451 
1452   return false;
1453 }
1454 
1455 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1456   QualType DecompType = DD->getType();
1457 
1458   // If the type of the decomposition is dependent, then so is the type of
1459   // each binding.
1460   if (DecompType->isDependentType()) {
1461     for (auto *B : DD->bindings())
1462       B->setType(Context.DependentTy);
1463     return;
1464   }
1465 
1466   DecompType = DecompType.getNonReferenceType();
1467   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1468 
1469   // C++1z [dcl.decomp]/2:
1470   //   If E is an array type [...]
1471   // As an extension, we also support decomposition of built-in complex and
1472   // vector types.
1473   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1474     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1475       DD->setInvalidDecl();
1476     return;
1477   }
1478   if (auto *VT = DecompType->getAs<VectorType>()) {
1479     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1480       DD->setInvalidDecl();
1481     return;
1482   }
1483   if (auto *CT = DecompType->getAs<ComplexType>()) {
1484     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1485       DD->setInvalidDecl();
1486     return;
1487   }
1488 
1489   // C++1z [dcl.decomp]/3:
1490   //   if the expression std::tuple_size<E>::value is a well-formed integral
1491   //   constant expression, [...]
1492   llvm::APSInt TupleSize(32);
1493   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1494   case IsTupleLike::Error:
1495     DD->setInvalidDecl();
1496     return;
1497 
1498   case IsTupleLike::TupleLike:
1499     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1500       DD->setInvalidDecl();
1501     return;
1502 
1503   case IsTupleLike::NotTupleLike:
1504     break;
1505   }
1506 
1507   // C++1z [dcl.dcl]/8:
1508   //   [E shall be of array or non-union class type]
1509   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1510   if (!RD || RD->isUnion()) {
1511     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1512         << DD << !RD << DecompType;
1513     DD->setInvalidDecl();
1514     return;
1515   }
1516 
1517   // C++1z [dcl.decomp]/4:
1518   //   all of E's non-static data members shall be [...] direct members of
1519   //   E or of the same unambiguous public base class of E, ...
1520   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1521     DD->setInvalidDecl();
1522 }
1523 
1524 /// Merge the exception specifications of two variable declarations.
1525 ///
1526 /// This is called when there's a redeclaration of a VarDecl. The function
1527 /// checks if the redeclaration might have an exception specification and
1528 /// validates compatibility and merges the specs if necessary.
1529 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1530   // Shortcut if exceptions are disabled.
1531   if (!getLangOpts().CXXExceptions)
1532     return;
1533 
1534   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1535          "Should only be called if types are otherwise the same.");
1536 
1537   QualType NewType = New->getType();
1538   QualType OldType = Old->getType();
1539 
1540   // We're only interested in pointers and references to functions, as well
1541   // as pointers to member functions.
1542   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1543     NewType = R->getPointeeType();
1544     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1545   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1546     NewType = P->getPointeeType();
1547     OldType = OldType->castAs<PointerType>()->getPointeeType();
1548   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1549     NewType = M->getPointeeType();
1550     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1551   }
1552 
1553   if (!NewType->isFunctionProtoType())
1554     return;
1555 
1556   // There's lots of special cases for functions. For function pointers, system
1557   // libraries are hopefully not as broken so that we don't need these
1558   // workarounds.
1559   if (CheckEquivalentExceptionSpec(
1560         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1561         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1562     New->setInvalidDecl();
1563   }
1564 }
1565 
1566 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1567 /// function declaration are well-formed according to C++
1568 /// [dcl.fct.default].
1569 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1570   unsigned NumParams = FD->getNumParams();
1571   unsigned ParamIdx = 0;
1572 
1573   // This checking doesn't make sense for explicit specializations; their
1574   // default arguments are determined by the declaration we're specializing,
1575   // not by FD.
1576   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1577     return;
1578   if (auto *FTD = FD->getDescribedFunctionTemplate())
1579     if (FTD->isMemberSpecialization())
1580       return;
1581 
1582   // Find first parameter with a default argument
1583   for (; ParamIdx < NumParams; ++ParamIdx) {
1584     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1585     if (Param->hasDefaultArg())
1586       break;
1587   }
1588 
1589   // C++20 [dcl.fct.default]p4:
1590   //   In a given function declaration, each parameter subsequent to a parameter
1591   //   with a default argument shall have a default argument supplied in this or
1592   //   a previous declaration, unless the parameter was expanded from a
1593   //   parameter pack, or shall be a function parameter pack.
1594   for (; ParamIdx < NumParams; ++ParamIdx) {
1595     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1596     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1597         !(CurrentInstantiationScope &&
1598           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1599       if (Param->isInvalidDecl())
1600         /* We already complained about this parameter. */;
1601       else if (Param->getIdentifier())
1602         Diag(Param->getLocation(),
1603              diag::err_param_default_argument_missing_name)
1604           << Param->getIdentifier();
1605       else
1606         Diag(Param->getLocation(),
1607              diag::err_param_default_argument_missing);
1608     }
1609   }
1610 }
1611 
1612 /// Check that the given type is a literal type. Issue a diagnostic if not,
1613 /// if Kind is Diagnose.
1614 /// \return \c true if a problem has been found (and optionally diagnosed).
1615 template <typename... Ts>
1616 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1617                              SourceLocation Loc, QualType T, unsigned DiagID,
1618                              Ts &&...DiagArgs) {
1619   if (T->isDependentType())
1620     return false;
1621 
1622   switch (Kind) {
1623   case Sema::CheckConstexprKind::Diagnose:
1624     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1625                                       std::forward<Ts>(DiagArgs)...);
1626 
1627   case Sema::CheckConstexprKind::CheckValid:
1628     return !T->isLiteralType(SemaRef.Context);
1629   }
1630 
1631   llvm_unreachable("unknown CheckConstexprKind");
1632 }
1633 
1634 /// Determine whether a destructor cannot be constexpr due to
1635 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1636                                                const CXXDestructorDecl *DD,
1637                                                Sema::CheckConstexprKind Kind) {
1638   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1639     const CXXRecordDecl *RD =
1640         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1641     if (!RD || RD->hasConstexprDestructor())
1642       return true;
1643 
1644     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1645       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1646           << static_cast<int>(DD->getConstexprKind()) << !FD
1647           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1648       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1649           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1650     }
1651     return false;
1652   };
1653 
1654   const CXXRecordDecl *RD = DD->getParent();
1655   for (const CXXBaseSpecifier &B : RD->bases())
1656     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1657       return false;
1658   for (const FieldDecl *FD : RD->fields())
1659     if (!Check(FD->getLocation(), FD->getType(), FD))
1660       return false;
1661   return true;
1662 }
1663 
1664 /// Check whether a function's parameter types are all literal types. If so,
1665 /// return true. If not, produce a suitable diagnostic and return false.
1666 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1667                                          const FunctionDecl *FD,
1668                                          Sema::CheckConstexprKind Kind) {
1669   unsigned ArgIndex = 0;
1670   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1671   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1672                                               e = FT->param_type_end();
1673        i != e; ++i, ++ArgIndex) {
1674     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1675     SourceLocation ParamLoc = PD->getLocation();
1676     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1677                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1678                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1679                          FD->isConsteval()))
1680       return false;
1681   }
1682   return true;
1683 }
1684 
1685 /// Check whether a function's return type is a literal type. If so, return
1686 /// true. If not, produce a suitable diagnostic and return false.
1687 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1688                                      Sema::CheckConstexprKind Kind) {
1689   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1690                        diag::err_constexpr_non_literal_return,
1691                        FD->isConsteval()))
1692     return false;
1693   return true;
1694 }
1695 
1696 /// Get diagnostic %select index for tag kind for
1697 /// record diagnostic message.
1698 /// WARNING: Indexes apply to particular diagnostics only!
1699 ///
1700 /// \returns diagnostic %select index.
1701 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1702   switch (Tag) {
1703   case TTK_Struct: return 0;
1704   case TTK_Interface: return 1;
1705   case TTK_Class:  return 2;
1706   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1707   }
1708 }
1709 
1710 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1711                                        Stmt *Body,
1712                                        Sema::CheckConstexprKind Kind);
1713 
1714 // Check whether a function declaration satisfies the requirements of a
1715 // constexpr function definition or a constexpr constructor definition. If so,
1716 // return true. If not, produce appropriate diagnostics (unless asked not to by
1717 // Kind) and return false.
1718 //
1719 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1720 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1721                                             CheckConstexprKind Kind) {
1722   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1723   if (MD && MD->isInstance()) {
1724     // C++11 [dcl.constexpr]p4:
1725     //  The definition of a constexpr constructor shall satisfy the following
1726     //  constraints:
1727     //  - the class shall not have any virtual base classes;
1728     //
1729     // FIXME: This only applies to constructors and destructors, not arbitrary
1730     // member functions.
1731     const CXXRecordDecl *RD = MD->getParent();
1732     if (RD->getNumVBases()) {
1733       if (Kind == CheckConstexprKind::CheckValid)
1734         return false;
1735 
1736       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1737         << isa<CXXConstructorDecl>(NewFD)
1738         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1739       for (const auto &I : RD->vbases())
1740         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1741             << I.getSourceRange();
1742       return false;
1743     }
1744   }
1745 
1746   if (!isa<CXXConstructorDecl>(NewFD)) {
1747     // C++11 [dcl.constexpr]p3:
1748     //  The definition of a constexpr function shall satisfy the following
1749     //  constraints:
1750     // - it shall not be virtual; (removed in C++20)
1751     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1752     if (Method && Method->isVirtual()) {
1753       if (getLangOpts().CPlusPlus20) {
1754         if (Kind == CheckConstexprKind::Diagnose)
1755           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1756       } else {
1757         if (Kind == CheckConstexprKind::CheckValid)
1758           return false;
1759 
1760         Method = Method->getCanonicalDecl();
1761         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1762 
1763         // If it's not obvious why this function is virtual, find an overridden
1764         // function which uses the 'virtual' keyword.
1765         const CXXMethodDecl *WrittenVirtual = Method;
1766         while (!WrittenVirtual->isVirtualAsWritten())
1767           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1768         if (WrittenVirtual != Method)
1769           Diag(WrittenVirtual->getLocation(),
1770                diag::note_overridden_virtual_function);
1771         return false;
1772       }
1773     }
1774 
1775     // - its return type shall be a literal type;
1776     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1777       return false;
1778   }
1779 
1780   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1781     // A destructor can be constexpr only if the defaulted destructor could be;
1782     // we don't need to check the members and bases if we already know they all
1783     // have constexpr destructors.
1784     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1785       if (Kind == CheckConstexprKind::CheckValid)
1786         return false;
1787       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1788         return false;
1789     }
1790   }
1791 
1792   // - each of its parameter types shall be a literal type;
1793   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1794     return false;
1795 
1796   Stmt *Body = NewFD->getBody();
1797   assert(Body &&
1798          "CheckConstexprFunctionDefinition called on function with no body");
1799   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1800 }
1801 
1802 /// Check the given declaration statement is legal within a constexpr function
1803 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1804 ///
1805 /// \return true if the body is OK (maybe only as an extension), false if we
1806 ///         have diagnosed a problem.
1807 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1808                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1809                                    Sema::CheckConstexprKind Kind) {
1810   // C++11 [dcl.constexpr]p3 and p4:
1811   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1812   //  contain only
1813   for (const auto *DclIt : DS->decls()) {
1814     switch (DclIt->getKind()) {
1815     case Decl::StaticAssert:
1816     case Decl::Using:
1817     case Decl::UsingShadow:
1818     case Decl::UsingDirective:
1819     case Decl::UnresolvedUsingTypename:
1820     case Decl::UnresolvedUsingValue:
1821       //   - static_assert-declarations
1822       //   - using-declarations,
1823       //   - using-directives,
1824       continue;
1825 
1826     case Decl::Typedef:
1827     case Decl::TypeAlias: {
1828       //   - typedef declarations and alias-declarations that do not define
1829       //     classes or enumerations,
1830       const auto *TN = cast<TypedefNameDecl>(DclIt);
1831       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1832         // Don't allow variably-modified types in constexpr functions.
1833         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1834           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1835           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1836             << TL.getSourceRange() << TL.getType()
1837             << isa<CXXConstructorDecl>(Dcl);
1838         }
1839         return false;
1840       }
1841       continue;
1842     }
1843 
1844     case Decl::Enum:
1845     case Decl::CXXRecord:
1846       // C++1y allows types to be defined, not just declared.
1847       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1848         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1849           SemaRef.Diag(DS->getBeginLoc(),
1850                        SemaRef.getLangOpts().CPlusPlus14
1851                            ? diag::warn_cxx11_compat_constexpr_type_definition
1852                            : diag::ext_constexpr_type_definition)
1853               << isa<CXXConstructorDecl>(Dcl);
1854         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1855           return false;
1856         }
1857       }
1858       continue;
1859 
1860     case Decl::EnumConstant:
1861     case Decl::IndirectField:
1862     case Decl::ParmVar:
1863       // These can only appear with other declarations which are banned in
1864       // C++11 and permitted in C++1y, so ignore them.
1865       continue;
1866 
1867     case Decl::Var:
1868     case Decl::Decomposition: {
1869       // C++1y [dcl.constexpr]p3 allows anything except:
1870       //   a definition of a variable of non-literal type or of static or
1871       //   thread storage duration or [before C++2a] for which no
1872       //   initialization is performed.
1873       const auto *VD = cast<VarDecl>(DclIt);
1874       if (VD->isThisDeclarationADefinition()) {
1875         if (VD->isStaticLocal()) {
1876           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1877             SemaRef.Diag(VD->getLocation(),
1878                          diag::err_constexpr_local_var_static)
1879               << isa<CXXConstructorDecl>(Dcl)
1880               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1881           }
1882           return false;
1883         }
1884         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1885                              diag::err_constexpr_local_var_non_literal_type,
1886                              isa<CXXConstructorDecl>(Dcl)))
1887           return false;
1888         if (!VD->getType()->isDependentType() &&
1889             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1890           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1891             SemaRef.Diag(
1892                 VD->getLocation(),
1893                 SemaRef.getLangOpts().CPlusPlus20
1894                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1895                     : diag::ext_constexpr_local_var_no_init)
1896                 << isa<CXXConstructorDecl>(Dcl);
1897           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1898             return false;
1899           }
1900           continue;
1901         }
1902       }
1903       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1904         SemaRef.Diag(VD->getLocation(),
1905                      SemaRef.getLangOpts().CPlusPlus14
1906                       ? diag::warn_cxx11_compat_constexpr_local_var
1907                       : diag::ext_constexpr_local_var)
1908           << isa<CXXConstructorDecl>(Dcl);
1909       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1910         return false;
1911       }
1912       continue;
1913     }
1914 
1915     case Decl::NamespaceAlias:
1916     case Decl::Function:
1917       // These are disallowed in C++11 and permitted in C++1y. Allow them
1918       // everywhere as an extension.
1919       if (!Cxx1yLoc.isValid())
1920         Cxx1yLoc = DS->getBeginLoc();
1921       continue;
1922 
1923     default:
1924       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1925         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1926             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1927       }
1928       return false;
1929     }
1930   }
1931 
1932   return true;
1933 }
1934 
1935 /// Check that the given field is initialized within a constexpr constructor.
1936 ///
1937 /// \param Dcl The constexpr constructor being checked.
1938 /// \param Field The field being checked. This may be a member of an anonymous
1939 ///        struct or union nested within the class being checked.
1940 /// \param Inits All declarations, including anonymous struct/union members and
1941 ///        indirect members, for which any initialization was provided.
1942 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1943 ///        multiple notes for different members to the same error.
1944 /// \param Kind Whether we're diagnosing a constructor as written or determining
1945 ///        whether the formal requirements are satisfied.
1946 /// \return \c false if we're checking for validity and the constructor does
1947 ///         not satisfy the requirements on a constexpr constructor.
1948 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1949                                           const FunctionDecl *Dcl,
1950                                           FieldDecl *Field,
1951                                           llvm::SmallSet<Decl*, 16> &Inits,
1952                                           bool &Diagnosed,
1953                                           Sema::CheckConstexprKind Kind) {
1954   // In C++20 onwards, there's nothing to check for validity.
1955   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1956       SemaRef.getLangOpts().CPlusPlus20)
1957     return true;
1958 
1959   if (Field->isInvalidDecl())
1960     return true;
1961 
1962   if (Field->isUnnamedBitfield())
1963     return true;
1964 
1965   // Anonymous unions with no variant members and empty anonymous structs do not
1966   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1967   // indirect fields don't need initializing.
1968   if (Field->isAnonymousStructOrUnion() &&
1969       (Field->getType()->isUnionType()
1970            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1971            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1972     return true;
1973 
1974   if (!Inits.count(Field)) {
1975     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1976       if (!Diagnosed) {
1977         SemaRef.Diag(Dcl->getLocation(),
1978                      SemaRef.getLangOpts().CPlusPlus20
1979                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1980                          : diag::ext_constexpr_ctor_missing_init);
1981         Diagnosed = true;
1982       }
1983       SemaRef.Diag(Field->getLocation(),
1984                    diag::note_constexpr_ctor_missing_init);
1985     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1986       return false;
1987     }
1988   } else if (Field->isAnonymousStructOrUnion()) {
1989     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1990     for (auto *I : RD->fields())
1991       // If an anonymous union contains an anonymous struct of which any member
1992       // is initialized, all members must be initialized.
1993       if (!RD->isUnion() || Inits.count(I))
1994         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1995                                            Kind))
1996           return false;
1997   }
1998   return true;
1999 }
2000 
2001 /// Check the provided statement is allowed in a constexpr function
2002 /// definition.
2003 static bool
2004 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2005                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2006                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2007                            Sema::CheckConstexprKind Kind) {
2008   // - its function-body shall be [...] a compound-statement that contains only
2009   switch (S->getStmtClass()) {
2010   case Stmt::NullStmtClass:
2011     //   - null statements,
2012     return true;
2013 
2014   case Stmt::DeclStmtClass:
2015     //   - static_assert-declarations
2016     //   - using-declarations,
2017     //   - using-directives,
2018     //   - typedef declarations and alias-declarations that do not define
2019     //     classes or enumerations,
2020     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2021       return false;
2022     return true;
2023 
2024   case Stmt::ReturnStmtClass:
2025     //   - and exactly one return statement;
2026     if (isa<CXXConstructorDecl>(Dcl)) {
2027       // C++1y allows return statements in constexpr constructors.
2028       if (!Cxx1yLoc.isValid())
2029         Cxx1yLoc = S->getBeginLoc();
2030       return true;
2031     }
2032 
2033     ReturnStmts.push_back(S->getBeginLoc());
2034     return true;
2035 
2036   case Stmt::CompoundStmtClass: {
2037     // C++1y allows compound-statements.
2038     if (!Cxx1yLoc.isValid())
2039       Cxx1yLoc = S->getBeginLoc();
2040 
2041     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2042     for (auto *BodyIt : CompStmt->body()) {
2043       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2044                                       Cxx1yLoc, Cxx2aLoc, Kind))
2045         return false;
2046     }
2047     return true;
2048   }
2049 
2050   case Stmt::AttributedStmtClass:
2051     if (!Cxx1yLoc.isValid())
2052       Cxx1yLoc = S->getBeginLoc();
2053     return true;
2054 
2055   case Stmt::IfStmtClass: {
2056     // C++1y allows if-statements.
2057     if (!Cxx1yLoc.isValid())
2058       Cxx1yLoc = S->getBeginLoc();
2059 
2060     IfStmt *If = cast<IfStmt>(S);
2061     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2062                                     Cxx1yLoc, Cxx2aLoc, Kind))
2063       return false;
2064     if (If->getElse() &&
2065         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2066                                     Cxx1yLoc, Cxx2aLoc, Kind))
2067       return false;
2068     return true;
2069   }
2070 
2071   case Stmt::WhileStmtClass:
2072   case Stmt::DoStmtClass:
2073   case Stmt::ForStmtClass:
2074   case Stmt::CXXForRangeStmtClass:
2075   case Stmt::ContinueStmtClass:
2076     // C++1y allows all of these. We don't allow them as extensions in C++11,
2077     // because they don't make sense without variable mutation.
2078     if (!SemaRef.getLangOpts().CPlusPlus14)
2079       break;
2080     if (!Cxx1yLoc.isValid())
2081       Cxx1yLoc = S->getBeginLoc();
2082     for (Stmt *SubStmt : S->children())
2083       if (SubStmt &&
2084           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2085                                       Cxx1yLoc, Cxx2aLoc, Kind))
2086         return false;
2087     return true;
2088 
2089   case Stmt::SwitchStmtClass:
2090   case Stmt::CaseStmtClass:
2091   case Stmt::DefaultStmtClass:
2092   case Stmt::BreakStmtClass:
2093     // C++1y allows switch-statements, and since they don't need variable
2094     // mutation, we can reasonably allow them in C++11 as an extension.
2095     if (!Cxx1yLoc.isValid())
2096       Cxx1yLoc = S->getBeginLoc();
2097     for (Stmt *SubStmt : S->children())
2098       if (SubStmt &&
2099           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2100                                       Cxx1yLoc, Cxx2aLoc, Kind))
2101         return false;
2102     return true;
2103 
2104   case Stmt::GCCAsmStmtClass:
2105   case Stmt::MSAsmStmtClass:
2106     // C++2a allows inline assembly statements.
2107   case Stmt::CXXTryStmtClass:
2108     if (Cxx2aLoc.isInvalid())
2109       Cxx2aLoc = S->getBeginLoc();
2110     for (Stmt *SubStmt : S->children()) {
2111       if (SubStmt &&
2112           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2113                                       Cxx1yLoc, Cxx2aLoc, Kind))
2114         return false;
2115     }
2116     return true;
2117 
2118   case Stmt::CXXCatchStmtClass:
2119     // Do not bother checking the language mode (already covered by the
2120     // try block check).
2121     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2122                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2123                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2124       return false;
2125     return true;
2126 
2127   default:
2128     if (!isa<Expr>(S))
2129       break;
2130 
2131     // C++1y allows expression-statements.
2132     if (!Cxx1yLoc.isValid())
2133       Cxx1yLoc = S->getBeginLoc();
2134     return true;
2135   }
2136 
2137   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2138     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2139         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2140   }
2141   return false;
2142 }
2143 
2144 /// Check the body for the given constexpr function declaration only contains
2145 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2146 ///
2147 /// \return true if the body is OK, false if we have found or diagnosed a
2148 /// problem.
2149 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2150                                        Stmt *Body,
2151                                        Sema::CheckConstexprKind Kind) {
2152   SmallVector<SourceLocation, 4> ReturnStmts;
2153 
2154   if (isa<CXXTryStmt>(Body)) {
2155     // C++11 [dcl.constexpr]p3:
2156     //  The definition of a constexpr function shall satisfy the following
2157     //  constraints: [...]
2158     // - its function-body shall be = delete, = default, or a
2159     //   compound-statement
2160     //
2161     // C++11 [dcl.constexpr]p4:
2162     //  In the definition of a constexpr constructor, [...]
2163     // - its function-body shall not be a function-try-block;
2164     //
2165     // This restriction is lifted in C++2a, as long as inner statements also
2166     // apply the general constexpr rules.
2167     switch (Kind) {
2168     case Sema::CheckConstexprKind::CheckValid:
2169       if (!SemaRef.getLangOpts().CPlusPlus20)
2170         return false;
2171       break;
2172 
2173     case Sema::CheckConstexprKind::Diagnose:
2174       SemaRef.Diag(Body->getBeginLoc(),
2175            !SemaRef.getLangOpts().CPlusPlus20
2176                ? diag::ext_constexpr_function_try_block_cxx20
2177                : diag::warn_cxx17_compat_constexpr_function_try_block)
2178           << isa<CXXConstructorDecl>(Dcl);
2179       break;
2180     }
2181   }
2182 
2183   // - its function-body shall be [...] a compound-statement that contains only
2184   //   [... list of cases ...]
2185   //
2186   // Note that walking the children here is enough to properly check for
2187   // CompoundStmt and CXXTryStmt body.
2188   SourceLocation Cxx1yLoc, Cxx2aLoc;
2189   for (Stmt *SubStmt : Body->children()) {
2190     if (SubStmt &&
2191         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2192                                     Cxx1yLoc, Cxx2aLoc, Kind))
2193       return false;
2194   }
2195 
2196   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2197     // If this is only valid as an extension, report that we don't satisfy the
2198     // constraints of the current language.
2199     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2200         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2201       return false;
2202   } else if (Cxx2aLoc.isValid()) {
2203     SemaRef.Diag(Cxx2aLoc,
2204          SemaRef.getLangOpts().CPlusPlus20
2205            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2206            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2207       << isa<CXXConstructorDecl>(Dcl);
2208   } else if (Cxx1yLoc.isValid()) {
2209     SemaRef.Diag(Cxx1yLoc,
2210          SemaRef.getLangOpts().CPlusPlus14
2211            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2212            : diag::ext_constexpr_body_invalid_stmt)
2213       << isa<CXXConstructorDecl>(Dcl);
2214   }
2215 
2216   if (const CXXConstructorDecl *Constructor
2217         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2218     const CXXRecordDecl *RD = Constructor->getParent();
2219     // DR1359:
2220     // - every non-variant non-static data member and base class sub-object
2221     //   shall be initialized;
2222     // DR1460:
2223     // - if the class is a union having variant members, exactly one of them
2224     //   shall be initialized;
2225     if (RD->isUnion()) {
2226       if (Constructor->getNumCtorInitializers() == 0 &&
2227           RD->hasVariantMembers()) {
2228         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2229           SemaRef.Diag(
2230               Dcl->getLocation(),
2231               SemaRef.getLangOpts().CPlusPlus20
2232                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2233                   : diag::ext_constexpr_union_ctor_no_init);
2234         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2235           return false;
2236         }
2237       }
2238     } else if (!Constructor->isDependentContext() &&
2239                !Constructor->isDelegatingConstructor()) {
2240       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2241 
2242       // Skip detailed checking if we have enough initializers, and we would
2243       // allow at most one initializer per member.
2244       bool AnyAnonStructUnionMembers = false;
2245       unsigned Fields = 0;
2246       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2247            E = RD->field_end(); I != E; ++I, ++Fields) {
2248         if (I->isAnonymousStructOrUnion()) {
2249           AnyAnonStructUnionMembers = true;
2250           break;
2251         }
2252       }
2253       // DR1460:
2254       // - if the class is a union-like class, but is not a union, for each of
2255       //   its anonymous union members having variant members, exactly one of
2256       //   them shall be initialized;
2257       if (AnyAnonStructUnionMembers ||
2258           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2259         // Check initialization of non-static data members. Base classes are
2260         // always initialized so do not need to be checked. Dependent bases
2261         // might not have initializers in the member initializer list.
2262         llvm::SmallSet<Decl*, 16> Inits;
2263         for (const auto *I: Constructor->inits()) {
2264           if (FieldDecl *FD = I->getMember())
2265             Inits.insert(FD);
2266           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2267             Inits.insert(ID->chain_begin(), ID->chain_end());
2268         }
2269 
2270         bool Diagnosed = false;
2271         for (auto *I : RD->fields())
2272           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2273                                              Kind))
2274             return false;
2275       }
2276     }
2277   } else {
2278     if (ReturnStmts.empty()) {
2279       // C++1y doesn't require constexpr functions to contain a 'return'
2280       // statement. We still do, unless the return type might be void, because
2281       // otherwise if there's no return statement, the function cannot
2282       // be used in a core constant expression.
2283       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2284                 (Dcl->getReturnType()->isVoidType() ||
2285                  Dcl->getReturnType()->isDependentType());
2286       switch (Kind) {
2287       case Sema::CheckConstexprKind::Diagnose:
2288         SemaRef.Diag(Dcl->getLocation(),
2289                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2290                         : diag::err_constexpr_body_no_return)
2291             << Dcl->isConsteval();
2292         if (!OK)
2293           return false;
2294         break;
2295 
2296       case Sema::CheckConstexprKind::CheckValid:
2297         // The formal requirements don't include this rule in C++14, even
2298         // though the "must be able to produce a constant expression" rules
2299         // still imply it in some cases.
2300         if (!SemaRef.getLangOpts().CPlusPlus14)
2301           return false;
2302         break;
2303       }
2304     } else if (ReturnStmts.size() > 1) {
2305       switch (Kind) {
2306       case Sema::CheckConstexprKind::Diagnose:
2307         SemaRef.Diag(
2308             ReturnStmts.back(),
2309             SemaRef.getLangOpts().CPlusPlus14
2310                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2311                 : diag::ext_constexpr_body_multiple_return);
2312         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2313           SemaRef.Diag(ReturnStmts[I],
2314                        diag::note_constexpr_body_previous_return);
2315         break;
2316 
2317       case Sema::CheckConstexprKind::CheckValid:
2318         if (!SemaRef.getLangOpts().CPlusPlus14)
2319           return false;
2320         break;
2321       }
2322     }
2323   }
2324 
2325   // C++11 [dcl.constexpr]p5:
2326   //   if no function argument values exist such that the function invocation
2327   //   substitution would produce a constant expression, the program is
2328   //   ill-formed; no diagnostic required.
2329   // C++11 [dcl.constexpr]p3:
2330   //   - every constructor call and implicit conversion used in initializing the
2331   //     return value shall be one of those allowed in a constant expression.
2332   // C++11 [dcl.constexpr]p4:
2333   //   - every constructor involved in initializing non-static data members and
2334   //     base class sub-objects shall be a constexpr constructor.
2335   //
2336   // Note that this rule is distinct from the "requirements for a constexpr
2337   // function", so is not checked in CheckValid mode.
2338   SmallVector<PartialDiagnosticAt, 8> Diags;
2339   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2340       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2341     SemaRef.Diag(Dcl->getLocation(),
2342                  diag::ext_constexpr_function_never_constant_expr)
2343         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2344     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2345       SemaRef.Diag(Diags[I].first, Diags[I].second);
2346     // Don't return false here: we allow this for compatibility in
2347     // system headers.
2348   }
2349 
2350   return true;
2351 }
2352 
2353 /// Get the class that is directly named by the current context. This is the
2354 /// class for which an unqualified-id in this scope could name a constructor
2355 /// or destructor.
2356 ///
2357 /// If the scope specifier denotes a class, this will be that class.
2358 /// If the scope specifier is empty, this will be the class whose
2359 /// member-specification we are currently within. Otherwise, there
2360 /// is no such class.
2361 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2362   assert(getLangOpts().CPlusPlus && "No class names in C!");
2363 
2364   if (SS && SS->isInvalid())
2365     return nullptr;
2366 
2367   if (SS && SS->isNotEmpty()) {
2368     DeclContext *DC = computeDeclContext(*SS, true);
2369     return dyn_cast_or_null<CXXRecordDecl>(DC);
2370   }
2371 
2372   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2373 }
2374 
2375 /// isCurrentClassName - Determine whether the identifier II is the
2376 /// name of the class type currently being defined. In the case of
2377 /// nested classes, this will only return true if II is the name of
2378 /// the innermost class.
2379 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2380                               const CXXScopeSpec *SS) {
2381   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2382   return CurDecl && &II == CurDecl->getIdentifier();
2383 }
2384 
2385 /// Determine whether the identifier II is a typo for the name of
2386 /// the class type currently being defined. If so, update it to the identifier
2387 /// that should have been used.
2388 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2389   assert(getLangOpts().CPlusPlus && "No class names in C!");
2390 
2391   if (!getLangOpts().SpellChecking)
2392     return false;
2393 
2394   CXXRecordDecl *CurDecl;
2395   if (SS && SS->isSet() && !SS->isInvalid()) {
2396     DeclContext *DC = computeDeclContext(*SS, true);
2397     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2398   } else
2399     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2400 
2401   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2402       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2403           < II->getLength()) {
2404     II = CurDecl->getIdentifier();
2405     return true;
2406   }
2407 
2408   return false;
2409 }
2410 
2411 /// Determine whether the given class is a base class of the given
2412 /// class, including looking at dependent bases.
2413 static bool findCircularInheritance(const CXXRecordDecl *Class,
2414                                     const CXXRecordDecl *Current) {
2415   SmallVector<const CXXRecordDecl*, 8> Queue;
2416 
2417   Class = Class->getCanonicalDecl();
2418   while (true) {
2419     for (const auto &I : Current->bases()) {
2420       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2421       if (!Base)
2422         continue;
2423 
2424       Base = Base->getDefinition();
2425       if (!Base)
2426         continue;
2427 
2428       if (Base->getCanonicalDecl() == Class)
2429         return true;
2430 
2431       Queue.push_back(Base);
2432     }
2433 
2434     if (Queue.empty())
2435       return false;
2436 
2437     Current = Queue.pop_back_val();
2438   }
2439 
2440   return false;
2441 }
2442 
2443 /// Check the validity of a C++ base class specifier.
2444 ///
2445 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2446 /// and returns NULL otherwise.
2447 CXXBaseSpecifier *
2448 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2449                          SourceRange SpecifierRange,
2450                          bool Virtual, AccessSpecifier Access,
2451                          TypeSourceInfo *TInfo,
2452                          SourceLocation EllipsisLoc) {
2453   QualType BaseType = TInfo->getType();
2454   if (BaseType->containsErrors()) {
2455     // Already emitted a diagnostic when parsing the error type.
2456     return nullptr;
2457   }
2458   // C++ [class.union]p1:
2459   //   A union shall not have base classes.
2460   if (Class->isUnion()) {
2461     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2462       << SpecifierRange;
2463     return nullptr;
2464   }
2465 
2466   if (EllipsisLoc.isValid() &&
2467       !TInfo->getType()->containsUnexpandedParameterPack()) {
2468     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2469       << TInfo->getTypeLoc().getSourceRange();
2470     EllipsisLoc = SourceLocation();
2471   }
2472 
2473   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2474 
2475   if (BaseType->isDependentType()) {
2476     // Make sure that we don't have circular inheritance among our dependent
2477     // bases. For non-dependent bases, the check for completeness below handles
2478     // this.
2479     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2480       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2481           ((BaseDecl = BaseDecl->getDefinition()) &&
2482            findCircularInheritance(Class, BaseDecl))) {
2483         Diag(BaseLoc, diag::err_circular_inheritance)
2484           << BaseType << Context.getTypeDeclType(Class);
2485 
2486         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2487           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2488             << BaseType;
2489 
2490         return nullptr;
2491       }
2492     }
2493 
2494     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2495                                           Class->getTagKind() == TTK_Class,
2496                                           Access, TInfo, EllipsisLoc);
2497   }
2498 
2499   // Base specifiers must be record types.
2500   if (!BaseType->isRecordType()) {
2501     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2502     return nullptr;
2503   }
2504 
2505   // C++ [class.union]p1:
2506   //   A union shall not be used as a base class.
2507   if (BaseType->isUnionType()) {
2508     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2509     return nullptr;
2510   }
2511 
2512   // For the MS ABI, propagate DLL attributes to base class templates.
2513   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2514     if (Attr *ClassAttr = getDLLAttr(Class)) {
2515       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2516               BaseType->getAsCXXRecordDecl())) {
2517         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2518                                             BaseLoc);
2519       }
2520     }
2521   }
2522 
2523   // C++ [class.derived]p2:
2524   //   The class-name in a base-specifier shall not be an incompletely
2525   //   defined class.
2526   if (RequireCompleteType(BaseLoc, BaseType,
2527                           diag::err_incomplete_base_class, SpecifierRange)) {
2528     Class->setInvalidDecl();
2529     return nullptr;
2530   }
2531 
2532   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2533   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2534   assert(BaseDecl && "Record type has no declaration");
2535   BaseDecl = BaseDecl->getDefinition();
2536   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2537   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2538   assert(CXXBaseDecl && "Base type is not a C++ type");
2539 
2540   // Microsoft docs say:
2541   // "If a base-class has a code_seg attribute, derived classes must have the
2542   // same attribute."
2543   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2544   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2545   if ((DerivedCSA || BaseCSA) &&
2546       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2547     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2548     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2549       << CXXBaseDecl;
2550     return nullptr;
2551   }
2552 
2553   // A class which contains a flexible array member is not suitable for use as a
2554   // base class:
2555   //   - If the layout determines that a base comes before another base,
2556   //     the flexible array member would index into the subsequent base.
2557   //   - If the layout determines that base comes before the derived class,
2558   //     the flexible array member would index into the derived class.
2559   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2560     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2561       << CXXBaseDecl->getDeclName();
2562     return nullptr;
2563   }
2564 
2565   // C++ [class]p3:
2566   //   If a class is marked final and it appears as a base-type-specifier in
2567   //   base-clause, the program is ill-formed.
2568   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2569     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2570       << CXXBaseDecl->getDeclName()
2571       << FA->isSpelledAsSealed();
2572     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2573         << CXXBaseDecl->getDeclName() << FA->getRange();
2574     return nullptr;
2575   }
2576 
2577   if (BaseDecl->isInvalidDecl())
2578     Class->setInvalidDecl();
2579 
2580   // Create the base specifier.
2581   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2582                                         Class->getTagKind() == TTK_Class,
2583                                         Access, TInfo, EllipsisLoc);
2584 }
2585 
2586 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2587 /// one entry in the base class list of a class specifier, for
2588 /// example:
2589 ///    class foo : public bar, virtual private baz {
2590 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2591 BaseResult
2592 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2593                          ParsedAttributes &Attributes,
2594                          bool Virtual, AccessSpecifier Access,
2595                          ParsedType basetype, SourceLocation BaseLoc,
2596                          SourceLocation EllipsisLoc) {
2597   if (!classdecl)
2598     return true;
2599 
2600   AdjustDeclIfTemplate(classdecl);
2601   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2602   if (!Class)
2603     return true;
2604 
2605   // We haven't yet attached the base specifiers.
2606   Class->setIsParsingBaseSpecifiers();
2607 
2608   // We do not support any C++11 attributes on base-specifiers yet.
2609   // Diagnose any attributes we see.
2610   for (const ParsedAttr &AL : Attributes) {
2611     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2612       continue;
2613     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2614                           ? (unsigned)diag::warn_unknown_attribute_ignored
2615                           : (unsigned)diag::err_base_specifier_attribute)
2616         << AL << AL.getRange();
2617   }
2618 
2619   TypeSourceInfo *TInfo = nullptr;
2620   GetTypeFromParser(basetype, &TInfo);
2621 
2622   if (EllipsisLoc.isInvalid() &&
2623       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2624                                       UPPC_BaseType))
2625     return true;
2626 
2627   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2628                                                       Virtual, Access, TInfo,
2629                                                       EllipsisLoc))
2630     return BaseSpec;
2631   else
2632     Class->setInvalidDecl();
2633 
2634   return true;
2635 }
2636 
2637 /// Use small set to collect indirect bases.  As this is only used
2638 /// locally, there's no need to abstract the small size parameter.
2639 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2640 
2641 /// Recursively add the bases of Type.  Don't add Type itself.
2642 static void
2643 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2644                   const QualType &Type)
2645 {
2646   // Even though the incoming type is a base, it might not be
2647   // a class -- it could be a template parm, for instance.
2648   if (auto Rec = Type->getAs<RecordType>()) {
2649     auto Decl = Rec->getAsCXXRecordDecl();
2650 
2651     // Iterate over its bases.
2652     for (const auto &BaseSpec : Decl->bases()) {
2653       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2654         .getUnqualifiedType();
2655       if (Set.insert(Base).second)
2656         // If we've not already seen it, recurse.
2657         NoteIndirectBases(Context, Set, Base);
2658     }
2659   }
2660 }
2661 
2662 /// Performs the actual work of attaching the given base class
2663 /// specifiers to a C++ class.
2664 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2665                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2666  if (Bases.empty())
2667     return false;
2668 
2669   // Used to keep track of which base types we have already seen, so
2670   // that we can properly diagnose redundant direct base types. Note
2671   // that the key is always the unqualified canonical type of the base
2672   // class.
2673   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2674 
2675   // Used to track indirect bases so we can see if a direct base is
2676   // ambiguous.
2677   IndirectBaseSet IndirectBaseTypes;
2678 
2679   // Copy non-redundant base specifiers into permanent storage.
2680   unsigned NumGoodBases = 0;
2681   bool Invalid = false;
2682   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2683     QualType NewBaseType
2684       = Context.getCanonicalType(Bases[idx]->getType());
2685     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2686 
2687     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2688     if (KnownBase) {
2689       // C++ [class.mi]p3:
2690       //   A class shall not be specified as a direct base class of a
2691       //   derived class more than once.
2692       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2693           << KnownBase->getType() << Bases[idx]->getSourceRange();
2694 
2695       // Delete the duplicate base class specifier; we're going to
2696       // overwrite its pointer later.
2697       Context.Deallocate(Bases[idx]);
2698 
2699       Invalid = true;
2700     } else {
2701       // Okay, add this new base class.
2702       KnownBase = Bases[idx];
2703       Bases[NumGoodBases++] = Bases[idx];
2704 
2705       // Note this base's direct & indirect bases, if there could be ambiguity.
2706       if (Bases.size() > 1)
2707         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2708 
2709       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2710         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2711         if (Class->isInterface() &&
2712               (!RD->isInterfaceLike() ||
2713                KnownBase->getAccessSpecifier() != AS_public)) {
2714           // The Microsoft extension __interface does not permit bases that
2715           // are not themselves public interfaces.
2716           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2717               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2718               << RD->getSourceRange();
2719           Invalid = true;
2720         }
2721         if (RD->hasAttr<WeakAttr>())
2722           Class->addAttr(WeakAttr::CreateImplicit(Context));
2723       }
2724     }
2725   }
2726 
2727   // Attach the remaining base class specifiers to the derived class.
2728   Class->setBases(Bases.data(), NumGoodBases);
2729 
2730   // Check that the only base classes that are duplicate are virtual.
2731   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2732     // Check whether this direct base is inaccessible due to ambiguity.
2733     QualType BaseType = Bases[idx]->getType();
2734 
2735     // Skip all dependent types in templates being used as base specifiers.
2736     // Checks below assume that the base specifier is a CXXRecord.
2737     if (BaseType->isDependentType())
2738       continue;
2739 
2740     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2741       .getUnqualifiedType();
2742 
2743     if (IndirectBaseTypes.count(CanonicalBase)) {
2744       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2745                          /*DetectVirtual=*/true);
2746       bool found
2747         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2748       assert(found);
2749       (void)found;
2750 
2751       if (Paths.isAmbiguous(CanonicalBase))
2752         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2753             << BaseType << getAmbiguousPathsDisplayString(Paths)
2754             << Bases[idx]->getSourceRange();
2755       else
2756         assert(Bases[idx]->isVirtual());
2757     }
2758 
2759     // Delete the base class specifier, since its data has been copied
2760     // into the CXXRecordDecl.
2761     Context.Deallocate(Bases[idx]);
2762   }
2763 
2764   return Invalid;
2765 }
2766 
2767 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2768 /// class, after checking whether there are any duplicate base
2769 /// classes.
2770 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2771                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2772   if (!ClassDecl || Bases.empty())
2773     return;
2774 
2775   AdjustDeclIfTemplate(ClassDecl);
2776   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2777 }
2778 
2779 /// Determine whether the type \p Derived is a C++ class that is
2780 /// derived from the type \p Base.
2781 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2782   if (!getLangOpts().CPlusPlus)
2783     return false;
2784 
2785   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2786   if (!DerivedRD)
2787     return false;
2788 
2789   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2790   if (!BaseRD)
2791     return false;
2792 
2793   // If either the base or the derived type is invalid, don't try to
2794   // check whether one is derived from the other.
2795   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2796     return false;
2797 
2798   // FIXME: In a modules build, do we need the entire path to be visible for us
2799   // to be able to use the inheritance relationship?
2800   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2801     return false;
2802 
2803   return DerivedRD->isDerivedFrom(BaseRD);
2804 }
2805 
2806 /// Determine whether the type \p Derived is a C++ class that is
2807 /// derived from the type \p Base.
2808 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2809                          CXXBasePaths &Paths) {
2810   if (!getLangOpts().CPlusPlus)
2811     return false;
2812 
2813   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2814   if (!DerivedRD)
2815     return false;
2816 
2817   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2818   if (!BaseRD)
2819     return false;
2820 
2821   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2822     return false;
2823 
2824   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2825 }
2826 
2827 static void BuildBasePathArray(const CXXBasePath &Path,
2828                                CXXCastPath &BasePathArray) {
2829   // We first go backward and check if we have a virtual base.
2830   // FIXME: It would be better if CXXBasePath had the base specifier for
2831   // the nearest virtual base.
2832   unsigned Start = 0;
2833   for (unsigned I = Path.size(); I != 0; --I) {
2834     if (Path[I - 1].Base->isVirtual()) {
2835       Start = I - 1;
2836       break;
2837     }
2838   }
2839 
2840   // Now add all bases.
2841   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2842     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2843 }
2844 
2845 
2846 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2847                               CXXCastPath &BasePathArray) {
2848   assert(BasePathArray.empty() && "Base path array must be empty!");
2849   assert(Paths.isRecordingPaths() && "Must record paths!");
2850   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2851 }
2852 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2853 /// conversion (where Derived and Base are class types) is
2854 /// well-formed, meaning that the conversion is unambiguous (and
2855 /// that all of the base classes are accessible). Returns true
2856 /// and emits a diagnostic if the code is ill-formed, returns false
2857 /// otherwise. Loc is the location where this routine should point to
2858 /// if there is an error, and Range is the source range to highlight
2859 /// if there is an error.
2860 ///
2861 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2862 /// diagnostic for the respective type of error will be suppressed, but the
2863 /// check for ill-formed code will still be performed.
2864 bool
2865 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2866                                    unsigned InaccessibleBaseID,
2867                                    unsigned AmbiguousBaseConvID,
2868                                    SourceLocation Loc, SourceRange Range,
2869                                    DeclarationName Name,
2870                                    CXXCastPath *BasePath,
2871                                    bool IgnoreAccess) {
2872   // First, determine whether the path from Derived to Base is
2873   // ambiguous. This is slightly more expensive than checking whether
2874   // the Derived to Base conversion exists, because here we need to
2875   // explore multiple paths to determine if there is an ambiguity.
2876   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2877                      /*DetectVirtual=*/false);
2878   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2879   if (!DerivationOkay)
2880     return true;
2881 
2882   const CXXBasePath *Path = nullptr;
2883   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2884     Path = &Paths.front();
2885 
2886   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2887   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2888   // user to access such bases.
2889   if (!Path && getLangOpts().MSVCCompat) {
2890     for (const CXXBasePath &PossiblePath : Paths) {
2891       if (PossiblePath.size() == 1) {
2892         Path = &PossiblePath;
2893         if (AmbiguousBaseConvID)
2894           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2895               << Base << Derived << Range;
2896         break;
2897       }
2898     }
2899   }
2900 
2901   if (Path) {
2902     if (!IgnoreAccess) {
2903       // Check that the base class can be accessed.
2904       switch (
2905           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2906       case AR_inaccessible:
2907         return true;
2908       case AR_accessible:
2909       case AR_dependent:
2910       case AR_delayed:
2911         break;
2912       }
2913     }
2914 
2915     // Build a base path if necessary.
2916     if (BasePath)
2917       ::BuildBasePathArray(*Path, *BasePath);
2918     return false;
2919   }
2920 
2921   if (AmbiguousBaseConvID) {
2922     // We know that the derived-to-base conversion is ambiguous, and
2923     // we're going to produce a diagnostic. Perform the derived-to-base
2924     // search just one more time to compute all of the possible paths so
2925     // that we can print them out. This is more expensive than any of
2926     // the previous derived-to-base checks we've done, but at this point
2927     // performance isn't as much of an issue.
2928     Paths.clear();
2929     Paths.setRecordingPaths(true);
2930     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2931     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2932     (void)StillOkay;
2933 
2934     // Build up a textual representation of the ambiguous paths, e.g.,
2935     // D -> B -> A, that will be used to illustrate the ambiguous
2936     // conversions in the diagnostic. We only print one of the paths
2937     // to each base class subobject.
2938     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2939 
2940     Diag(Loc, AmbiguousBaseConvID)
2941     << Derived << Base << PathDisplayStr << Range << Name;
2942   }
2943   return true;
2944 }
2945 
2946 bool
2947 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2948                                    SourceLocation Loc, SourceRange Range,
2949                                    CXXCastPath *BasePath,
2950                                    bool IgnoreAccess) {
2951   return CheckDerivedToBaseConversion(
2952       Derived, Base, diag::err_upcast_to_inaccessible_base,
2953       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2954       BasePath, IgnoreAccess);
2955 }
2956 
2957 
2958 /// Builds a string representing ambiguous paths from a
2959 /// specific derived class to different subobjects of the same base
2960 /// class.
2961 ///
2962 /// This function builds a string that can be used in error messages
2963 /// to show the different paths that one can take through the
2964 /// inheritance hierarchy to go from the derived class to different
2965 /// subobjects of a base class. The result looks something like this:
2966 /// @code
2967 /// struct D -> struct B -> struct A
2968 /// struct D -> struct C -> struct A
2969 /// @endcode
2970 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2971   std::string PathDisplayStr;
2972   std::set<unsigned> DisplayedPaths;
2973   for (CXXBasePaths::paths_iterator Path = Paths.begin();
2974        Path != Paths.end(); ++Path) {
2975     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2976       // We haven't displayed a path to this particular base
2977       // class subobject yet.
2978       PathDisplayStr += "\n    ";
2979       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2980       for (CXXBasePath::const_iterator Element = Path->begin();
2981            Element != Path->end(); ++Element)
2982         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2983     }
2984   }
2985 
2986   return PathDisplayStr;
2987 }
2988 
2989 //===----------------------------------------------------------------------===//
2990 // C++ class member Handling
2991 //===----------------------------------------------------------------------===//
2992 
2993 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2994 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2995                                 SourceLocation ColonLoc,
2996                                 const ParsedAttributesView &Attrs) {
2997   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2998   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2999                                                   ASLoc, ColonLoc);
3000   CurContext->addHiddenDecl(ASDecl);
3001   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3002 }
3003 
3004 /// CheckOverrideControl - Check C++11 override control semantics.
3005 void Sema::CheckOverrideControl(NamedDecl *D) {
3006   if (D->isInvalidDecl())
3007     return;
3008 
3009   // We only care about "override" and "final" declarations.
3010   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3011     return;
3012 
3013   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3014 
3015   // We can't check dependent instance methods.
3016   if (MD && MD->isInstance() &&
3017       (MD->getParent()->hasAnyDependentBases() ||
3018        MD->getType()->isDependentType()))
3019     return;
3020 
3021   if (MD && !MD->isVirtual()) {
3022     // If we have a non-virtual method, check if if hides a virtual method.
3023     // (In that case, it's most likely the method has the wrong type.)
3024     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3025     FindHiddenVirtualMethods(MD, OverloadedMethods);
3026 
3027     if (!OverloadedMethods.empty()) {
3028       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3029         Diag(OA->getLocation(),
3030              diag::override_keyword_hides_virtual_member_function)
3031           << "override" << (OverloadedMethods.size() > 1);
3032       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3033         Diag(FA->getLocation(),
3034              diag::override_keyword_hides_virtual_member_function)
3035           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3036           << (OverloadedMethods.size() > 1);
3037       }
3038       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3039       MD->setInvalidDecl();
3040       return;
3041     }
3042     // Fall through into the general case diagnostic.
3043     // FIXME: We might want to attempt typo correction here.
3044   }
3045 
3046   if (!MD || !MD->isVirtual()) {
3047     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3048       Diag(OA->getLocation(),
3049            diag::override_keyword_only_allowed_on_virtual_member_functions)
3050         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3051       D->dropAttr<OverrideAttr>();
3052     }
3053     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3054       Diag(FA->getLocation(),
3055            diag::override_keyword_only_allowed_on_virtual_member_functions)
3056         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3057         << FixItHint::CreateRemoval(FA->getLocation());
3058       D->dropAttr<FinalAttr>();
3059     }
3060     return;
3061   }
3062 
3063   // C++11 [class.virtual]p5:
3064   //   If a function is marked with the virt-specifier override and
3065   //   does not override a member function of a base class, the program is
3066   //   ill-formed.
3067   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3068   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3069     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3070       << MD->getDeclName();
3071 }
3072 
3073 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3074   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3075     return;
3076   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3077   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3078     return;
3079 
3080   SourceLocation Loc = MD->getLocation();
3081   SourceLocation SpellingLoc = Loc;
3082   if (getSourceManager().isMacroArgExpansion(Loc))
3083     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3084   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3085   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3086       return;
3087 
3088   if (MD->size_overridden_methods() > 0) {
3089     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3090       unsigned DiagID =
3091           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3092               ? DiagInconsistent
3093               : DiagSuggest;
3094       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3095       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3096       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3097     };
3098     if (isa<CXXDestructorDecl>(MD))
3099       EmitDiag(
3100           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3101           diag::warn_suggest_destructor_marked_not_override_overriding);
3102     else
3103       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3104                diag::warn_suggest_function_marked_not_override_overriding);
3105   }
3106 }
3107 
3108 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3109 /// function overrides a virtual member function marked 'final', according to
3110 /// C++11 [class.virtual]p4.
3111 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3112                                                   const CXXMethodDecl *Old) {
3113   FinalAttr *FA = Old->getAttr<FinalAttr>();
3114   if (!FA)
3115     return false;
3116 
3117   Diag(New->getLocation(), diag::err_final_function_overridden)
3118     << New->getDeclName()
3119     << FA->isSpelledAsSealed();
3120   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3121   return true;
3122 }
3123 
3124 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3125   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3126   // FIXME: Destruction of ObjC lifetime types has side-effects.
3127   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3128     return !RD->isCompleteDefinition() ||
3129            !RD->hasTrivialDefaultConstructor() ||
3130            !RD->hasTrivialDestructor();
3131   return false;
3132 }
3133 
3134 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3135   ParsedAttributesView::const_iterator Itr =
3136       llvm::find_if(list, [](const ParsedAttr &AL) {
3137         return AL.isDeclspecPropertyAttribute();
3138       });
3139   if (Itr != list.end())
3140     return &*Itr;
3141   return nullptr;
3142 }
3143 
3144 // Check if there is a field shadowing.
3145 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3146                                       DeclarationName FieldName,
3147                                       const CXXRecordDecl *RD,
3148                                       bool DeclIsField) {
3149   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3150     return;
3151 
3152   // To record a shadowed field in a base
3153   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3154   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3155                            CXXBasePath &Path) {
3156     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3157     // Record an ambiguous path directly
3158     if (Bases.find(Base) != Bases.end())
3159       return true;
3160     for (const auto Field : Base->lookup(FieldName)) {
3161       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3162           Field->getAccess() != AS_private) {
3163         assert(Field->getAccess() != AS_none);
3164         assert(Bases.find(Base) == Bases.end());
3165         Bases[Base] = Field;
3166         return true;
3167       }
3168     }
3169     return false;
3170   };
3171 
3172   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3173                      /*DetectVirtual=*/true);
3174   if (!RD->lookupInBases(FieldShadowed, Paths))
3175     return;
3176 
3177   for (const auto &P : Paths) {
3178     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3179     auto It = Bases.find(Base);
3180     // Skip duplicated bases
3181     if (It == Bases.end())
3182       continue;
3183     auto BaseField = It->second;
3184     assert(BaseField->getAccess() != AS_private);
3185     if (AS_none !=
3186         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3187       Diag(Loc, diag::warn_shadow_field)
3188         << FieldName << RD << Base << DeclIsField;
3189       Diag(BaseField->getLocation(), diag::note_shadow_field);
3190       Bases.erase(It);
3191     }
3192   }
3193 }
3194 
3195 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3196 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3197 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3198 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3199 /// present (but parsing it has been deferred).
3200 NamedDecl *
3201 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3202                                MultiTemplateParamsArg TemplateParameterLists,
3203                                Expr *BW, const VirtSpecifiers &VS,
3204                                InClassInitStyle InitStyle) {
3205   const DeclSpec &DS = D.getDeclSpec();
3206   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3207   DeclarationName Name = NameInfo.getName();
3208   SourceLocation Loc = NameInfo.getLoc();
3209 
3210   // For anonymous bitfields, the location should point to the type.
3211   if (Loc.isInvalid())
3212     Loc = D.getBeginLoc();
3213 
3214   Expr *BitWidth = static_cast<Expr*>(BW);
3215 
3216   assert(isa<CXXRecordDecl>(CurContext));
3217   assert(!DS.isFriendSpecified());
3218 
3219   bool isFunc = D.isDeclarationOfFunction();
3220   const ParsedAttr *MSPropertyAttr =
3221       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3222 
3223   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3224     // The Microsoft extension __interface only permits public member functions
3225     // and prohibits constructors, destructors, operators, non-public member
3226     // functions, static methods and data members.
3227     unsigned InvalidDecl;
3228     bool ShowDeclName = true;
3229     if (!isFunc &&
3230         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3231       InvalidDecl = 0;
3232     else if (!isFunc)
3233       InvalidDecl = 1;
3234     else if (AS != AS_public)
3235       InvalidDecl = 2;
3236     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3237       InvalidDecl = 3;
3238     else switch (Name.getNameKind()) {
3239       case DeclarationName::CXXConstructorName:
3240         InvalidDecl = 4;
3241         ShowDeclName = false;
3242         break;
3243 
3244       case DeclarationName::CXXDestructorName:
3245         InvalidDecl = 5;
3246         ShowDeclName = false;
3247         break;
3248 
3249       case DeclarationName::CXXOperatorName:
3250       case DeclarationName::CXXConversionFunctionName:
3251         InvalidDecl = 6;
3252         break;
3253 
3254       default:
3255         InvalidDecl = 0;
3256         break;
3257     }
3258 
3259     if (InvalidDecl) {
3260       if (ShowDeclName)
3261         Diag(Loc, diag::err_invalid_member_in_interface)
3262           << (InvalidDecl-1) << Name;
3263       else
3264         Diag(Loc, diag::err_invalid_member_in_interface)
3265           << (InvalidDecl-1) << "";
3266       return nullptr;
3267     }
3268   }
3269 
3270   // C++ 9.2p6: A member shall not be declared to have automatic storage
3271   // duration (auto, register) or with the extern storage-class-specifier.
3272   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3273   // data members and cannot be applied to names declared const or static,
3274   // and cannot be applied to reference members.
3275   switch (DS.getStorageClassSpec()) {
3276   case DeclSpec::SCS_unspecified:
3277   case DeclSpec::SCS_typedef:
3278   case DeclSpec::SCS_static:
3279     break;
3280   case DeclSpec::SCS_mutable:
3281     if (isFunc) {
3282       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3283 
3284       // FIXME: It would be nicer if the keyword was ignored only for this
3285       // declarator. Otherwise we could get follow-up errors.
3286       D.getMutableDeclSpec().ClearStorageClassSpecs();
3287     }
3288     break;
3289   default:
3290     Diag(DS.getStorageClassSpecLoc(),
3291          diag::err_storageclass_invalid_for_member);
3292     D.getMutableDeclSpec().ClearStorageClassSpecs();
3293     break;
3294   }
3295 
3296   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3297                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3298                       !isFunc);
3299 
3300   if (DS.hasConstexprSpecifier() && isInstField) {
3301     SemaDiagnosticBuilder B =
3302         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3303     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3304     if (InitStyle == ICIS_NoInit) {
3305       B << 0 << 0;
3306       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3307         B << FixItHint::CreateRemoval(ConstexprLoc);
3308       else {
3309         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3310         D.getMutableDeclSpec().ClearConstexprSpec();
3311         const char *PrevSpec;
3312         unsigned DiagID;
3313         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3314             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3315         (void)Failed;
3316         assert(!Failed && "Making a constexpr member const shouldn't fail");
3317       }
3318     } else {
3319       B << 1;
3320       const char *PrevSpec;
3321       unsigned DiagID;
3322       if (D.getMutableDeclSpec().SetStorageClassSpec(
3323           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3324           Context.getPrintingPolicy())) {
3325         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3326                "This is the only DeclSpec that should fail to be applied");
3327         B << 1;
3328       } else {
3329         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3330         isInstField = false;
3331       }
3332     }
3333   }
3334 
3335   NamedDecl *Member;
3336   if (isInstField) {
3337     CXXScopeSpec &SS = D.getCXXScopeSpec();
3338 
3339     // Data members must have identifiers for names.
3340     if (!Name.isIdentifier()) {
3341       Diag(Loc, diag::err_bad_variable_name)
3342         << Name;
3343       return nullptr;
3344     }
3345 
3346     IdentifierInfo *II = Name.getAsIdentifierInfo();
3347 
3348     // Member field could not be with "template" keyword.
3349     // So TemplateParameterLists should be empty in this case.
3350     if (TemplateParameterLists.size()) {
3351       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3352       if (TemplateParams->size()) {
3353         // There is no such thing as a member field template.
3354         Diag(D.getIdentifierLoc(), diag::err_template_member)
3355             << II
3356             << SourceRange(TemplateParams->getTemplateLoc(),
3357                 TemplateParams->getRAngleLoc());
3358       } else {
3359         // There is an extraneous 'template<>' for this member.
3360         Diag(TemplateParams->getTemplateLoc(),
3361             diag::err_template_member_noparams)
3362             << II
3363             << SourceRange(TemplateParams->getTemplateLoc(),
3364                 TemplateParams->getRAngleLoc());
3365       }
3366       return nullptr;
3367     }
3368 
3369     if (SS.isSet() && !SS.isInvalid()) {
3370       // The user provided a superfluous scope specifier inside a class
3371       // definition:
3372       //
3373       // class X {
3374       //   int X::member;
3375       // };
3376       if (DeclContext *DC = computeDeclContext(SS, false))
3377         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3378                                      D.getName().getKind() ==
3379                                          UnqualifiedIdKind::IK_TemplateId);
3380       else
3381         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3382           << Name << SS.getRange();
3383 
3384       SS.clear();
3385     }
3386 
3387     if (MSPropertyAttr) {
3388       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3389                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3390       if (!Member)
3391         return nullptr;
3392       isInstField = false;
3393     } else {
3394       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3395                                 BitWidth, InitStyle, AS);
3396       if (!Member)
3397         return nullptr;
3398     }
3399 
3400     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3401   } else {
3402     Member = HandleDeclarator(S, D, TemplateParameterLists);
3403     if (!Member)
3404       return nullptr;
3405 
3406     // Non-instance-fields can't have a bitfield.
3407     if (BitWidth) {
3408       if (Member->isInvalidDecl()) {
3409         // don't emit another diagnostic.
3410       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3411         // C++ 9.6p3: A bit-field shall not be a static member.
3412         // "static member 'A' cannot be a bit-field"
3413         Diag(Loc, diag::err_static_not_bitfield)
3414           << Name << BitWidth->getSourceRange();
3415       } else if (isa<TypedefDecl>(Member)) {
3416         // "typedef member 'x' cannot be a bit-field"
3417         Diag(Loc, diag::err_typedef_not_bitfield)
3418           << Name << BitWidth->getSourceRange();
3419       } else {
3420         // A function typedef ("typedef int f(); f a;").
3421         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3422         Diag(Loc, diag::err_not_integral_type_bitfield)
3423           << Name << cast<ValueDecl>(Member)->getType()
3424           << BitWidth->getSourceRange();
3425       }
3426 
3427       BitWidth = nullptr;
3428       Member->setInvalidDecl();
3429     }
3430 
3431     NamedDecl *NonTemplateMember = Member;
3432     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3433       NonTemplateMember = FunTmpl->getTemplatedDecl();
3434     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3435       NonTemplateMember = VarTmpl->getTemplatedDecl();
3436 
3437     Member->setAccess(AS);
3438 
3439     // If we have declared a member function template or static data member
3440     // template, set the access of the templated declaration as well.
3441     if (NonTemplateMember != Member)
3442       NonTemplateMember->setAccess(AS);
3443 
3444     // C++ [temp.deduct.guide]p3:
3445     //   A deduction guide [...] for a member class template [shall be
3446     //   declared] with the same access [as the template].
3447     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3448       auto *TD = DG->getDeducedTemplate();
3449       // Access specifiers are only meaningful if both the template and the
3450       // deduction guide are from the same scope.
3451       if (AS != TD->getAccess() &&
3452           TD->getDeclContext()->getRedeclContext()->Equals(
3453               DG->getDeclContext()->getRedeclContext())) {
3454         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3455         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3456             << TD->getAccess();
3457         const AccessSpecDecl *LastAccessSpec = nullptr;
3458         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3459           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3460             LastAccessSpec = AccessSpec;
3461         }
3462         assert(LastAccessSpec && "differing access with no access specifier");
3463         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3464             << AS;
3465       }
3466     }
3467   }
3468 
3469   if (VS.isOverrideSpecified())
3470     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3471                                          AttributeCommonInfo::AS_Keyword));
3472   if (VS.isFinalSpecified())
3473     Member->addAttr(FinalAttr::Create(
3474         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3475         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3476 
3477   if (VS.getLastLocation().isValid()) {
3478     // Update the end location of a method that has a virt-specifiers.
3479     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3480       MD->setRangeEnd(VS.getLastLocation());
3481   }
3482 
3483   CheckOverrideControl(Member);
3484 
3485   assert((Name || isInstField) && "No identifier for non-field ?");
3486 
3487   if (isInstField) {
3488     FieldDecl *FD = cast<FieldDecl>(Member);
3489     FieldCollector->Add(FD);
3490 
3491     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3492       // Remember all explicit private FieldDecls that have a name, no side
3493       // effects and are not part of a dependent type declaration.
3494       if (!FD->isImplicit() && FD->getDeclName() &&
3495           FD->getAccess() == AS_private &&
3496           !FD->hasAttr<UnusedAttr>() &&
3497           !FD->getParent()->isDependentContext() &&
3498           !InitializationHasSideEffects(*FD))
3499         UnusedPrivateFields.insert(FD);
3500     }
3501   }
3502 
3503   return Member;
3504 }
3505 
3506 namespace {
3507   class UninitializedFieldVisitor
3508       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3509     Sema &S;
3510     // List of Decls to generate a warning on.  Also remove Decls that become
3511     // initialized.
3512     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3513     // List of base classes of the record.  Classes are removed after their
3514     // initializers.
3515     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3516     // Vector of decls to be removed from the Decl set prior to visiting the
3517     // nodes.  These Decls may have been initialized in the prior initializer.
3518     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3519     // If non-null, add a note to the warning pointing back to the constructor.
3520     const CXXConstructorDecl *Constructor;
3521     // Variables to hold state when processing an initializer list.  When
3522     // InitList is true, special case initialization of FieldDecls matching
3523     // InitListFieldDecl.
3524     bool InitList;
3525     FieldDecl *InitListFieldDecl;
3526     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3527 
3528   public:
3529     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3530     UninitializedFieldVisitor(Sema &S,
3531                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3532                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3533       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3534         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3535 
3536     // Returns true if the use of ME is not an uninitialized use.
3537     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3538                                          bool CheckReferenceOnly) {
3539       llvm::SmallVector<FieldDecl*, 4> Fields;
3540       bool ReferenceField = false;
3541       while (ME) {
3542         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3543         if (!FD)
3544           return false;
3545         Fields.push_back(FD);
3546         if (FD->getType()->isReferenceType())
3547           ReferenceField = true;
3548         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3549       }
3550 
3551       // Binding a reference to an uninitialized field is not an
3552       // uninitialized use.
3553       if (CheckReferenceOnly && !ReferenceField)
3554         return true;
3555 
3556       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3557       // Discard the first field since it is the field decl that is being
3558       // initialized.
3559       for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3560         UsedFieldIndex.push_back((*I)->getFieldIndex());
3561       }
3562 
3563       for (auto UsedIter = UsedFieldIndex.begin(),
3564                 UsedEnd = UsedFieldIndex.end(),
3565                 OrigIter = InitFieldIndex.begin(),
3566                 OrigEnd = InitFieldIndex.end();
3567            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3568         if (*UsedIter < *OrigIter)
3569           return true;
3570         if (*UsedIter > *OrigIter)
3571           break;
3572       }
3573 
3574       return false;
3575     }
3576 
3577     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3578                           bool AddressOf) {
3579       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3580         return;
3581 
3582       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3583       // or union.
3584       MemberExpr *FieldME = ME;
3585 
3586       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3587 
3588       Expr *Base = ME;
3589       while (MemberExpr *SubME =
3590                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3591 
3592         if (isa<VarDecl>(SubME->getMemberDecl()))
3593           return;
3594 
3595         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3596           if (!FD->isAnonymousStructOrUnion())
3597             FieldME = SubME;
3598 
3599         if (!FieldME->getType().isPODType(S.Context))
3600           AllPODFields = false;
3601 
3602         Base = SubME->getBase();
3603       }
3604 
3605       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3606         Visit(Base);
3607         return;
3608       }
3609 
3610       if (AddressOf && AllPODFields)
3611         return;
3612 
3613       ValueDecl* FoundVD = FieldME->getMemberDecl();
3614 
3615       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3616         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3617           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3618         }
3619 
3620         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3621           QualType T = BaseCast->getType();
3622           if (T->isPointerType() &&
3623               BaseClasses.count(T->getPointeeType())) {
3624             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3625                 << T->getPointeeType() << FoundVD;
3626           }
3627         }
3628       }
3629 
3630       if (!Decls.count(FoundVD))
3631         return;
3632 
3633       const bool IsReference = FoundVD->getType()->isReferenceType();
3634 
3635       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3636         // Special checking for initializer lists.
3637         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3638           return;
3639         }
3640       } else {
3641         // Prevent double warnings on use of unbounded references.
3642         if (CheckReferenceOnly && !IsReference)
3643           return;
3644       }
3645 
3646       unsigned diag = IsReference
3647           ? diag::warn_reference_field_is_uninit
3648           : diag::warn_field_is_uninit;
3649       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3650       if (Constructor)
3651         S.Diag(Constructor->getLocation(),
3652                diag::note_uninit_in_this_constructor)
3653           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3654 
3655     }
3656 
3657     void HandleValue(Expr *E, bool AddressOf) {
3658       E = E->IgnoreParens();
3659 
3660       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3661         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3662                          AddressOf /*AddressOf*/);
3663         return;
3664       }
3665 
3666       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3667         Visit(CO->getCond());
3668         HandleValue(CO->getTrueExpr(), AddressOf);
3669         HandleValue(CO->getFalseExpr(), AddressOf);
3670         return;
3671       }
3672 
3673       if (BinaryConditionalOperator *BCO =
3674               dyn_cast<BinaryConditionalOperator>(E)) {
3675         Visit(BCO->getCond());
3676         HandleValue(BCO->getFalseExpr(), AddressOf);
3677         return;
3678       }
3679 
3680       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3681         HandleValue(OVE->getSourceExpr(), AddressOf);
3682         return;
3683       }
3684 
3685       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3686         switch (BO->getOpcode()) {
3687         default:
3688           break;
3689         case(BO_PtrMemD):
3690         case(BO_PtrMemI):
3691           HandleValue(BO->getLHS(), AddressOf);
3692           Visit(BO->getRHS());
3693           return;
3694         case(BO_Comma):
3695           Visit(BO->getLHS());
3696           HandleValue(BO->getRHS(), AddressOf);
3697           return;
3698         }
3699       }
3700 
3701       Visit(E);
3702     }
3703 
3704     void CheckInitListExpr(InitListExpr *ILE) {
3705       InitFieldIndex.push_back(0);
3706       for (auto Child : ILE->children()) {
3707         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3708           CheckInitListExpr(SubList);
3709         } else {
3710           Visit(Child);
3711         }
3712         ++InitFieldIndex.back();
3713       }
3714       InitFieldIndex.pop_back();
3715     }
3716 
3717     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3718                           FieldDecl *Field, const Type *BaseClass) {
3719       // Remove Decls that may have been initialized in the previous
3720       // initializer.
3721       for (ValueDecl* VD : DeclsToRemove)
3722         Decls.erase(VD);
3723       DeclsToRemove.clear();
3724 
3725       Constructor = FieldConstructor;
3726       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3727 
3728       if (ILE && Field) {
3729         InitList = true;
3730         InitListFieldDecl = Field;
3731         InitFieldIndex.clear();
3732         CheckInitListExpr(ILE);
3733       } else {
3734         InitList = false;
3735         Visit(E);
3736       }
3737 
3738       if (Field)
3739         Decls.erase(Field);
3740       if (BaseClass)
3741         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3742     }
3743 
3744     void VisitMemberExpr(MemberExpr *ME) {
3745       // All uses of unbounded reference fields will warn.
3746       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3747     }
3748 
3749     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3750       if (E->getCastKind() == CK_LValueToRValue) {
3751         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3752         return;
3753       }
3754 
3755       Inherited::VisitImplicitCastExpr(E);
3756     }
3757 
3758     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3759       if (E->getConstructor()->isCopyConstructor()) {
3760         Expr *ArgExpr = E->getArg(0);
3761         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3762           if (ILE->getNumInits() == 1)
3763             ArgExpr = ILE->getInit(0);
3764         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3765           if (ICE->getCastKind() == CK_NoOp)
3766             ArgExpr = ICE->getSubExpr();
3767         HandleValue(ArgExpr, false /*AddressOf*/);
3768         return;
3769       }
3770       Inherited::VisitCXXConstructExpr(E);
3771     }
3772 
3773     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3774       Expr *Callee = E->getCallee();
3775       if (isa<MemberExpr>(Callee)) {
3776         HandleValue(Callee, false /*AddressOf*/);
3777         for (auto Arg : E->arguments())
3778           Visit(Arg);
3779         return;
3780       }
3781 
3782       Inherited::VisitCXXMemberCallExpr(E);
3783     }
3784 
3785     void VisitCallExpr(CallExpr *E) {
3786       // Treat std::move as a use.
3787       if (E->isCallToStdMove()) {
3788         HandleValue(E->getArg(0), /*AddressOf=*/false);
3789         return;
3790       }
3791 
3792       Inherited::VisitCallExpr(E);
3793     }
3794 
3795     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3796       Expr *Callee = E->getCallee();
3797 
3798       if (isa<UnresolvedLookupExpr>(Callee))
3799         return Inherited::VisitCXXOperatorCallExpr(E);
3800 
3801       Visit(Callee);
3802       for (auto Arg : E->arguments())
3803         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3804     }
3805 
3806     void VisitBinaryOperator(BinaryOperator *E) {
3807       // If a field assignment is detected, remove the field from the
3808       // uninitiailized field set.
3809       if (E->getOpcode() == BO_Assign)
3810         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3811           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3812             if (!FD->getType()->isReferenceType())
3813               DeclsToRemove.push_back(FD);
3814 
3815       if (E->isCompoundAssignmentOp()) {
3816         HandleValue(E->getLHS(), false /*AddressOf*/);
3817         Visit(E->getRHS());
3818         return;
3819       }
3820 
3821       Inherited::VisitBinaryOperator(E);
3822     }
3823 
3824     void VisitUnaryOperator(UnaryOperator *E) {
3825       if (E->isIncrementDecrementOp()) {
3826         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3827         return;
3828       }
3829       if (E->getOpcode() == UO_AddrOf) {
3830         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3831           HandleValue(ME->getBase(), true /*AddressOf*/);
3832           return;
3833         }
3834       }
3835 
3836       Inherited::VisitUnaryOperator(E);
3837     }
3838   };
3839 
3840   // Diagnose value-uses of fields to initialize themselves, e.g.
3841   //   foo(foo)
3842   // where foo is not also a parameter to the constructor.
3843   // Also diagnose across field uninitialized use such as
3844   //   x(y), y(x)
3845   // TODO: implement -Wuninitialized and fold this into that framework.
3846   static void DiagnoseUninitializedFields(
3847       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3848 
3849     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3850                                            Constructor->getLocation())) {
3851       return;
3852     }
3853 
3854     if (Constructor->isInvalidDecl())
3855       return;
3856 
3857     const CXXRecordDecl *RD = Constructor->getParent();
3858 
3859     if (RD->isDependentContext())
3860       return;
3861 
3862     // Holds fields that are uninitialized.
3863     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3864 
3865     // At the beginning, all fields are uninitialized.
3866     for (auto *I : RD->decls()) {
3867       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3868         UninitializedFields.insert(FD);
3869       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3870         UninitializedFields.insert(IFD->getAnonField());
3871       }
3872     }
3873 
3874     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3875     for (auto I : RD->bases())
3876       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3877 
3878     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3879       return;
3880 
3881     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3882                                                    UninitializedFields,
3883                                                    UninitializedBaseClasses);
3884 
3885     for (const auto *FieldInit : Constructor->inits()) {
3886       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3887         break;
3888 
3889       Expr *InitExpr = FieldInit->getInit();
3890       if (!InitExpr)
3891         continue;
3892 
3893       if (CXXDefaultInitExpr *Default =
3894               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3895         InitExpr = Default->getExpr();
3896         if (!InitExpr)
3897           continue;
3898         // In class initializers will point to the constructor.
3899         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3900                                               FieldInit->getAnyMember(),
3901                                               FieldInit->getBaseClass());
3902       } else {
3903         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3904                                               FieldInit->getAnyMember(),
3905                                               FieldInit->getBaseClass());
3906       }
3907     }
3908   }
3909 } // namespace
3910 
3911 /// Enter a new C++ default initializer scope. After calling this, the
3912 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3913 /// parsing or instantiating the initializer failed.
3914 void Sema::ActOnStartCXXInClassMemberInitializer() {
3915   // Create a synthetic function scope to represent the call to the constructor
3916   // that notionally surrounds a use of this initializer.
3917   PushFunctionScope();
3918 }
3919 
3920 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3921   if (!D.isFunctionDeclarator())
3922     return;
3923   auto &FTI = D.getFunctionTypeInfo();
3924   if (!FTI.Params)
3925     return;
3926   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3927                                                           FTI.NumParams)) {
3928     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3929     if (ParamDecl->getDeclName())
3930       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3931   }
3932 }
3933 
3934 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3935   if (ConstraintExpr.isInvalid())
3936     return ExprError();
3937   return CorrectDelayedTyposInExpr(ConstraintExpr);
3938 }
3939 
3940 /// This is invoked after parsing an in-class initializer for a
3941 /// non-static C++ class member, and after instantiating an in-class initializer
3942 /// in a class template. Such actions are deferred until the class is complete.
3943 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3944                                                   SourceLocation InitLoc,
3945                                                   Expr *InitExpr) {
3946   // Pop the notional constructor scope we created earlier.
3947   PopFunctionScopeInfo(nullptr, D);
3948 
3949   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3950   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3951          "must set init style when field is created");
3952 
3953   if (!InitExpr) {
3954     D->setInvalidDecl();
3955     if (FD)
3956       FD->removeInClassInitializer();
3957     return;
3958   }
3959 
3960   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3961     FD->setInvalidDecl();
3962     FD->removeInClassInitializer();
3963     return;
3964   }
3965 
3966   ExprResult Init = InitExpr;
3967   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3968     InitializedEntity Entity =
3969         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3970     InitializationKind Kind =
3971         FD->getInClassInitStyle() == ICIS_ListInit
3972             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3973                                                    InitExpr->getBeginLoc(),
3974                                                    InitExpr->getEndLoc())
3975             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3976     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3977     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3978     if (Init.isInvalid()) {
3979       FD->setInvalidDecl();
3980       return;
3981     }
3982   }
3983 
3984   // C++11 [class.base.init]p7:
3985   //   The initialization of each base and member constitutes a
3986   //   full-expression.
3987   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3988   if (Init.isInvalid()) {
3989     FD->setInvalidDecl();
3990     return;
3991   }
3992 
3993   InitExpr = Init.get();
3994 
3995   FD->setInClassInitializer(InitExpr);
3996 }
3997 
3998 /// Find the direct and/or virtual base specifiers that
3999 /// correspond to the given base type, for use in base initialization
4000 /// within a constructor.
4001 static bool FindBaseInitializer(Sema &SemaRef,
4002                                 CXXRecordDecl *ClassDecl,
4003                                 QualType BaseType,
4004                                 const CXXBaseSpecifier *&DirectBaseSpec,
4005                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4006   // First, check for a direct base class.
4007   DirectBaseSpec = nullptr;
4008   for (const auto &Base : ClassDecl->bases()) {
4009     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4010       // We found a direct base of this type. That's what we're
4011       // initializing.
4012       DirectBaseSpec = &Base;
4013       break;
4014     }
4015   }
4016 
4017   // Check for a virtual base class.
4018   // FIXME: We might be able to short-circuit this if we know in advance that
4019   // there are no virtual bases.
4020   VirtualBaseSpec = nullptr;
4021   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4022     // We haven't found a base yet; search the class hierarchy for a
4023     // virtual base class.
4024     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4025                        /*DetectVirtual=*/false);
4026     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4027                               SemaRef.Context.getTypeDeclType(ClassDecl),
4028                               BaseType, Paths)) {
4029       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4030            Path != Paths.end(); ++Path) {
4031         if (Path->back().Base->isVirtual()) {
4032           VirtualBaseSpec = Path->back().Base;
4033           break;
4034         }
4035       }
4036     }
4037   }
4038 
4039   return DirectBaseSpec || VirtualBaseSpec;
4040 }
4041 
4042 /// Handle a C++ member initializer using braced-init-list syntax.
4043 MemInitResult
4044 Sema::ActOnMemInitializer(Decl *ConstructorD,
4045                           Scope *S,
4046                           CXXScopeSpec &SS,
4047                           IdentifierInfo *MemberOrBase,
4048                           ParsedType TemplateTypeTy,
4049                           const DeclSpec &DS,
4050                           SourceLocation IdLoc,
4051                           Expr *InitList,
4052                           SourceLocation EllipsisLoc) {
4053   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4054                              DS, IdLoc, InitList,
4055                              EllipsisLoc);
4056 }
4057 
4058 /// Handle a C++ member initializer using parentheses syntax.
4059 MemInitResult
4060 Sema::ActOnMemInitializer(Decl *ConstructorD,
4061                           Scope *S,
4062                           CXXScopeSpec &SS,
4063                           IdentifierInfo *MemberOrBase,
4064                           ParsedType TemplateTypeTy,
4065                           const DeclSpec &DS,
4066                           SourceLocation IdLoc,
4067                           SourceLocation LParenLoc,
4068                           ArrayRef<Expr *> Args,
4069                           SourceLocation RParenLoc,
4070                           SourceLocation EllipsisLoc) {
4071   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4072   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4073                              DS, IdLoc, List, EllipsisLoc);
4074 }
4075 
4076 namespace {
4077 
4078 // Callback to only accept typo corrections that can be a valid C++ member
4079 // intializer: either a non-static field member or a base class.
4080 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4081 public:
4082   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4083       : ClassDecl(ClassDecl) {}
4084 
4085   bool ValidateCandidate(const TypoCorrection &candidate) override {
4086     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4087       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4088         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4089       return isa<TypeDecl>(ND);
4090     }
4091     return false;
4092   }
4093 
4094   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4095     return std::make_unique<MemInitializerValidatorCCC>(*this);
4096   }
4097 
4098 private:
4099   CXXRecordDecl *ClassDecl;
4100 };
4101 
4102 }
4103 
4104 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4105                                              CXXScopeSpec &SS,
4106                                              ParsedType TemplateTypeTy,
4107                                              IdentifierInfo *MemberOrBase) {
4108   if (SS.getScopeRep() || TemplateTypeTy)
4109     return nullptr;
4110   DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4111   if (Result.empty())
4112     return nullptr;
4113   ValueDecl *Member;
4114   if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4115       (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4116     return Member;
4117   return nullptr;
4118 }
4119 
4120 /// Handle a C++ member initializer.
4121 MemInitResult
4122 Sema::BuildMemInitializer(Decl *ConstructorD,
4123                           Scope *S,
4124                           CXXScopeSpec &SS,
4125                           IdentifierInfo *MemberOrBase,
4126                           ParsedType TemplateTypeTy,
4127                           const DeclSpec &DS,
4128                           SourceLocation IdLoc,
4129                           Expr *Init,
4130                           SourceLocation EllipsisLoc) {
4131   ExprResult Res = CorrectDelayedTyposInExpr(Init);
4132   if (!Res.isUsable())
4133     return true;
4134   Init = Res.get();
4135 
4136   if (!ConstructorD)
4137     return true;
4138 
4139   AdjustDeclIfTemplate(ConstructorD);
4140 
4141   CXXConstructorDecl *Constructor
4142     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4143   if (!Constructor) {
4144     // The user wrote a constructor initializer on a function that is
4145     // not a C++ constructor. Ignore the error for now, because we may
4146     // have more member initializers coming; we'll diagnose it just
4147     // once in ActOnMemInitializers.
4148     return true;
4149   }
4150 
4151   CXXRecordDecl *ClassDecl = Constructor->getParent();
4152 
4153   // C++ [class.base.init]p2:
4154   //   Names in a mem-initializer-id are looked up in the scope of the
4155   //   constructor's class and, if not found in that scope, are looked
4156   //   up in the scope containing the constructor's definition.
4157   //   [Note: if the constructor's class contains a member with the
4158   //   same name as a direct or virtual base class of the class, a
4159   //   mem-initializer-id naming the member or base class and composed
4160   //   of a single identifier refers to the class member. A
4161   //   mem-initializer-id for the hidden base class may be specified
4162   //   using a qualified name. ]
4163 
4164   // Look for a member, first.
4165   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4166           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4167     if (EllipsisLoc.isValid())
4168       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4169           << MemberOrBase
4170           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4171 
4172     return BuildMemberInitializer(Member, Init, IdLoc);
4173   }
4174   // It didn't name a member, so see if it names a class.
4175   QualType BaseType;
4176   TypeSourceInfo *TInfo = nullptr;
4177 
4178   if (TemplateTypeTy) {
4179     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4180     if (BaseType.isNull())
4181       return true;
4182   } else if (DS.getTypeSpecType() == TST_decltype) {
4183     BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4184   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4185     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4186     return true;
4187   } else {
4188     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4189     LookupParsedName(R, S, &SS);
4190 
4191     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4192     if (!TyD) {
4193       if (R.isAmbiguous()) return true;
4194 
4195       // We don't want access-control diagnostics here.
4196       R.suppressDiagnostics();
4197 
4198       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4199         bool NotUnknownSpecialization = false;
4200         DeclContext *DC = computeDeclContext(SS, false);
4201         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4202           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4203 
4204         if (!NotUnknownSpecialization) {
4205           // When the scope specifier can refer to a member of an unknown
4206           // specialization, we take it as a type name.
4207           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4208                                        SS.getWithLocInContext(Context),
4209                                        *MemberOrBase, IdLoc);
4210           if (BaseType.isNull())
4211             return true;
4212 
4213           TInfo = Context.CreateTypeSourceInfo(BaseType);
4214           DependentNameTypeLoc TL =
4215               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4216           if (!TL.isNull()) {
4217             TL.setNameLoc(IdLoc);
4218             TL.setElaboratedKeywordLoc(SourceLocation());
4219             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4220           }
4221 
4222           R.clear();
4223           R.setLookupName(MemberOrBase);
4224         }
4225       }
4226 
4227       // If no results were found, try to correct typos.
4228       TypoCorrection Corr;
4229       MemInitializerValidatorCCC CCC(ClassDecl);
4230       if (R.empty() && BaseType.isNull() &&
4231           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4232                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4233         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4234           // We have found a non-static data member with a similar
4235           // name to what was typed; complain and initialize that
4236           // member.
4237           diagnoseTypo(Corr,
4238                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4239                          << MemberOrBase << true);
4240           return BuildMemberInitializer(Member, Init, IdLoc);
4241         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4242           const CXXBaseSpecifier *DirectBaseSpec;
4243           const CXXBaseSpecifier *VirtualBaseSpec;
4244           if (FindBaseInitializer(*this, ClassDecl,
4245                                   Context.getTypeDeclType(Type),
4246                                   DirectBaseSpec, VirtualBaseSpec)) {
4247             // We have found a direct or virtual base class with a
4248             // similar name to what was typed; complain and initialize
4249             // that base class.
4250             diagnoseTypo(Corr,
4251                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4252                            << MemberOrBase << false,
4253                          PDiag() /*Suppress note, we provide our own.*/);
4254 
4255             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4256                                                               : VirtualBaseSpec;
4257             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4258                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4259 
4260             TyD = Type;
4261           }
4262         }
4263       }
4264 
4265       if (!TyD && BaseType.isNull()) {
4266         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4267           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4268         return true;
4269       }
4270     }
4271 
4272     if (BaseType.isNull()) {
4273       BaseType = Context.getTypeDeclType(TyD);
4274       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4275       if (SS.isSet()) {
4276         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4277                                              BaseType);
4278         TInfo = Context.CreateTypeSourceInfo(BaseType);
4279         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4280         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4281         TL.setElaboratedKeywordLoc(SourceLocation());
4282         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4283       }
4284     }
4285   }
4286 
4287   if (!TInfo)
4288     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4289 
4290   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4291 }
4292 
4293 MemInitResult
4294 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4295                              SourceLocation IdLoc) {
4296   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4297   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4298   assert((DirectMember || IndirectMember) &&
4299          "Member must be a FieldDecl or IndirectFieldDecl");
4300 
4301   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4302     return true;
4303 
4304   if (Member->isInvalidDecl())
4305     return true;
4306 
4307   MultiExprArg Args;
4308   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4309     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4310   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4311     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4312   } else {
4313     // Template instantiation doesn't reconstruct ParenListExprs for us.
4314     Args = Init;
4315   }
4316 
4317   SourceRange InitRange = Init->getSourceRange();
4318 
4319   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4320     // Can't check initialization for a member of dependent type or when
4321     // any of the arguments are type-dependent expressions.
4322     DiscardCleanupsInEvaluationContext();
4323   } else {
4324     bool InitList = false;
4325     if (isa<InitListExpr>(Init)) {
4326       InitList = true;
4327       Args = Init;
4328     }
4329 
4330     // Initialize the member.
4331     InitializedEntity MemberEntity =
4332       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4333                    : InitializedEntity::InitializeMember(IndirectMember,
4334                                                          nullptr);
4335     InitializationKind Kind =
4336         InitList ? InitializationKind::CreateDirectList(
4337                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4338                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4339                                                     InitRange.getEnd());
4340 
4341     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4342     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4343                                             nullptr);
4344     if (MemberInit.isInvalid())
4345       return true;
4346 
4347     // C++11 [class.base.init]p7:
4348     //   The initialization of each base and member constitutes a
4349     //   full-expression.
4350     MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4351                                      /*DiscardedValue*/ false);
4352     if (MemberInit.isInvalid())
4353       return true;
4354 
4355     Init = MemberInit.get();
4356   }
4357 
4358   if (DirectMember) {
4359     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4360                                             InitRange.getBegin(), Init,
4361                                             InitRange.getEnd());
4362   } else {
4363     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4364                                             InitRange.getBegin(), Init,
4365                                             InitRange.getEnd());
4366   }
4367 }
4368 
4369 MemInitResult
4370 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4371                                  CXXRecordDecl *ClassDecl) {
4372   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4373   if (!LangOpts.CPlusPlus11)
4374     return Diag(NameLoc, diag::err_delegating_ctor)
4375       << TInfo->getTypeLoc().getLocalSourceRange();
4376   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4377 
4378   bool InitList = true;
4379   MultiExprArg Args = Init;
4380   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4381     InitList = false;
4382     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4383   }
4384 
4385   SourceRange InitRange = Init->getSourceRange();
4386   // Initialize the object.
4387   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4388                                      QualType(ClassDecl->getTypeForDecl(), 0));
4389   InitializationKind Kind =
4390       InitList ? InitializationKind::CreateDirectList(
4391                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4392                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4393                                                   InitRange.getEnd());
4394   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4395   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4396                                               Args, nullptr);
4397   if (DelegationInit.isInvalid())
4398     return true;
4399 
4400   assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4401          "Delegating constructor with no target?");
4402 
4403   // C++11 [class.base.init]p7:
4404   //   The initialization of each base and member constitutes a
4405   //   full-expression.
4406   DelegationInit = ActOnFinishFullExpr(
4407       DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4408   if (DelegationInit.isInvalid())
4409     return true;
4410 
4411   // If we are in a dependent context, template instantiation will
4412   // perform this type-checking again. Just save the arguments that we
4413   // received in a ParenListExpr.
4414   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4415   // of the information that we have about the base
4416   // initializer. However, deconstructing the ASTs is a dicey process,
4417   // and this approach is far more likely to get the corner cases right.
4418   if (CurContext->isDependentContext())
4419     DelegationInit = Init;
4420 
4421   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4422                                           DelegationInit.getAs<Expr>(),
4423                                           InitRange.getEnd());
4424 }
4425 
4426 MemInitResult
4427 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4428                            Expr *Init, CXXRecordDecl *ClassDecl,
4429                            SourceLocation EllipsisLoc) {
4430   SourceLocation BaseLoc
4431     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4432 
4433   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4434     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4435              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4436 
4437   // C++ [class.base.init]p2:
4438   //   [...] Unless the mem-initializer-id names a nonstatic data
4439   //   member of the constructor's class or a direct or virtual base
4440   //   of that class, the mem-initializer is ill-formed. A
4441   //   mem-initializer-list can initialize a base class using any
4442   //   name that denotes that base class type.
4443   bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4444 
4445   SourceRange InitRange = Init->getSourceRange();
4446   if (EllipsisLoc.isValid()) {
4447     // This is a pack expansion.
4448     if (!BaseType->containsUnexpandedParameterPack())  {
4449       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4450         << SourceRange(BaseLoc, InitRange.getEnd());
4451 
4452       EllipsisLoc = SourceLocation();
4453     }
4454   } else {
4455     // Check for any unexpanded parameter packs.
4456     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4457       return true;
4458 
4459     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4460       return true;
4461   }
4462 
4463   // Check for direct and virtual base classes.
4464   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4465   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4466   if (!Dependent) {
4467     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4468                                        BaseType))
4469       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4470 
4471     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4472                         VirtualBaseSpec);
4473 
4474     // C++ [base.class.init]p2:
4475     // Unless the mem-initializer-id names a nonstatic data member of the
4476     // constructor's class or a direct or virtual base of that class, the
4477     // mem-initializer is ill-formed.
4478     if (!DirectBaseSpec && !VirtualBaseSpec) {
4479       // If the class has any dependent bases, then it's possible that
4480       // one of those types will resolve to the same type as
4481       // BaseType. Therefore, just treat this as a dependent base
4482       // class initialization.  FIXME: Should we try to check the
4483       // initialization anyway? It seems odd.
4484       if (ClassDecl->hasAnyDependentBases())
4485         Dependent = true;
4486       else
4487         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4488           << BaseType << Context.getTypeDeclType(ClassDecl)
4489           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4490     }
4491   }
4492 
4493   if (Dependent) {
4494     DiscardCleanupsInEvaluationContext();
4495 
4496     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4497                                             /*IsVirtual=*/false,
4498                                             InitRange.getBegin(), Init,
4499                                             InitRange.getEnd(), EllipsisLoc);
4500   }
4501 
4502   // C++ [base.class.init]p2:
4503   //   If a mem-initializer-id is ambiguous because it designates both
4504   //   a direct non-virtual base class and an inherited virtual base
4505   //   class, the mem-initializer is ill-formed.
4506   if (DirectBaseSpec && VirtualBaseSpec)
4507     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4508       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4509 
4510   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4511   if (!BaseSpec)
4512     BaseSpec = VirtualBaseSpec;
4513 
4514   // Initialize the base.
4515   bool InitList = true;
4516   MultiExprArg Args = Init;
4517   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4518     InitList = false;
4519     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4520   }
4521 
4522   InitializedEntity BaseEntity =
4523     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4524   InitializationKind Kind =
4525       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4526                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4527                                                   InitRange.getEnd());
4528   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4529   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4530   if (BaseInit.isInvalid())
4531     return true;
4532 
4533   // C++11 [class.base.init]p7:
4534   //   The initialization of each base and member constitutes a
4535   //   full-expression.
4536   BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4537                                  /*DiscardedValue*/ false);
4538   if (BaseInit.isInvalid())
4539     return true;
4540 
4541   // If we are in a dependent context, template instantiation will
4542   // perform this type-checking again. Just save the arguments that we
4543   // received in a ParenListExpr.
4544   // FIXME: This isn't quite ideal, since our ASTs don't capture all
4545   // of the information that we have about the base
4546   // initializer. However, deconstructing the ASTs is a dicey process,
4547   // and this approach is far more likely to get the corner cases right.
4548   if (CurContext->isDependentContext())
4549     BaseInit = Init;
4550 
4551   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4552                                           BaseSpec->isVirtual(),
4553                                           InitRange.getBegin(),
4554                                           BaseInit.getAs<Expr>(),
4555                                           InitRange.getEnd(), EllipsisLoc);
4556 }
4557 
4558 // Create a static_cast\<T&&>(expr).
4559 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4560   if (T.isNull()) T = E->getType();
4561   QualType TargetType = SemaRef.BuildReferenceType(
4562       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4563   SourceLocation ExprLoc = E->getBeginLoc();
4564   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4565       TargetType, ExprLoc);
4566 
4567   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4568                                    SourceRange(ExprLoc, ExprLoc),
4569                                    E->getSourceRange()).get();
4570 }
4571 
4572 /// ImplicitInitializerKind - How an implicit base or member initializer should
4573 /// initialize its base or member.
4574 enum ImplicitInitializerKind {
4575   IIK_Default,
4576   IIK_Copy,
4577   IIK_Move,
4578   IIK_Inherit
4579 };
4580 
4581 static bool
4582 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4583                              ImplicitInitializerKind ImplicitInitKind,
4584                              CXXBaseSpecifier *BaseSpec,
4585                              bool IsInheritedVirtualBase,
4586                              CXXCtorInitializer *&CXXBaseInit) {
4587   InitializedEntity InitEntity
4588     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4589                                         IsInheritedVirtualBase);
4590 
4591   ExprResult BaseInit;
4592 
4593   switch (ImplicitInitKind) {
4594   case IIK_Inherit:
4595   case IIK_Default: {
4596     InitializationKind InitKind
4597       = InitializationKind::CreateDefault(Constructor->getLocation());
4598     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4599     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4600     break;
4601   }
4602 
4603   case IIK_Move:
4604   case IIK_Copy: {
4605     bool Moving = ImplicitInitKind == IIK_Move;
4606     ParmVarDecl *Param = Constructor->getParamDecl(0);
4607     QualType ParamType = Param->getType().getNonReferenceType();
4608 
4609     Expr *CopyCtorArg =
4610       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4611                           SourceLocation(), Param, false,
4612                           Constructor->getLocation(), ParamType,
4613                           VK_LValue, nullptr);
4614 
4615     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4616 
4617     // Cast to the base class to avoid ambiguities.
4618     QualType ArgTy =
4619       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4620                                        ParamType.getQualifiers());
4621 
4622     if (Moving) {
4623       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4624     }
4625 
4626     CXXCastPath BasePath;
4627     BasePath.push_back(BaseSpec);
4628     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4629                                             CK_UncheckedDerivedToBase,
4630                                             Moving ? VK_XValue : VK_LValue,
4631                                             &BasePath).get();
4632 
4633     InitializationKind InitKind
4634       = InitializationKind::CreateDirect(Constructor->getLocation(),
4635                                          SourceLocation(), SourceLocation());
4636     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4637     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4638     break;
4639   }
4640   }
4641 
4642   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4643   if (BaseInit.isInvalid())
4644     return true;
4645 
4646   CXXBaseInit =
4647     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4648                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4649                                                         SourceLocation()),
4650                                              BaseSpec->isVirtual(),
4651                                              SourceLocation(),
4652                                              BaseInit.getAs<Expr>(),
4653                                              SourceLocation(),
4654                                              SourceLocation());
4655 
4656   return false;
4657 }
4658 
4659 static bool RefersToRValueRef(Expr *MemRef) {
4660   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4661   return Referenced->getType()->isRValueReferenceType();
4662 }
4663 
4664 static bool
4665 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4666                                ImplicitInitializerKind ImplicitInitKind,
4667                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4668                                CXXCtorInitializer *&CXXMemberInit) {
4669   if (Field->isInvalidDecl())
4670     return true;
4671 
4672   SourceLocation Loc = Constructor->getLocation();
4673 
4674   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4675     bool Moving = ImplicitInitKind == IIK_Move;
4676     ParmVarDecl *Param = Constructor->getParamDecl(0);
4677     QualType ParamType = Param->getType().getNonReferenceType();
4678 
4679     // Suppress copying zero-width bitfields.
4680     if (Field->isZeroLengthBitField(SemaRef.Context))
4681       return false;
4682 
4683     Expr *MemberExprBase =
4684       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4685                           SourceLocation(), Param, false,
4686                           Loc, ParamType, VK_LValue, nullptr);
4687 
4688     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4689 
4690     if (Moving) {
4691       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4692     }
4693 
4694     // Build a reference to this field within the parameter.
4695     CXXScopeSpec SS;
4696     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4697                               Sema::LookupMemberName);
4698     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4699                                   : cast<ValueDecl>(Field), AS_public);
4700     MemberLookup.resolveKind();
4701     ExprResult CtorArg
4702       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4703                                          ParamType, Loc,
4704                                          /*IsArrow=*/false,
4705                                          SS,
4706                                          /*TemplateKWLoc=*/SourceLocation(),
4707                                          /*FirstQualifierInScope=*/nullptr,
4708                                          MemberLookup,
4709                                          /*TemplateArgs=*/nullptr,
4710                                          /*S*/nullptr);
4711     if (CtorArg.isInvalid())
4712       return true;
4713 
4714     // C++11 [class.copy]p15:
4715     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4716     //     with static_cast<T&&>(x.m);
4717     if (RefersToRValueRef(CtorArg.get())) {
4718       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4719     }
4720 
4721     InitializedEntity Entity =
4722         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4723                                                        /*Implicit*/ true)
4724                  : InitializedEntity::InitializeMember(Field, nullptr,
4725                                                        /*Implicit*/ true);
4726 
4727     // Direct-initialize to use the copy constructor.
4728     InitializationKind InitKind =
4729       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4730 
4731     Expr *CtorArgE = CtorArg.getAs<Expr>();
4732     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4733     ExprResult MemberInit =
4734         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4735     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4736     if (MemberInit.isInvalid())
4737       return true;
4738 
4739     if (Indirect)
4740       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4741           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4742     else
4743       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4744           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4745     return false;
4746   }
4747 
4748   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4749          "Unhandled implicit init kind!");
4750 
4751   QualType FieldBaseElementType =
4752     SemaRef.Context.getBaseElementType(Field->getType());
4753 
4754   if (FieldBaseElementType->isRecordType()) {
4755     InitializedEntity InitEntity =
4756         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4757                                                        /*Implicit*/ true)
4758                  : InitializedEntity::InitializeMember(Field, nullptr,
4759                                                        /*Implicit*/ true);
4760     InitializationKind InitKind =
4761       InitializationKind::CreateDefault(Loc);
4762 
4763     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4764     ExprResult MemberInit =
4765       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4766 
4767     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4768     if (MemberInit.isInvalid())
4769       return true;
4770 
4771     if (Indirect)
4772       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4773                                                                Indirect, Loc,
4774                                                                Loc,
4775                                                                MemberInit.get(),
4776                                                                Loc);
4777     else
4778       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4779                                                                Field, Loc, Loc,
4780                                                                MemberInit.get(),
4781                                                                Loc);
4782     return false;
4783   }
4784 
4785   if (!Field->getParent()->isUnion()) {
4786     if (FieldBaseElementType->isReferenceType()) {
4787       SemaRef.Diag(Constructor->getLocation(),
4788                    diag::err_uninitialized_member_in_ctor)
4789       << (int)Constructor->isImplicit()
4790       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4791       << 0 << Field->getDeclName();
4792       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4793       return true;
4794     }
4795 
4796     if (FieldBaseElementType.isConstQualified()) {
4797       SemaRef.Diag(Constructor->getLocation(),
4798                    diag::err_uninitialized_member_in_ctor)
4799       << (int)Constructor->isImplicit()
4800       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4801       << 1 << Field->getDeclName();
4802       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4803       return true;
4804     }
4805   }
4806 
4807   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4808     // ARC and Weak:
4809     //   Default-initialize Objective-C pointers to NULL.
4810     CXXMemberInit
4811       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4812                                                  Loc, Loc,
4813                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4814                                                  Loc);
4815     return false;
4816   }
4817 
4818   // Nothing to initialize.
4819   CXXMemberInit = nullptr;
4820   return false;
4821 }
4822 
4823 namespace {
4824 struct BaseAndFieldInfo {
4825   Sema &S;
4826   CXXConstructorDecl *Ctor;
4827   bool AnyErrorsInInits;
4828   ImplicitInitializerKind IIK;
4829   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4830   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4831   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4832 
4833   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4834     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4835     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4836     if (Ctor->getInheritedConstructor())
4837       IIK = IIK_Inherit;
4838     else if (Generated && Ctor->isCopyConstructor())
4839       IIK = IIK_Copy;
4840     else if (Generated && Ctor->isMoveConstructor())
4841       IIK = IIK_Move;
4842     else
4843       IIK = IIK_Default;
4844   }
4845 
4846   bool isImplicitCopyOrMove() const {
4847     switch (IIK) {
4848     case IIK_Copy:
4849     case IIK_Move:
4850       return true;
4851 
4852     case IIK_Default:
4853     case IIK_Inherit:
4854       return false;
4855     }
4856 
4857     llvm_unreachable("Invalid ImplicitInitializerKind!");
4858   }
4859 
4860   bool addFieldInitializer(CXXCtorInitializer *Init) {
4861     AllToInit.push_back(Init);
4862 
4863     // Check whether this initializer makes the field "used".
4864     if (Init->getInit()->HasSideEffects(S.Context))
4865       S.UnusedPrivateFields.remove(Init->getAnyMember());
4866 
4867     return false;
4868   }
4869 
4870   bool isInactiveUnionMember(FieldDecl *Field) {
4871     RecordDecl *Record = Field->getParent();
4872     if (!Record->isUnion())
4873       return false;
4874 
4875     if (FieldDecl *Active =
4876             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4877       return Active != Field->getCanonicalDecl();
4878 
4879     // In an implicit copy or move constructor, ignore any in-class initializer.
4880     if (isImplicitCopyOrMove())
4881       return true;
4882 
4883     // If there's no explicit initialization, the field is active only if it
4884     // has an in-class initializer...
4885     if (Field->hasInClassInitializer())
4886       return false;
4887     // ... or it's an anonymous struct or union whose class has an in-class
4888     // initializer.
4889     if (!Field->isAnonymousStructOrUnion())
4890       return true;
4891     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4892     return !FieldRD->hasInClassInitializer();
4893   }
4894 
4895   /// Determine whether the given field is, or is within, a union member
4896   /// that is inactive (because there was an initializer given for a different
4897   /// member of the union, or because the union was not initialized at all).
4898   bool isWithinInactiveUnionMember(FieldDecl *Field,
4899                                    IndirectFieldDecl *Indirect) {
4900     if (!Indirect)
4901       return isInactiveUnionMember(Field);
4902 
4903     for (auto *C : Indirect->chain()) {
4904       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4905       if (Field && isInactiveUnionMember(Field))
4906         return true;
4907     }
4908     return false;
4909   }
4910 };
4911 }
4912 
4913 /// Determine whether the given type is an incomplete or zero-lenfgth
4914 /// array type.
4915 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4916   if (T->isIncompleteArrayType())
4917     return true;
4918 
4919   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4920     if (!ArrayT->getSize())
4921       return true;
4922 
4923     T = ArrayT->getElementType();
4924   }
4925 
4926   return false;
4927 }
4928 
4929 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4930                                     FieldDecl *Field,
4931                                     IndirectFieldDecl *Indirect = nullptr) {
4932   if (Field->isInvalidDecl())
4933     return false;
4934 
4935   // Overwhelmingly common case: we have a direct initializer for this field.
4936   if (CXXCtorInitializer *Init =
4937           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4938     return Info.addFieldInitializer(Init);
4939 
4940   // C++11 [class.base.init]p8:
4941   //   if the entity is a non-static data member that has a
4942   //   brace-or-equal-initializer and either
4943   //   -- the constructor's class is a union and no other variant member of that
4944   //      union is designated by a mem-initializer-id or
4945   //   -- the constructor's class is not a union, and, if the entity is a member
4946   //      of an anonymous union, no other member of that union is designated by
4947   //      a mem-initializer-id,
4948   //   the entity is initialized as specified in [dcl.init].
4949   //
4950   // We also apply the same rules to handle anonymous structs within anonymous
4951   // unions.
4952   if (Info.isWithinInactiveUnionMember(Field, Indirect))
4953     return false;
4954 
4955   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4956     ExprResult DIE =
4957         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4958     if (DIE.isInvalid())
4959       return true;
4960 
4961     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4962     SemaRef.checkInitializerLifetime(Entity, DIE.get());
4963 
4964     CXXCtorInitializer *Init;
4965     if (Indirect)
4966       Init = new (SemaRef.Context)
4967           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4968                              SourceLocation(), DIE.get(), SourceLocation());
4969     else
4970       Init = new (SemaRef.Context)
4971           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4972                              SourceLocation(), DIE.get(), SourceLocation());
4973     return Info.addFieldInitializer(Init);
4974   }
4975 
4976   // Don't initialize incomplete or zero-length arrays.
4977   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4978     return false;
4979 
4980   // Don't try to build an implicit initializer if there were semantic
4981   // errors in any of the initializers (and therefore we might be
4982   // missing some that the user actually wrote).
4983   if (Info.AnyErrorsInInits)
4984     return false;
4985 
4986   CXXCtorInitializer *Init = nullptr;
4987   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4988                                      Indirect, Init))
4989     return true;
4990 
4991   if (!Init)
4992     return false;
4993 
4994   return Info.addFieldInitializer(Init);
4995 }
4996 
4997 bool
4998 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4999                                CXXCtorInitializer *Initializer) {
5000   assert(Initializer->isDelegatingInitializer());
5001   Constructor->setNumCtorInitializers(1);
5002   CXXCtorInitializer **initializer =
5003     new (Context) CXXCtorInitializer*[1];
5004   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5005   Constructor->setCtorInitializers(initializer);
5006 
5007   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5008     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5009     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5010   }
5011 
5012   DelegatingCtorDecls.push_back(Constructor);
5013 
5014   DiagnoseUninitializedFields(*this, Constructor);
5015 
5016   return false;
5017 }
5018 
5019 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5020                                ArrayRef<CXXCtorInitializer *> Initializers) {
5021   if (Constructor->isDependentContext()) {
5022     // Just store the initializers as written, they will be checked during
5023     // instantiation.
5024     if (!Initializers.empty()) {
5025       Constructor->setNumCtorInitializers(Initializers.size());
5026       CXXCtorInitializer **baseOrMemberInitializers =
5027         new (Context) CXXCtorInitializer*[Initializers.size()];
5028       memcpy(baseOrMemberInitializers, Initializers.data(),
5029              Initializers.size() * sizeof(CXXCtorInitializer*));
5030       Constructor->setCtorInitializers(baseOrMemberInitializers);
5031     }
5032 
5033     // Let template instantiation know whether we had errors.
5034     if (AnyErrors)
5035       Constructor->setInvalidDecl();
5036 
5037     return false;
5038   }
5039 
5040   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5041 
5042   // We need to build the initializer AST according to order of construction
5043   // and not what user specified in the Initializers list.
5044   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5045   if (!ClassDecl)
5046     return true;
5047 
5048   bool HadError = false;
5049 
5050   for (unsigned i = 0; i < Initializers.size(); i++) {
5051     CXXCtorInitializer *Member = Initializers[i];
5052 
5053     if (Member->isBaseInitializer())
5054       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5055     else {
5056       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5057 
5058       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5059         for (auto *C : F->chain()) {
5060           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5061           if (FD && FD->getParent()->isUnion())
5062             Info.ActiveUnionMember.insert(std::make_pair(
5063                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5064         }
5065       } else if (FieldDecl *FD = Member->getMember()) {
5066         if (FD->getParent()->isUnion())
5067           Info.ActiveUnionMember.insert(std::make_pair(
5068               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5069       }
5070     }
5071   }
5072 
5073   // Keep track of the direct virtual bases.
5074   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5075   for (auto &I : ClassDecl->bases()) {
5076     if (I.isVirtual())
5077       DirectVBases.insert(&I);
5078   }
5079 
5080   // Push virtual bases before others.
5081   for (auto &VBase : ClassDecl->vbases()) {
5082     if (CXXCtorInitializer *Value
5083         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5084       // [class.base.init]p7, per DR257:
5085       //   A mem-initializer where the mem-initializer-id names a virtual base
5086       //   class is ignored during execution of a constructor of any class that
5087       //   is not the most derived class.
5088       if (ClassDecl->isAbstract()) {
5089         // FIXME: Provide a fixit to remove the base specifier. This requires
5090         // tracking the location of the associated comma for a base specifier.
5091         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5092           << VBase.getType() << ClassDecl;
5093         DiagnoseAbstractType(ClassDecl);
5094       }
5095 
5096       Info.AllToInit.push_back(Value);
5097     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5098       // [class.base.init]p8, per DR257:
5099       //   If a given [...] base class is not named by a mem-initializer-id
5100       //   [...] and the entity is not a virtual base class of an abstract
5101       //   class, then [...] the entity is default-initialized.
5102       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5103       CXXCtorInitializer *CXXBaseInit;
5104       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5105                                        &VBase, IsInheritedVirtualBase,
5106                                        CXXBaseInit)) {
5107         HadError = true;
5108         continue;
5109       }
5110 
5111       Info.AllToInit.push_back(CXXBaseInit);
5112     }
5113   }
5114 
5115   // Non-virtual bases.
5116   for (auto &Base : ClassDecl->bases()) {
5117     // Virtuals are in the virtual base list and already constructed.
5118     if (Base.isVirtual())
5119       continue;
5120 
5121     if (CXXCtorInitializer *Value
5122           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5123       Info.AllToInit.push_back(Value);
5124     } else if (!AnyErrors) {
5125       CXXCtorInitializer *CXXBaseInit;
5126       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5127                                        &Base, /*IsInheritedVirtualBase=*/false,
5128                                        CXXBaseInit)) {
5129         HadError = true;
5130         continue;
5131       }
5132 
5133       Info.AllToInit.push_back(CXXBaseInit);
5134     }
5135   }
5136 
5137   // Fields.
5138   for (auto *Mem : ClassDecl->decls()) {
5139     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5140       // C++ [class.bit]p2:
5141       //   A declaration for a bit-field that omits the identifier declares an
5142       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5143       //   initialized.
5144       if (F->isUnnamedBitfield())
5145         continue;
5146 
5147       // If we're not generating the implicit copy/move constructor, then we'll
5148       // handle anonymous struct/union fields based on their individual
5149       // indirect fields.
5150       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5151         continue;
5152 
5153       if (CollectFieldInitializer(*this, Info, F))
5154         HadError = true;
5155       continue;
5156     }
5157 
5158     // Beyond this point, we only consider default initialization.
5159     if (Info.isImplicitCopyOrMove())
5160       continue;
5161 
5162     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5163       if (F->getType()->isIncompleteArrayType()) {
5164         assert(ClassDecl->hasFlexibleArrayMember() &&
5165                "Incomplete array type is not valid");
5166         continue;
5167       }
5168 
5169       // Initialize each field of an anonymous struct individually.
5170       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5171         HadError = true;
5172 
5173       continue;
5174     }
5175   }
5176 
5177   unsigned NumInitializers = Info.AllToInit.size();
5178   if (NumInitializers > 0) {
5179     Constructor->setNumCtorInitializers(NumInitializers);
5180     CXXCtorInitializer **baseOrMemberInitializers =
5181       new (Context) CXXCtorInitializer*[NumInitializers];
5182     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5183            NumInitializers * sizeof(CXXCtorInitializer*));
5184     Constructor->setCtorInitializers(baseOrMemberInitializers);
5185 
5186     // Constructors implicitly reference the base and member
5187     // destructors.
5188     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5189                                            Constructor->getParent());
5190   }
5191 
5192   return HadError;
5193 }
5194 
5195 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5196   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5197     const RecordDecl *RD = RT->getDecl();
5198     if (RD->isAnonymousStructOrUnion()) {
5199       for (auto *Field : RD->fields())
5200         PopulateKeysForFields(Field, IdealInits);
5201       return;
5202     }
5203   }
5204   IdealInits.push_back(Field->getCanonicalDecl());
5205 }
5206 
5207 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5208   return Context.getCanonicalType(BaseType).getTypePtr();
5209 }
5210 
5211 static const void *GetKeyForMember(ASTContext &Context,
5212                                    CXXCtorInitializer *Member) {
5213   if (!Member->isAnyMemberInitializer())
5214     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5215 
5216   return Member->getAnyMember()->getCanonicalDecl();
5217 }
5218 
5219 static void DiagnoseBaseOrMemInitializerOrder(
5220     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5221     ArrayRef<CXXCtorInitializer *> Inits) {
5222   if (Constructor->getDeclContext()->isDependentContext())
5223     return;
5224 
5225   // Don't check initializers order unless the warning is enabled at the
5226   // location of at least one initializer.
5227   bool ShouldCheckOrder = false;
5228   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5229     CXXCtorInitializer *Init = Inits[InitIndex];
5230     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5231                                  Init->getSourceLocation())) {
5232       ShouldCheckOrder = true;
5233       break;
5234     }
5235   }
5236   if (!ShouldCheckOrder)
5237     return;
5238 
5239   // Build the list of bases and members in the order that they'll
5240   // actually be initialized.  The explicit initializers should be in
5241   // this same order but may be missing things.
5242   SmallVector<const void*, 32> IdealInitKeys;
5243 
5244   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5245 
5246   // 1. Virtual bases.
5247   for (const auto &VBase : ClassDecl->vbases())
5248     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5249 
5250   // 2. Non-virtual bases.
5251   for (const auto &Base : ClassDecl->bases()) {
5252     if (Base.isVirtual())
5253       continue;
5254     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5255   }
5256 
5257   // 3. Direct fields.
5258   for (auto *Field : ClassDecl->fields()) {
5259     if (Field->isUnnamedBitfield())
5260       continue;
5261 
5262     PopulateKeysForFields(Field, IdealInitKeys);
5263   }
5264 
5265   unsigned NumIdealInits = IdealInitKeys.size();
5266   unsigned IdealIndex = 0;
5267 
5268   CXXCtorInitializer *PrevInit = nullptr;
5269   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5270     CXXCtorInitializer *Init = Inits[InitIndex];
5271     const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5272 
5273     // Scan forward to try to find this initializer in the idealized
5274     // initializers list.
5275     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5276       if (InitKey == IdealInitKeys[IdealIndex])
5277         break;
5278 
5279     // If we didn't find this initializer, it must be because we
5280     // scanned past it on a previous iteration.  That can only
5281     // happen if we're out of order;  emit a warning.
5282     if (IdealIndex == NumIdealInits && PrevInit) {
5283       Sema::SemaDiagnosticBuilder D =
5284         SemaRef.Diag(PrevInit->getSourceLocation(),
5285                      diag::warn_initializer_out_of_order);
5286 
5287       if (PrevInit->isAnyMemberInitializer())
5288         D << 0 << PrevInit->getAnyMember()->getDeclName();
5289       else
5290         D << 1 << PrevInit->getTypeSourceInfo()->getType();
5291 
5292       if (Init->isAnyMemberInitializer())
5293         D << 0 << Init->getAnyMember()->getDeclName();
5294       else
5295         D << 1 << Init->getTypeSourceInfo()->getType();
5296 
5297       // Move back to the initializer's location in the ideal list.
5298       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5299         if (InitKey == IdealInitKeys[IdealIndex])
5300           break;
5301 
5302       assert(IdealIndex < NumIdealInits &&
5303              "initializer not found in initializer list");
5304     }
5305 
5306     PrevInit = Init;
5307   }
5308 }
5309 
5310 namespace {
5311 bool CheckRedundantInit(Sema &S,
5312                         CXXCtorInitializer *Init,
5313                         CXXCtorInitializer *&PrevInit) {
5314   if (!PrevInit) {
5315     PrevInit = Init;
5316     return false;
5317   }
5318 
5319   if (FieldDecl *Field = Init->getAnyMember())
5320     S.Diag(Init->getSourceLocation(),
5321            diag::err_multiple_mem_initialization)
5322       << Field->getDeclName()
5323       << Init->getSourceRange();
5324   else {
5325     const Type *BaseClass = Init->getBaseClass();
5326     assert(BaseClass && "neither field nor base");
5327     S.Diag(Init->getSourceLocation(),
5328            diag::err_multiple_base_initialization)
5329       << QualType(BaseClass, 0)
5330       << Init->getSourceRange();
5331   }
5332   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5333     << 0 << PrevInit->getSourceRange();
5334 
5335   return true;
5336 }
5337 
5338 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5339 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5340 
5341 bool CheckRedundantUnionInit(Sema &S,
5342                              CXXCtorInitializer *Init,
5343                              RedundantUnionMap &Unions) {
5344   FieldDecl *Field = Init->getAnyMember();
5345   RecordDecl *Parent = Field->getParent();
5346   NamedDecl *Child = Field;
5347 
5348   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5349     if (Parent->isUnion()) {
5350       UnionEntry &En = Unions[Parent];
5351       if (En.first && En.first != Child) {
5352         S.Diag(Init->getSourceLocation(),
5353                diag::err_multiple_mem_union_initialization)
5354           << Field->getDeclName()
5355           << Init->getSourceRange();
5356         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5357           << 0 << En.second->getSourceRange();
5358         return true;
5359       }
5360       if (!En.first) {
5361         En.first = Child;
5362         En.second = Init;
5363       }
5364       if (!Parent->isAnonymousStructOrUnion())
5365         return false;
5366     }
5367 
5368     Child = Parent;
5369     Parent = cast<RecordDecl>(Parent->getDeclContext());
5370   }
5371 
5372   return false;
5373 }
5374 }
5375 
5376 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5377 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5378                                 SourceLocation ColonLoc,
5379                                 ArrayRef<CXXCtorInitializer*> MemInits,
5380                                 bool AnyErrors) {
5381   if (!ConstructorDecl)
5382     return;
5383 
5384   AdjustDeclIfTemplate(ConstructorDecl);
5385 
5386   CXXConstructorDecl *Constructor
5387     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5388 
5389   if (!Constructor) {
5390     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5391     return;
5392   }
5393 
5394   // Mapping for the duplicate initializers check.
5395   // For member initializers, this is keyed with a FieldDecl*.
5396   // For base initializers, this is keyed with a Type*.
5397   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5398 
5399   // Mapping for the inconsistent anonymous-union initializers check.
5400   RedundantUnionMap MemberUnions;
5401 
5402   bool HadError = false;
5403   for (unsigned i = 0; i < MemInits.size(); i++) {
5404     CXXCtorInitializer *Init = MemInits[i];
5405 
5406     // Set the source order index.
5407     Init->setSourceOrder(i);
5408 
5409     if (Init->isAnyMemberInitializer()) {
5410       const void *Key = GetKeyForMember(Context, Init);
5411       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5412           CheckRedundantUnionInit(*this, Init, MemberUnions))
5413         HadError = true;
5414     } else if (Init->isBaseInitializer()) {
5415       const void *Key = GetKeyForMember(Context, Init);
5416       if (CheckRedundantInit(*this, Init, Members[Key]))
5417         HadError = true;
5418     } else {
5419       assert(Init->isDelegatingInitializer());
5420       // This must be the only initializer
5421       if (MemInits.size() != 1) {
5422         Diag(Init->getSourceLocation(),
5423              diag::err_delegating_initializer_alone)
5424           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5425         // We will treat this as being the only initializer.
5426       }
5427       SetDelegatingInitializer(Constructor, MemInits[i]);
5428       // Return immediately as the initializer is set.
5429       return;
5430     }
5431   }
5432 
5433   if (HadError)
5434     return;
5435 
5436   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5437 
5438   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5439 
5440   DiagnoseUninitializedFields(*this, Constructor);
5441 }
5442 
5443 void
5444 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5445                                              CXXRecordDecl *ClassDecl) {
5446   // Ignore dependent contexts. Also ignore unions, since their members never
5447   // have destructors implicitly called.
5448   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5449     return;
5450 
5451   // FIXME: all the access-control diagnostics are positioned on the
5452   // field/base declaration.  That's probably good; that said, the
5453   // user might reasonably want to know why the destructor is being
5454   // emitted, and we currently don't say.
5455 
5456   // Non-static data members.
5457   for (auto *Field : ClassDecl->fields()) {
5458     if (Field->isInvalidDecl())
5459       continue;
5460 
5461     // Don't destroy incomplete or zero-length arrays.
5462     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5463       continue;
5464 
5465     QualType FieldType = Context.getBaseElementType(Field->getType());
5466 
5467     const RecordType* RT = FieldType->getAs<RecordType>();
5468     if (!RT)
5469       continue;
5470 
5471     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5472     if (FieldClassDecl->isInvalidDecl())
5473       continue;
5474     if (FieldClassDecl->hasIrrelevantDestructor())
5475       continue;
5476     // The destructor for an implicit anonymous union member is never invoked.
5477     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5478       continue;
5479 
5480     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5481     assert(Dtor && "No dtor found for FieldClassDecl!");
5482     CheckDestructorAccess(Field->getLocation(), Dtor,
5483                           PDiag(diag::err_access_dtor_field)
5484                             << Field->getDeclName()
5485                             << FieldType);
5486 
5487     MarkFunctionReferenced(Location, Dtor);
5488     DiagnoseUseOfDecl(Dtor, Location);
5489   }
5490 
5491   // We only potentially invoke the destructors of potentially constructed
5492   // subobjects.
5493   bool VisitVirtualBases = !ClassDecl->isAbstract();
5494 
5495   // If the destructor exists and has already been marked used in the MS ABI,
5496   // then virtual base destructors have already been checked and marked used.
5497   // Skip checking them again to avoid duplicate diagnostics.
5498   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5499     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5500     if (Dtor && Dtor->isUsed())
5501       VisitVirtualBases = false;
5502   }
5503 
5504   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5505 
5506   // Bases.
5507   for (const auto &Base : ClassDecl->bases()) {
5508     // Bases are always records in a well-formed non-dependent class.
5509     const RecordType *RT = Base.getType()->getAs<RecordType>();
5510 
5511     // Remember direct virtual bases.
5512     if (Base.isVirtual()) {
5513       if (!VisitVirtualBases)
5514         continue;
5515       DirectVirtualBases.insert(RT);
5516     }
5517 
5518     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5519     // If our base class is invalid, we probably can't get its dtor anyway.
5520     if (BaseClassDecl->isInvalidDecl())
5521       continue;
5522     if (BaseClassDecl->hasIrrelevantDestructor())
5523       continue;
5524 
5525     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5526     assert(Dtor && "No dtor found for BaseClassDecl!");
5527 
5528     // FIXME: caret should be on the start of the class name
5529     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5530                           PDiag(diag::err_access_dtor_base)
5531                               << Base.getType() << Base.getSourceRange(),
5532                           Context.getTypeDeclType(ClassDecl));
5533 
5534     MarkFunctionReferenced(Location, Dtor);
5535     DiagnoseUseOfDecl(Dtor, Location);
5536   }
5537 
5538   if (VisitVirtualBases)
5539     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5540                                          &DirectVirtualBases);
5541 }
5542 
5543 void Sema::MarkVirtualBaseDestructorsReferenced(
5544     SourceLocation Location, CXXRecordDecl *ClassDecl,
5545     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5546   // Virtual bases.
5547   for (const auto &VBase : ClassDecl->vbases()) {
5548     // Bases are always records in a well-formed non-dependent class.
5549     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5550 
5551     // Ignore already visited direct virtual bases.
5552     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5553       continue;
5554 
5555     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5556     // If our base class is invalid, we probably can't get its dtor anyway.
5557     if (BaseClassDecl->isInvalidDecl())
5558       continue;
5559     if (BaseClassDecl->hasIrrelevantDestructor())
5560       continue;
5561 
5562     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5563     assert(Dtor && "No dtor found for BaseClassDecl!");
5564     if (CheckDestructorAccess(
5565             ClassDecl->getLocation(), Dtor,
5566             PDiag(diag::err_access_dtor_vbase)
5567                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5568             Context.getTypeDeclType(ClassDecl)) ==
5569         AR_accessible) {
5570       CheckDerivedToBaseConversion(
5571           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5572           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5573           SourceRange(), DeclarationName(), nullptr);
5574     }
5575 
5576     MarkFunctionReferenced(Location, Dtor);
5577     DiagnoseUseOfDecl(Dtor, Location);
5578   }
5579 }
5580 
5581 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5582   if (!CDtorDecl)
5583     return;
5584 
5585   if (CXXConstructorDecl *Constructor
5586       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5587     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5588     DiagnoseUninitializedFields(*this, Constructor);
5589   }
5590 }
5591 
5592 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5593   if (!getLangOpts().CPlusPlus)
5594     return false;
5595 
5596   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5597   if (!RD)
5598     return false;
5599 
5600   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5601   // class template specialization here, but doing so breaks a lot of code.
5602 
5603   // We can't answer whether something is abstract until it has a
5604   // definition. If it's currently being defined, we'll walk back
5605   // over all the declarations when we have a full definition.
5606   const CXXRecordDecl *Def = RD->getDefinition();
5607   if (!Def || Def->isBeingDefined())
5608     return false;
5609 
5610   return RD->isAbstract();
5611 }
5612 
5613 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5614                                   TypeDiagnoser &Diagnoser) {
5615   if (!isAbstractType(Loc, T))
5616     return false;
5617 
5618   T = Context.getBaseElementType(T);
5619   Diagnoser.diagnose(*this, Loc, T);
5620   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5621   return true;
5622 }
5623 
5624 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5625   // Check if we've already emitted the list of pure virtual functions
5626   // for this class.
5627   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5628     return;
5629 
5630   // If the diagnostic is suppressed, don't emit the notes. We're only
5631   // going to emit them once, so try to attach them to a diagnostic we're
5632   // actually going to show.
5633   if (Diags.isLastDiagnosticIgnored())
5634     return;
5635 
5636   CXXFinalOverriderMap FinalOverriders;
5637   RD->getFinalOverriders(FinalOverriders);
5638 
5639   // Keep a set of seen pure methods so we won't diagnose the same method
5640   // more than once.
5641   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5642 
5643   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5644                                    MEnd = FinalOverriders.end();
5645        M != MEnd;
5646        ++M) {
5647     for (OverridingMethods::iterator SO = M->second.begin(),
5648                                   SOEnd = M->second.end();
5649          SO != SOEnd; ++SO) {
5650       // C++ [class.abstract]p4:
5651       //   A class is abstract if it contains or inherits at least one
5652       //   pure virtual function for which the final overrider is pure
5653       //   virtual.
5654 
5655       //
5656       if (SO->second.size() != 1)
5657         continue;
5658 
5659       if (!SO->second.front().Method->isPure())
5660         continue;
5661 
5662       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5663         continue;
5664 
5665       Diag(SO->second.front().Method->getLocation(),
5666            diag::note_pure_virtual_function)
5667         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5668     }
5669   }
5670 
5671   if (!PureVirtualClassDiagSet)
5672     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5673   PureVirtualClassDiagSet->insert(RD);
5674 }
5675 
5676 namespace {
5677 struct AbstractUsageInfo {
5678   Sema &S;
5679   CXXRecordDecl *Record;
5680   CanQualType AbstractType;
5681   bool Invalid;
5682 
5683   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5684     : S(S), Record(Record),
5685       AbstractType(S.Context.getCanonicalType(
5686                    S.Context.getTypeDeclType(Record))),
5687       Invalid(false) {}
5688 
5689   void DiagnoseAbstractType() {
5690     if (Invalid) return;
5691     S.DiagnoseAbstractType(Record);
5692     Invalid = true;
5693   }
5694 
5695   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5696 };
5697 
5698 struct CheckAbstractUsage {
5699   AbstractUsageInfo &Info;
5700   const NamedDecl *Ctx;
5701 
5702   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5703     : Info(Info), Ctx(Ctx) {}
5704 
5705   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5706     switch (TL.getTypeLocClass()) {
5707 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5708 #define TYPELOC(CLASS, PARENT) \
5709     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5710 #include "clang/AST/TypeLocNodes.def"
5711     }
5712   }
5713 
5714   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5715     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5716     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5717       if (!TL.getParam(I))
5718         continue;
5719 
5720       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5721       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5722     }
5723   }
5724 
5725   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5726     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5727   }
5728 
5729   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5730     // Visit the type parameters from a permissive context.
5731     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5732       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5733       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5734         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5735           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5736       // TODO: other template argument types?
5737     }
5738   }
5739 
5740   // Visit pointee types from a permissive context.
5741 #define CheckPolymorphic(Type) \
5742   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5743     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5744   }
5745   CheckPolymorphic(PointerTypeLoc)
5746   CheckPolymorphic(ReferenceTypeLoc)
5747   CheckPolymorphic(MemberPointerTypeLoc)
5748   CheckPolymorphic(BlockPointerTypeLoc)
5749   CheckPolymorphic(AtomicTypeLoc)
5750 
5751   /// Handle all the types we haven't given a more specific
5752   /// implementation for above.
5753   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5754     // Every other kind of type that we haven't called out already
5755     // that has an inner type is either (1) sugar or (2) contains that
5756     // inner type in some way as a subobject.
5757     if (TypeLoc Next = TL.getNextTypeLoc())
5758       return Visit(Next, Sel);
5759 
5760     // If there's no inner type and we're in a permissive context,
5761     // don't diagnose.
5762     if (Sel == Sema::AbstractNone) return;
5763 
5764     // Check whether the type matches the abstract type.
5765     QualType T = TL.getType();
5766     if (T->isArrayType()) {
5767       Sel = Sema::AbstractArrayType;
5768       T = Info.S.Context.getBaseElementType(T);
5769     }
5770     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5771     if (CT != Info.AbstractType) return;
5772 
5773     // It matched; do some magic.
5774     if (Sel == Sema::AbstractArrayType) {
5775       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5776         << T << TL.getSourceRange();
5777     } else {
5778       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5779         << Sel << T << TL.getSourceRange();
5780     }
5781     Info.DiagnoseAbstractType();
5782   }
5783 };
5784 
5785 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5786                                   Sema::AbstractDiagSelID Sel) {
5787   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5788 }
5789 
5790 }
5791 
5792 /// Check for invalid uses of an abstract type in a method declaration.
5793 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5794                                     CXXMethodDecl *MD) {
5795   // No need to do the check on definitions, which require that
5796   // the return/param types be complete.
5797   if (MD->doesThisDeclarationHaveABody())
5798     return;
5799 
5800   // For safety's sake, just ignore it if we don't have type source
5801   // information.  This should never happen for non-implicit methods,
5802   // but...
5803   if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5804     Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5805 }
5806 
5807 /// Check for invalid uses of an abstract type within a class definition.
5808 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5809                                     CXXRecordDecl *RD) {
5810   for (auto *D : RD->decls()) {
5811     if (D->isImplicit()) continue;
5812 
5813     // Methods and method templates.
5814     if (isa<CXXMethodDecl>(D)) {
5815       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5816     } else if (isa<FunctionTemplateDecl>(D)) {
5817       FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5818       CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5819 
5820     // Fields and static variables.
5821     } else if (isa<FieldDecl>(D)) {
5822       FieldDecl *FD = cast<FieldDecl>(D);
5823       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5824         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5825     } else if (isa<VarDecl>(D)) {
5826       VarDecl *VD = cast<VarDecl>(D);
5827       if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5828         Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5829 
5830     // Nested classes and class templates.
5831     } else if (isa<CXXRecordDecl>(D)) {
5832       CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5833     } else if (isa<ClassTemplateDecl>(D)) {
5834       CheckAbstractClassUsage(Info,
5835                              cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5836     }
5837   }
5838 }
5839 
5840 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5841   Attr *ClassAttr = getDLLAttr(Class);
5842   if (!ClassAttr)
5843     return;
5844 
5845   assert(ClassAttr->getKind() == attr::DLLExport);
5846 
5847   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5848 
5849   if (TSK == TSK_ExplicitInstantiationDeclaration)
5850     // Don't go any further if this is just an explicit instantiation
5851     // declaration.
5852     return;
5853 
5854   // Add a context note to explain how we got to any diagnostics produced below.
5855   struct MarkingClassDllexported {
5856     Sema &S;
5857     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5858                             SourceLocation AttrLoc)
5859         : S(S) {
5860       Sema::CodeSynthesisContext Ctx;
5861       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5862       Ctx.PointOfInstantiation = AttrLoc;
5863       Ctx.Entity = Class;
5864       S.pushCodeSynthesisContext(Ctx);
5865     }
5866     ~MarkingClassDllexported() {
5867       S.popCodeSynthesisContext();
5868     }
5869   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5870 
5871   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5872     S.MarkVTableUsed(Class->getLocation(), Class, true);
5873 
5874   for (Decl *Member : Class->decls()) {
5875     // Defined static variables that are members of an exported base
5876     // class must be marked export too.
5877     auto *VD = dyn_cast<VarDecl>(Member);
5878     if (VD && Member->getAttr<DLLExportAttr>() &&
5879         VD->getStorageClass() == SC_Static &&
5880         TSK == TSK_ImplicitInstantiation)
5881       S.MarkVariableReferenced(VD->getLocation(), VD);
5882 
5883     auto *MD = dyn_cast<CXXMethodDecl>(Member);
5884     if (!MD)
5885       continue;
5886 
5887     if (Member->getAttr<DLLExportAttr>()) {
5888       if (MD->isUserProvided()) {
5889         // Instantiate non-default class member functions ...
5890 
5891         // .. except for certain kinds of template specializations.
5892         if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5893           continue;
5894 
5895         S.MarkFunctionReferenced(Class->getLocation(), MD);
5896 
5897         // The function will be passed to the consumer when its definition is
5898         // encountered.
5899       } else if (MD->isExplicitlyDefaulted()) {
5900         // Synthesize and instantiate explicitly defaulted methods.
5901         S.MarkFunctionReferenced(Class->getLocation(), MD);
5902 
5903         if (TSK != TSK_ExplicitInstantiationDefinition) {
5904           // Except for explicit instantiation defs, we will not see the
5905           // definition again later, so pass it to the consumer now.
5906           S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5907         }
5908       } else if (!MD->isTrivial() ||
5909                  MD->isCopyAssignmentOperator() ||
5910                  MD->isMoveAssignmentOperator()) {
5911         // Synthesize and instantiate non-trivial implicit methods, and the copy
5912         // and move assignment operators. The latter are exported even if they
5913         // are trivial, because the address of an operator can be taken and
5914         // should compare equal across libraries.
5915         S.MarkFunctionReferenced(Class->getLocation(), MD);
5916 
5917         // There is no later point when we will see the definition of this
5918         // function, so pass it to the consumer now.
5919         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5920       }
5921     }
5922   }
5923 }
5924 
5925 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5926                                                         CXXRecordDecl *Class) {
5927   // Only the MS ABI has default constructor closures, so we don't need to do
5928   // this semantic checking anywhere else.
5929   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5930     return;
5931 
5932   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5933   for (Decl *Member : Class->decls()) {
5934     // Look for exported default constructors.
5935     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5936     if (!CD || !CD->isDefaultConstructor())
5937       continue;
5938     auto *Attr = CD->getAttr<DLLExportAttr>();
5939     if (!Attr)
5940       continue;
5941 
5942     // If the class is non-dependent, mark the default arguments as ODR-used so
5943     // that we can properly codegen the constructor closure.
5944     if (!Class->isDependentContext()) {
5945       for (ParmVarDecl *PD : CD->parameters()) {
5946         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5947         S.DiscardCleanupsInEvaluationContext();
5948       }
5949     }
5950 
5951     if (LastExportedDefaultCtor) {
5952       S.Diag(LastExportedDefaultCtor->getLocation(),
5953              diag::err_attribute_dll_ambiguous_default_ctor)
5954           << Class;
5955       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5956           << CD->getDeclName();
5957       return;
5958     }
5959     LastExportedDefaultCtor = CD;
5960   }
5961 }
5962 
5963 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5964                                                        CXXRecordDecl *Class) {
5965   bool ErrorReported = false;
5966   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5967                                                      ClassTemplateDecl *TD) {
5968     if (ErrorReported)
5969       return;
5970     S.Diag(TD->getLocation(),
5971            diag::err_cuda_device_builtin_surftex_cls_template)
5972         << /*surface*/ 0 << TD;
5973     ErrorReported = true;
5974   };
5975 
5976   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5977   if (!TD) {
5978     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5979     if (!SD) {
5980       S.Diag(Class->getLocation(),
5981              diag::err_cuda_device_builtin_surftex_ref_decl)
5982           << /*surface*/ 0 << Class;
5983       S.Diag(Class->getLocation(),
5984              diag::note_cuda_device_builtin_surftex_should_be_template_class)
5985           << Class;
5986       return;
5987     }
5988     TD = SD->getSpecializedTemplate();
5989   }
5990 
5991   TemplateParameterList *Params = TD->getTemplateParameters();
5992   unsigned N = Params->size();
5993 
5994   if (N != 2) {
5995     reportIllegalClassTemplate(S, TD);
5996     S.Diag(TD->getLocation(),
5997            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
5998         << TD << 2;
5999   }
6000   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6001     reportIllegalClassTemplate(S, TD);
6002     S.Diag(TD->getLocation(),
6003            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6004         << TD << /*1st*/ 0 << /*type*/ 0;
6005   }
6006   if (N > 1) {
6007     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6008     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6009       reportIllegalClassTemplate(S, TD);
6010       S.Diag(TD->getLocation(),
6011              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6012           << TD << /*2nd*/ 1 << /*integer*/ 1;
6013     }
6014   }
6015 }
6016 
6017 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6018                                                        CXXRecordDecl *Class) {
6019   bool ErrorReported = false;
6020   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6021                                                      ClassTemplateDecl *TD) {
6022     if (ErrorReported)
6023       return;
6024     S.Diag(TD->getLocation(),
6025            diag::err_cuda_device_builtin_surftex_cls_template)
6026         << /*texture*/ 1 << TD;
6027     ErrorReported = true;
6028   };
6029 
6030   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6031   if (!TD) {
6032     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6033     if (!SD) {
6034       S.Diag(Class->getLocation(),
6035              diag::err_cuda_device_builtin_surftex_ref_decl)
6036           << /*texture*/ 1 << Class;
6037       S.Diag(Class->getLocation(),
6038              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6039           << Class;
6040       return;
6041     }
6042     TD = SD->getSpecializedTemplate();
6043   }
6044 
6045   TemplateParameterList *Params = TD->getTemplateParameters();
6046   unsigned N = Params->size();
6047 
6048   if (N != 3) {
6049     reportIllegalClassTemplate(S, TD);
6050     S.Diag(TD->getLocation(),
6051            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6052         << TD << 3;
6053   }
6054   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6055     reportIllegalClassTemplate(S, TD);
6056     S.Diag(TD->getLocation(),
6057            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6058         << TD << /*1st*/ 0 << /*type*/ 0;
6059   }
6060   if (N > 1) {
6061     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6062     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6063       reportIllegalClassTemplate(S, TD);
6064       S.Diag(TD->getLocation(),
6065              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6066           << TD << /*2nd*/ 1 << /*integer*/ 1;
6067     }
6068   }
6069   if (N > 2) {
6070     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6071     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6072       reportIllegalClassTemplate(S, TD);
6073       S.Diag(TD->getLocation(),
6074              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6075           << TD << /*3rd*/ 2 << /*integer*/ 1;
6076     }
6077   }
6078 }
6079 
6080 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6081   // Mark any compiler-generated routines with the implicit code_seg attribute.
6082   for (auto *Method : Class->methods()) {
6083     if (Method->isUserProvided())
6084       continue;
6085     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6086       Method->addAttr(A);
6087   }
6088 }
6089 
6090 /// Check class-level dllimport/dllexport attribute.
6091 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6092   Attr *ClassAttr = getDLLAttr(Class);
6093 
6094   // MSVC inherits DLL attributes to partial class template specializations.
6095   if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6096        Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) && !ClassAttr) {
6097     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6098       if (Attr *TemplateAttr =
6099               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6100         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6101         A->setInherited(true);
6102         ClassAttr = A;
6103       }
6104     }
6105   }
6106 
6107   if (!ClassAttr)
6108     return;
6109 
6110   if (!Class->isExternallyVisible()) {
6111     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6112         << Class << ClassAttr;
6113     return;
6114   }
6115 
6116   if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6117        Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) &&
6118       !ClassAttr->isInherited()) {
6119     // Diagnose dll attributes on members of class with dll attribute.
6120     for (Decl *Member : Class->decls()) {
6121       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6122         continue;
6123       InheritableAttr *MemberAttr = getDLLAttr(Member);
6124       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6125         continue;
6126 
6127       Diag(MemberAttr->getLocation(),
6128              diag::err_attribute_dll_member_of_dll_class)
6129           << MemberAttr << ClassAttr;
6130       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6131       Member->setInvalidDecl();
6132     }
6133   }
6134 
6135   if (Class->getDescribedClassTemplate())
6136     // Don't inherit dll attribute until the template is instantiated.
6137     return;
6138 
6139   // The class is either imported or exported.
6140   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6141 
6142   // Check if this was a dllimport attribute propagated from a derived class to
6143   // a base class template specialization. We don't apply these attributes to
6144   // static data members.
6145   const bool PropagatedImport =
6146       !ClassExported &&
6147       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6148 
6149   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6150 
6151   // Ignore explicit dllexport on explicit class template instantiation
6152   // declarations, except in MinGW mode.
6153   if (ClassExported && !ClassAttr->isInherited() &&
6154       TSK == TSK_ExplicitInstantiationDeclaration &&
6155       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6156     Class->dropAttr<DLLExportAttr>();
6157     return;
6158   }
6159 
6160   // Force declaration of implicit members so they can inherit the attribute.
6161   ForceDeclarationOfImplicitMembers(Class);
6162 
6163   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6164   // seem to be true in practice?
6165 
6166   for (Decl *Member : Class->decls()) {
6167     VarDecl *VD = dyn_cast<VarDecl>(Member);
6168     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6169 
6170     // Only methods and static fields inherit the attributes.
6171     if (!VD && !MD)
6172       continue;
6173 
6174     if (MD) {
6175       // Don't process deleted methods.
6176       if (MD->isDeleted())
6177         continue;
6178 
6179       if (MD->isInlined()) {
6180         // MinGW does not import or export inline methods. But do it for
6181         // template instantiations.
6182         if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6183             !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
6184             TSK != TSK_ExplicitInstantiationDeclaration &&
6185             TSK != TSK_ExplicitInstantiationDefinition)
6186           continue;
6187 
6188         // MSVC versions before 2015 don't export the move assignment operators
6189         // and move constructor, so don't attempt to import/export them if
6190         // we have a definition.
6191         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6192         if ((MD->isMoveAssignmentOperator() ||
6193              (Ctor && Ctor->isMoveConstructor())) &&
6194             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6195           continue;
6196 
6197         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6198         // operator is exported anyway.
6199         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6200             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6201           continue;
6202       }
6203     }
6204 
6205     // Don't apply dllimport attributes to static data members of class template
6206     // instantiations when the attribute is propagated from a derived class.
6207     if (VD && PropagatedImport)
6208       continue;
6209 
6210     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6211       continue;
6212 
6213     if (!getDLLAttr(Member)) {
6214       InheritableAttr *NewAttr = nullptr;
6215 
6216       // Do not export/import inline function when -fno-dllexport-inlines is
6217       // passed. But add attribute for later local static var check.
6218       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6219           TSK != TSK_ExplicitInstantiationDeclaration &&
6220           TSK != TSK_ExplicitInstantiationDefinition) {
6221         if (ClassExported) {
6222           NewAttr = ::new (getASTContext())
6223               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6224         } else {
6225           NewAttr = ::new (getASTContext())
6226               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6227         }
6228       } else {
6229         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6230       }
6231 
6232       NewAttr->setInherited(true);
6233       Member->addAttr(NewAttr);
6234 
6235       if (MD) {
6236         // Propagate DLLAttr to friend re-declarations of MD that have already
6237         // been constructed.
6238         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6239              FD = FD->getPreviousDecl()) {
6240           if (FD->getFriendObjectKind() == Decl::FOK_None)
6241             continue;
6242           assert(!getDLLAttr(FD) &&
6243                  "friend re-decl should not already have a DLLAttr");
6244           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6245           NewAttr->setInherited(true);
6246           FD->addAttr(NewAttr);
6247         }
6248       }
6249     }
6250   }
6251 
6252   if (ClassExported)
6253     DelayedDllExportClasses.push_back(Class);
6254 }
6255 
6256 /// Perform propagation of DLL attributes from a derived class to a
6257 /// templated base class for MS compatibility.
6258 void Sema::propagateDLLAttrToBaseClassTemplate(
6259     CXXRecordDecl *Class, Attr *ClassAttr,
6260     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6261   if (getDLLAttr(
6262           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6263     // If the base class template has a DLL attribute, don't try to change it.
6264     return;
6265   }
6266 
6267   auto TSK = BaseTemplateSpec->getSpecializationKind();
6268   if (!getDLLAttr(BaseTemplateSpec) &&
6269       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6270        TSK == TSK_ImplicitInstantiation)) {
6271     // The template hasn't been instantiated yet (or it has, but only as an
6272     // explicit instantiation declaration or implicit instantiation, which means
6273     // we haven't codegenned any members yet), so propagate the attribute.
6274     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6275     NewAttr->setInherited(true);
6276     BaseTemplateSpec->addAttr(NewAttr);
6277 
6278     // If this was an import, mark that we propagated it from a derived class to
6279     // a base class template specialization.
6280     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6281       ImportAttr->setPropagatedToBaseTemplate();
6282 
6283     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6284     // needs to be run again to work see the new attribute. Otherwise this will
6285     // get run whenever the template is instantiated.
6286     if (TSK != TSK_Undeclared)
6287       checkClassLevelDLLAttribute(BaseTemplateSpec);
6288 
6289     return;
6290   }
6291 
6292   if (getDLLAttr(BaseTemplateSpec)) {
6293     // The template has already been specialized or instantiated with an
6294     // attribute, explicitly or through propagation. We should not try to change
6295     // it.
6296     return;
6297   }
6298 
6299   // The template was previously instantiated or explicitly specialized without
6300   // a dll attribute, It's too late for us to add an attribute, so warn that
6301   // this is unsupported.
6302   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6303       << BaseTemplateSpec->isExplicitSpecialization();
6304   Diag(ClassAttr->getLocation(), diag::note_attribute);
6305   if (BaseTemplateSpec->isExplicitSpecialization()) {
6306     Diag(BaseTemplateSpec->getLocation(),
6307            diag::note_template_class_explicit_specialization_was_here)
6308         << BaseTemplateSpec;
6309   } else {
6310     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6311            diag::note_template_class_instantiation_was_here)
6312         << BaseTemplateSpec;
6313   }
6314 }
6315 
6316 /// Determine the kind of defaulting that would be done for a given function.
6317 ///
6318 /// If the function is both a default constructor and a copy / move constructor
6319 /// (due to having a default argument for the first parameter), this picks
6320 /// CXXDefaultConstructor.
6321 ///
6322 /// FIXME: Check that case is properly handled by all callers.
6323 Sema::DefaultedFunctionKind
6324 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6325   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6326     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6327       if (Ctor->isDefaultConstructor())
6328         return Sema::CXXDefaultConstructor;
6329 
6330       if (Ctor->isCopyConstructor())
6331         return Sema::CXXCopyConstructor;
6332 
6333       if (Ctor->isMoveConstructor())
6334         return Sema::CXXMoveConstructor;
6335     }
6336 
6337     if (MD->isCopyAssignmentOperator())
6338       return Sema::CXXCopyAssignment;
6339 
6340     if (MD->isMoveAssignmentOperator())
6341       return Sema::CXXMoveAssignment;
6342 
6343     if (isa<CXXDestructorDecl>(FD))
6344       return Sema::CXXDestructor;
6345   }
6346 
6347   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6348   case OO_EqualEqual:
6349     return DefaultedComparisonKind::Equal;
6350 
6351   case OO_ExclaimEqual:
6352     return DefaultedComparisonKind::NotEqual;
6353 
6354   case OO_Spaceship:
6355     // No point allowing this if <=> doesn't exist in the current language mode.
6356     if (!getLangOpts().CPlusPlus20)
6357       break;
6358     return DefaultedComparisonKind::ThreeWay;
6359 
6360   case OO_Less:
6361   case OO_LessEqual:
6362   case OO_Greater:
6363   case OO_GreaterEqual:
6364     // No point allowing this if <=> doesn't exist in the current language mode.
6365     if (!getLangOpts().CPlusPlus20)
6366       break;
6367     return DefaultedComparisonKind::Relational;
6368 
6369   default:
6370     break;
6371   }
6372 
6373   // Not defaultable.
6374   return DefaultedFunctionKind();
6375 }
6376 
6377 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6378                                     SourceLocation DefaultLoc) {
6379   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6380   if (DFK.isComparison())
6381     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6382 
6383   switch (DFK.asSpecialMember()) {
6384   case Sema::CXXDefaultConstructor:
6385     S.DefineImplicitDefaultConstructor(DefaultLoc,
6386                                        cast<CXXConstructorDecl>(FD));
6387     break;
6388   case Sema::CXXCopyConstructor:
6389     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6390     break;
6391   case Sema::CXXCopyAssignment:
6392     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6393     break;
6394   case Sema::CXXDestructor:
6395     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6396     break;
6397   case Sema::CXXMoveConstructor:
6398     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6399     break;
6400   case Sema::CXXMoveAssignment:
6401     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6402     break;
6403   case Sema::CXXInvalid:
6404     llvm_unreachable("Invalid special member.");
6405   }
6406 }
6407 
6408 /// Determine whether a type is permitted to be passed or returned in
6409 /// registers, per C++ [class.temporary]p3.
6410 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6411                                TargetInfo::CallingConvKind CCK) {
6412   if (D->isDependentType() || D->isInvalidDecl())
6413     return false;
6414 
6415   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6416   // The PS4 platform ABI follows the behavior of Clang 3.2.
6417   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6418     return !D->hasNonTrivialDestructorForCall() &&
6419            !D->hasNonTrivialCopyConstructorForCall();
6420 
6421   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6422     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6423     bool DtorIsTrivialForCall = false;
6424 
6425     // If a class has at least one non-deleted, trivial copy constructor, it
6426     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6427     //
6428     // Note: This permits classes with non-trivial copy or move ctors to be
6429     // passed in registers, so long as they *also* have a trivial copy ctor,
6430     // which is non-conforming.
6431     if (D->needsImplicitCopyConstructor()) {
6432       if (!D->defaultedCopyConstructorIsDeleted()) {
6433         if (D->hasTrivialCopyConstructor())
6434           CopyCtorIsTrivial = true;
6435         if (D->hasTrivialCopyConstructorForCall())
6436           CopyCtorIsTrivialForCall = true;
6437       }
6438     } else {
6439       for (const CXXConstructorDecl *CD : D->ctors()) {
6440         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6441           if (CD->isTrivial())
6442             CopyCtorIsTrivial = true;
6443           if (CD->isTrivialForCall())
6444             CopyCtorIsTrivialForCall = true;
6445         }
6446       }
6447     }
6448 
6449     if (D->needsImplicitDestructor()) {
6450       if (!D->defaultedDestructorIsDeleted() &&
6451           D->hasTrivialDestructorForCall())
6452         DtorIsTrivialForCall = true;
6453     } else if (const auto *DD = D->getDestructor()) {
6454       if (!DD->isDeleted() && DD->isTrivialForCall())
6455         DtorIsTrivialForCall = true;
6456     }
6457 
6458     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6459     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6460       return true;
6461 
6462     // If a class has a destructor, we'd really like to pass it indirectly
6463     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6464     // impossible for small types, which it will pass in a single register or
6465     // stack slot. Most objects with dtors are large-ish, so handle that early.
6466     // We can't call out all large objects as being indirect because there are
6467     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6468     // how we pass large POD types.
6469 
6470     // Note: This permits small classes with nontrivial destructors to be
6471     // passed in registers, which is non-conforming.
6472     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6473     uint64_t TypeSize = isAArch64 ? 128 : 64;
6474 
6475     if (CopyCtorIsTrivial &&
6476         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6477       return true;
6478     return false;
6479   }
6480 
6481   // Per C++ [class.temporary]p3, the relevant condition is:
6482   //   each copy constructor, move constructor, and destructor of X is
6483   //   either trivial or deleted, and X has at least one non-deleted copy
6484   //   or move constructor
6485   bool HasNonDeletedCopyOrMove = false;
6486 
6487   if (D->needsImplicitCopyConstructor() &&
6488       !D->defaultedCopyConstructorIsDeleted()) {
6489     if (!D->hasTrivialCopyConstructorForCall())
6490       return false;
6491     HasNonDeletedCopyOrMove = true;
6492   }
6493 
6494   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6495       !D->defaultedMoveConstructorIsDeleted()) {
6496     if (!D->hasTrivialMoveConstructorForCall())
6497       return false;
6498     HasNonDeletedCopyOrMove = true;
6499   }
6500 
6501   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6502       !D->hasTrivialDestructorForCall())
6503     return false;
6504 
6505   for (const CXXMethodDecl *MD : D->methods()) {
6506     if (MD->isDeleted())
6507       continue;
6508 
6509     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6510     if (CD && CD->isCopyOrMoveConstructor())
6511       HasNonDeletedCopyOrMove = true;
6512     else if (!isa<CXXDestructorDecl>(MD))
6513       continue;
6514 
6515     if (!MD->isTrivialForCall())
6516       return false;
6517   }
6518 
6519   return HasNonDeletedCopyOrMove;
6520 }
6521 
6522 /// Report an error regarding overriding, along with any relevant
6523 /// overridden methods.
6524 ///
6525 /// \param DiagID the primary error to report.
6526 /// \param MD the overriding method.
6527 static bool
6528 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6529                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6530   bool IssuedDiagnostic = false;
6531   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6532     if (Report(O)) {
6533       if (!IssuedDiagnostic) {
6534         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6535         IssuedDiagnostic = true;
6536       }
6537       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6538     }
6539   }
6540   return IssuedDiagnostic;
6541 }
6542 
6543 /// Perform semantic checks on a class definition that has been
6544 /// completing, introducing implicitly-declared members, checking for
6545 /// abstract types, etc.
6546 ///
6547 /// \param S The scope in which the class was parsed. Null if we didn't just
6548 ///        parse a class definition.
6549 /// \param Record The completed class.
6550 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6551   if (!Record)
6552     return;
6553 
6554   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6555     AbstractUsageInfo Info(*this, Record);
6556     CheckAbstractClassUsage(Info, Record);
6557   }
6558 
6559   // If this is not an aggregate type and has no user-declared constructor,
6560   // complain about any non-static data members of reference or const scalar
6561   // type, since they will never get initializers.
6562   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6563       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6564       !Record->isLambda()) {
6565     bool Complained = false;
6566     for (const auto *F : Record->fields()) {
6567       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6568         continue;
6569 
6570       if (F->getType()->isReferenceType() ||
6571           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6572         if (!Complained) {
6573           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6574             << Record->getTagKind() << Record;
6575           Complained = true;
6576         }
6577 
6578         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6579           << F->getType()->isReferenceType()
6580           << F->getDeclName();
6581       }
6582     }
6583   }
6584 
6585   if (Record->getIdentifier()) {
6586     // C++ [class.mem]p13:
6587     //   If T is the name of a class, then each of the following shall have a
6588     //   name different from T:
6589     //     - every member of every anonymous union that is a member of class T.
6590     //
6591     // C++ [class.mem]p14:
6592     //   In addition, if class T has a user-declared constructor (12.1), every
6593     //   non-static data member of class T shall have a name different from T.
6594     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6595     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6596          ++I) {
6597       NamedDecl *D = (*I)->getUnderlyingDecl();
6598       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6599            Record->hasUserDeclaredConstructor()) ||
6600           isa<IndirectFieldDecl>(D)) {
6601         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6602           << D->getDeclName();
6603         break;
6604       }
6605     }
6606   }
6607 
6608   // Warn if the class has virtual methods but non-virtual public destructor.
6609   if (Record->isPolymorphic() && !Record->isDependentType()) {
6610     CXXDestructorDecl *dtor = Record->getDestructor();
6611     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6612         !Record->hasAttr<FinalAttr>())
6613       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6614            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6615   }
6616 
6617   if (Record->isAbstract()) {
6618     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6619       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6620         << FA->isSpelledAsSealed();
6621       DiagnoseAbstractType(Record);
6622     }
6623   }
6624 
6625   // Warn if the class has a final destructor but is not itself marked final.
6626   if (!Record->hasAttr<FinalAttr>()) {
6627     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6628       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6629         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6630             << FA->isSpelledAsSealed()
6631             << FixItHint::CreateInsertion(
6632                    getLocForEndOfToken(Record->getLocation()),
6633                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6634         Diag(Record->getLocation(),
6635              diag::note_final_dtor_non_final_class_silence)
6636             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6637       }
6638     }
6639   }
6640 
6641   // See if trivial_abi has to be dropped.
6642   if (Record->hasAttr<TrivialABIAttr>())
6643     checkIllFormedTrivialABIStruct(*Record);
6644 
6645   // Set HasTrivialSpecialMemberForCall if the record has attribute
6646   // "trivial_abi".
6647   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6648 
6649   if (HasTrivialABI)
6650     Record->setHasTrivialSpecialMemberForCall();
6651 
6652   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6653   // We check these last because they can depend on the properties of the
6654   // primary comparison functions (==, <=>).
6655   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6656 
6657   // Perform checks that can't be done until we know all the properties of a
6658   // member function (whether it's defaulted, deleted, virtual, overriding,
6659   // ...).
6660   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6661     // A static function cannot override anything.
6662     if (MD->getStorageClass() == SC_Static) {
6663       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6664                           [](const CXXMethodDecl *) { return true; }))
6665         return;
6666     }
6667 
6668     // A deleted function cannot override a non-deleted function and vice
6669     // versa.
6670     if (ReportOverrides(*this,
6671                         MD->isDeleted() ? diag::err_deleted_override
6672                                         : diag::err_non_deleted_override,
6673                         MD, [&](const CXXMethodDecl *V) {
6674                           return MD->isDeleted() != V->isDeleted();
6675                         })) {
6676       if (MD->isDefaulted() && MD->isDeleted())
6677         // Explain why this defaulted function was deleted.
6678         DiagnoseDeletedDefaultedFunction(MD);
6679       return;
6680     }
6681 
6682     // A consteval function cannot override a non-consteval function and vice
6683     // versa.
6684     if (ReportOverrides(*this,
6685                         MD->isConsteval() ? diag::err_consteval_override
6686                                           : diag::err_non_consteval_override,
6687                         MD, [&](const CXXMethodDecl *V) {
6688                           return MD->isConsteval() != V->isConsteval();
6689                         })) {
6690       if (MD->isDefaulted() && MD->isDeleted())
6691         // Explain why this defaulted function was deleted.
6692         DiagnoseDeletedDefaultedFunction(MD);
6693       return;
6694     }
6695   };
6696 
6697   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6698     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6699       return false;
6700 
6701     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6702     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6703         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6704       DefaultedSecondaryComparisons.push_back(FD);
6705       return true;
6706     }
6707 
6708     CheckExplicitlyDefaultedFunction(S, FD);
6709     return false;
6710   };
6711 
6712   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6713     // Check whether the explicitly-defaulted members are valid.
6714     bool Incomplete = CheckForDefaultedFunction(M);
6715 
6716     // Skip the rest of the checks for a member of a dependent class.
6717     if (Record->isDependentType())
6718       return;
6719 
6720     // For an explicitly defaulted or deleted special member, we defer
6721     // determining triviality until the class is complete. That time is now!
6722     CXXSpecialMember CSM = getSpecialMember(M);
6723     if (!M->isImplicit() && !M->isUserProvided()) {
6724       if (CSM != CXXInvalid) {
6725         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6726         // Inform the class that we've finished declaring this member.
6727         Record->finishedDefaultedOrDeletedMember(M);
6728         M->setTrivialForCall(
6729             HasTrivialABI ||
6730             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6731         Record->setTrivialForCallFlags(M);
6732       }
6733     }
6734 
6735     // Set triviality for the purpose of calls if this is a user-provided
6736     // copy/move constructor or destructor.
6737     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6738          CSM == CXXDestructor) && M->isUserProvided()) {
6739       M->setTrivialForCall(HasTrivialABI);
6740       Record->setTrivialForCallFlags(M);
6741     }
6742 
6743     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6744         M->hasAttr<DLLExportAttr>()) {
6745       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6746           M->isTrivial() &&
6747           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6748            CSM == CXXDestructor))
6749         M->dropAttr<DLLExportAttr>();
6750 
6751       if (M->hasAttr<DLLExportAttr>()) {
6752         // Define after any fields with in-class initializers have been parsed.
6753         DelayedDllExportMemberFunctions.push_back(M);
6754       }
6755     }
6756 
6757     // Define defaulted constexpr virtual functions that override a base class
6758     // function right away.
6759     // FIXME: We can defer doing this until the vtable is marked as used.
6760     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6761       DefineDefaultedFunction(*this, M, M->getLocation());
6762 
6763     if (!Incomplete)
6764       CheckCompletedMemberFunction(M);
6765   };
6766 
6767   // Check the destructor before any other member function. We need to
6768   // determine whether it's trivial in order to determine whether the claas
6769   // type is a literal type, which is a prerequisite for determining whether
6770   // other special member functions are valid and whether they're implicitly
6771   // 'constexpr'.
6772   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6773     CompleteMemberFunction(Dtor);
6774 
6775   bool HasMethodWithOverrideControl = false,
6776        HasOverridingMethodWithoutOverrideControl = false;
6777   for (auto *D : Record->decls()) {
6778     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6779       // FIXME: We could do this check for dependent types with non-dependent
6780       // bases.
6781       if (!Record->isDependentType()) {
6782         // See if a method overloads virtual methods in a base
6783         // class without overriding any.
6784         if (!M->isStatic())
6785           DiagnoseHiddenVirtualMethods(M);
6786         if (M->hasAttr<OverrideAttr>())
6787           HasMethodWithOverrideControl = true;
6788         else if (M->size_overridden_methods() > 0)
6789           HasOverridingMethodWithoutOverrideControl = true;
6790       }
6791 
6792       if (!isa<CXXDestructorDecl>(M))
6793         CompleteMemberFunction(M);
6794     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6795       CheckForDefaultedFunction(
6796           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6797     }
6798   }
6799 
6800   if (HasOverridingMethodWithoutOverrideControl) {
6801     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6802     for (auto *M : Record->methods())
6803       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6804   }
6805 
6806   // Check the defaulted secondary comparisons after any other member functions.
6807   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6808     CheckExplicitlyDefaultedFunction(S, FD);
6809 
6810     // If this is a member function, we deferred checking it until now.
6811     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6812       CheckCompletedMemberFunction(MD);
6813   }
6814 
6815   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6816   // whether this class uses any C++ features that are implemented
6817   // completely differently in MSVC, and if so, emit a diagnostic.
6818   // That diagnostic defaults to an error, but we allow projects to
6819   // map it down to a warning (or ignore it).  It's a fairly common
6820   // practice among users of the ms_struct pragma to mass-annotate
6821   // headers, sweeping up a bunch of types that the project doesn't
6822   // really rely on MSVC-compatible layout for.  We must therefore
6823   // support "ms_struct except for C++ stuff" as a secondary ABI.
6824   // Don't emit this diagnostic if the feature was enabled as a
6825   // language option (as opposed to via a pragma or attribute), as
6826   // the option -mms-bitfields otherwise essentially makes it impossible
6827   // to build C++ code, unless this diagnostic is turned off.
6828   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6829       (Record->isPolymorphic() || Record->getNumBases())) {
6830     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6831   }
6832 
6833   checkClassLevelDLLAttribute(Record);
6834   checkClassLevelCodeSegAttribute(Record);
6835 
6836   bool ClangABICompat4 =
6837       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6838   TargetInfo::CallingConvKind CCK =
6839       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6840   bool CanPass = canPassInRegisters(*this, Record, CCK);
6841 
6842   // Do not change ArgPassingRestrictions if it has already been set to
6843   // APK_CanNeverPassInRegs.
6844   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6845     Record->setArgPassingRestrictions(CanPass
6846                                           ? RecordDecl::APK_CanPassInRegs
6847                                           : RecordDecl::APK_CannotPassInRegs);
6848 
6849   // If canPassInRegisters returns true despite the record having a non-trivial
6850   // destructor, the record is destructed in the callee. This happens only when
6851   // the record or one of its subobjects has a field annotated with trivial_abi
6852   // or a field qualified with ObjC __strong/__weak.
6853   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6854     Record->setParamDestroyedInCallee(true);
6855   else if (Record->hasNonTrivialDestructor())
6856     Record->setParamDestroyedInCallee(CanPass);
6857 
6858   if (getLangOpts().ForceEmitVTables) {
6859     // If we want to emit all the vtables, we need to mark it as used.  This
6860     // is especially required for cases like vtable assumption loads.
6861     MarkVTableUsed(Record->getInnerLocStart(), Record);
6862   }
6863 
6864   if (getLangOpts().CUDA) {
6865     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6866       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6867     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6868       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6869   }
6870 }
6871 
6872 /// Look up the special member function that would be called by a special
6873 /// member function for a subobject of class type.
6874 ///
6875 /// \param Class The class type of the subobject.
6876 /// \param CSM The kind of special member function.
6877 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6878 /// \param ConstRHS True if this is a copy operation with a const object
6879 ///        on its RHS, that is, if the argument to the outer special member
6880 ///        function is 'const' and this is not a field marked 'mutable'.
6881 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6882     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6883     unsigned FieldQuals, bool ConstRHS) {
6884   unsigned LHSQuals = 0;
6885   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6886     LHSQuals = FieldQuals;
6887 
6888   unsigned RHSQuals = FieldQuals;
6889   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6890     RHSQuals = 0;
6891   else if (ConstRHS)
6892     RHSQuals |= Qualifiers::Const;
6893 
6894   return S.LookupSpecialMember(Class, CSM,
6895                                RHSQuals & Qualifiers::Const,
6896                                RHSQuals & Qualifiers::Volatile,
6897                                false,
6898                                LHSQuals & Qualifiers::Const,
6899                                LHSQuals & Qualifiers::Volatile);
6900 }
6901 
6902 class Sema::InheritedConstructorInfo {
6903   Sema &S;
6904   SourceLocation UseLoc;
6905 
6906   /// A mapping from the base classes through which the constructor was
6907   /// inherited to the using shadow declaration in that base class (or a null
6908   /// pointer if the constructor was declared in that base class).
6909   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6910       InheritedFromBases;
6911 
6912 public:
6913   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6914                            ConstructorUsingShadowDecl *Shadow)
6915       : S(S), UseLoc(UseLoc) {
6916     bool DiagnosedMultipleConstructedBases = false;
6917     CXXRecordDecl *ConstructedBase = nullptr;
6918     UsingDecl *ConstructedBaseUsing = nullptr;
6919 
6920     // Find the set of such base class subobjects and check that there's a
6921     // unique constructed subobject.
6922     for (auto *D : Shadow->redecls()) {
6923       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6924       auto *DNominatedBase = DShadow->getNominatedBaseClass();
6925       auto *DConstructedBase = DShadow->getConstructedBaseClass();
6926 
6927       InheritedFromBases.insert(
6928           std::make_pair(DNominatedBase->getCanonicalDecl(),
6929                          DShadow->getNominatedBaseClassShadowDecl()));
6930       if (DShadow->constructsVirtualBase())
6931         InheritedFromBases.insert(
6932             std::make_pair(DConstructedBase->getCanonicalDecl(),
6933                            DShadow->getConstructedBaseClassShadowDecl()));
6934       else
6935         assert(DNominatedBase == DConstructedBase);
6936 
6937       // [class.inhctor.init]p2:
6938       //   If the constructor was inherited from multiple base class subobjects
6939       //   of type B, the program is ill-formed.
6940       if (!ConstructedBase) {
6941         ConstructedBase = DConstructedBase;
6942         ConstructedBaseUsing = D->getUsingDecl();
6943       } else if (ConstructedBase != DConstructedBase &&
6944                  !Shadow->isInvalidDecl()) {
6945         if (!DiagnosedMultipleConstructedBases) {
6946           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6947               << Shadow->getTargetDecl();
6948           S.Diag(ConstructedBaseUsing->getLocation(),
6949                diag::note_ambiguous_inherited_constructor_using)
6950               << ConstructedBase;
6951           DiagnosedMultipleConstructedBases = true;
6952         }
6953         S.Diag(D->getUsingDecl()->getLocation(),
6954                diag::note_ambiguous_inherited_constructor_using)
6955             << DConstructedBase;
6956       }
6957     }
6958 
6959     if (DiagnosedMultipleConstructedBases)
6960       Shadow->setInvalidDecl();
6961   }
6962 
6963   /// Find the constructor to use for inherited construction of a base class,
6964   /// and whether that base class constructor inherits the constructor from a
6965   /// virtual base class (in which case it won't actually invoke it).
6966   std::pair<CXXConstructorDecl *, bool>
6967   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6968     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6969     if (It == InheritedFromBases.end())
6970       return std::make_pair(nullptr, false);
6971 
6972     // This is an intermediary class.
6973     if (It->second)
6974       return std::make_pair(
6975           S.findInheritingConstructor(UseLoc, Ctor, It->second),
6976           It->second->constructsVirtualBase());
6977 
6978     // This is the base class from which the constructor was inherited.
6979     return std::make_pair(Ctor, false);
6980   }
6981 };
6982 
6983 /// Is the special member function which would be selected to perform the
6984 /// specified operation on the specified class type a constexpr constructor?
6985 static bool
6986 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6987                          Sema::CXXSpecialMember CSM, unsigned Quals,
6988                          bool ConstRHS,
6989                          CXXConstructorDecl *InheritedCtor = nullptr,
6990                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
6991   // If we're inheriting a constructor, see if we need to call it for this base
6992   // class.
6993   if (InheritedCtor) {
6994     assert(CSM == Sema::CXXDefaultConstructor);
6995     auto BaseCtor =
6996         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6997     if (BaseCtor)
6998       return BaseCtor->isConstexpr();
6999   }
7000 
7001   if (CSM == Sema::CXXDefaultConstructor)
7002     return ClassDecl->hasConstexprDefaultConstructor();
7003   if (CSM == Sema::CXXDestructor)
7004     return ClassDecl->hasConstexprDestructor();
7005 
7006   Sema::SpecialMemberOverloadResult SMOR =
7007       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7008   if (!SMOR.getMethod())
7009     // A constructor we wouldn't select can't be "involved in initializing"
7010     // anything.
7011     return true;
7012   return SMOR.getMethod()->isConstexpr();
7013 }
7014 
7015 /// Determine whether the specified special member function would be constexpr
7016 /// if it were implicitly defined.
7017 static bool defaultedSpecialMemberIsConstexpr(
7018     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7019     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7020     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7021   if (!S.getLangOpts().CPlusPlus11)
7022     return false;
7023 
7024   // C++11 [dcl.constexpr]p4:
7025   // In the definition of a constexpr constructor [...]
7026   bool Ctor = true;
7027   switch (CSM) {
7028   case Sema::CXXDefaultConstructor:
7029     if (Inherited)
7030       break;
7031     // Since default constructor lookup is essentially trivial (and cannot
7032     // involve, for instance, template instantiation), we compute whether a
7033     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7034     //
7035     // This is important for performance; we need to know whether the default
7036     // constructor is constexpr to determine whether the type is a literal type.
7037     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7038 
7039   case Sema::CXXCopyConstructor:
7040   case Sema::CXXMoveConstructor:
7041     // For copy or move constructors, we need to perform overload resolution.
7042     break;
7043 
7044   case Sema::CXXCopyAssignment:
7045   case Sema::CXXMoveAssignment:
7046     if (!S.getLangOpts().CPlusPlus14)
7047       return false;
7048     // In C++1y, we need to perform overload resolution.
7049     Ctor = false;
7050     break;
7051 
7052   case Sema::CXXDestructor:
7053     return ClassDecl->defaultedDestructorIsConstexpr();
7054 
7055   case Sema::CXXInvalid:
7056     return false;
7057   }
7058 
7059   //   -- if the class is a non-empty union, or for each non-empty anonymous
7060   //      union member of a non-union class, exactly one non-static data member
7061   //      shall be initialized; [DR1359]
7062   //
7063   // If we squint, this is guaranteed, since exactly one non-static data member
7064   // will be initialized (if the constructor isn't deleted), we just don't know
7065   // which one.
7066   if (Ctor && ClassDecl->isUnion())
7067     return CSM == Sema::CXXDefaultConstructor
7068                ? ClassDecl->hasInClassInitializer() ||
7069                      !ClassDecl->hasVariantMembers()
7070                : true;
7071 
7072   //   -- the class shall not have any virtual base classes;
7073   if (Ctor && ClassDecl->getNumVBases())
7074     return false;
7075 
7076   // C++1y [class.copy]p26:
7077   //   -- [the class] is a literal type, and
7078   if (!Ctor && !ClassDecl->isLiteral())
7079     return false;
7080 
7081   //   -- every constructor involved in initializing [...] base class
7082   //      sub-objects shall be a constexpr constructor;
7083   //   -- the assignment operator selected to copy/move each direct base
7084   //      class is a constexpr function, and
7085   for (const auto &B : ClassDecl->bases()) {
7086     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7087     if (!BaseType) continue;
7088 
7089     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7090     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7091                                   InheritedCtor, Inherited))
7092       return false;
7093   }
7094 
7095   //   -- every constructor involved in initializing non-static data members
7096   //      [...] shall be a constexpr constructor;
7097   //   -- every non-static data member and base class sub-object shall be
7098   //      initialized
7099   //   -- for each non-static data member of X that is of class type (or array
7100   //      thereof), the assignment operator selected to copy/move that member is
7101   //      a constexpr function
7102   for (const auto *F : ClassDecl->fields()) {
7103     if (F->isInvalidDecl())
7104       continue;
7105     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7106       continue;
7107     QualType BaseType = S.Context.getBaseElementType(F->getType());
7108     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7109       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7110       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7111                                     BaseType.getCVRQualifiers(),
7112                                     ConstArg && !F->isMutable()))
7113         return false;
7114     } else if (CSM == Sema::CXXDefaultConstructor) {
7115       return false;
7116     }
7117   }
7118 
7119   // All OK, it's constexpr!
7120   return true;
7121 }
7122 
7123 namespace {
7124 /// RAII object to register a defaulted function as having its exception
7125 /// specification computed.
7126 struct ComputingExceptionSpec {
7127   Sema &S;
7128 
7129   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7130       : S(S) {
7131     Sema::CodeSynthesisContext Ctx;
7132     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7133     Ctx.PointOfInstantiation = Loc;
7134     Ctx.Entity = FD;
7135     S.pushCodeSynthesisContext(Ctx);
7136   }
7137   ~ComputingExceptionSpec() {
7138     S.popCodeSynthesisContext();
7139   }
7140 };
7141 }
7142 
7143 static Sema::ImplicitExceptionSpecification
7144 ComputeDefaultedSpecialMemberExceptionSpec(
7145     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7146     Sema::InheritedConstructorInfo *ICI);
7147 
7148 static Sema::ImplicitExceptionSpecification
7149 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7150                                         FunctionDecl *FD,
7151                                         Sema::DefaultedComparisonKind DCK);
7152 
7153 static Sema::ImplicitExceptionSpecification
7154 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7155   auto DFK = S.getDefaultedFunctionKind(FD);
7156   if (DFK.isSpecialMember())
7157     return ComputeDefaultedSpecialMemberExceptionSpec(
7158         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7159   if (DFK.isComparison())
7160     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7161                                                    DFK.asComparison());
7162 
7163   auto *CD = cast<CXXConstructorDecl>(FD);
7164   assert(CD->getInheritedConstructor() &&
7165          "only defaulted functions and inherited constructors have implicit "
7166          "exception specs");
7167   Sema::InheritedConstructorInfo ICI(
7168       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7169   return ComputeDefaultedSpecialMemberExceptionSpec(
7170       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7171 }
7172 
7173 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7174                                                             CXXMethodDecl *MD) {
7175   FunctionProtoType::ExtProtoInfo EPI;
7176 
7177   // Build an exception specification pointing back at this member.
7178   EPI.ExceptionSpec.Type = EST_Unevaluated;
7179   EPI.ExceptionSpec.SourceDecl = MD;
7180 
7181   // Set the calling convention to the default for C++ instance methods.
7182   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7183       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7184                                             /*IsCXXMethod=*/true));
7185   return EPI;
7186 }
7187 
7188 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7189   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7190   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7191     return;
7192 
7193   // Evaluate the exception specification.
7194   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7195   auto ESI = IES.getExceptionSpec();
7196 
7197   // Update the type of the special member to use it.
7198   UpdateExceptionSpec(FD, ESI);
7199 }
7200 
7201 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7202   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7203 
7204   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7205   if (!DefKind) {
7206     assert(FD->getDeclContext()->isDependentContext());
7207     return;
7208   }
7209 
7210   if (DefKind.isSpecialMember()
7211           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7212                                                   DefKind.asSpecialMember())
7213           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7214     FD->setInvalidDecl();
7215 }
7216 
7217 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7218                                                  CXXSpecialMember CSM) {
7219   CXXRecordDecl *RD = MD->getParent();
7220 
7221   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7222          "not an explicitly-defaulted special member");
7223 
7224   // Defer all checking for special members of a dependent type.
7225   if (RD->isDependentType())
7226     return false;
7227 
7228   // Whether this was the first-declared instance of the constructor.
7229   // This affects whether we implicitly add an exception spec and constexpr.
7230   bool First = MD == MD->getCanonicalDecl();
7231 
7232   bool HadError = false;
7233 
7234   // C++11 [dcl.fct.def.default]p1:
7235   //   A function that is explicitly defaulted shall
7236   //     -- be a special member function [...] (checked elsewhere),
7237   //     -- have the same type (except for ref-qualifiers, and except that a
7238   //        copy operation can take a non-const reference) as an implicit
7239   //        declaration, and
7240   //     -- not have default arguments.
7241   // C++2a changes the second bullet to instead delete the function if it's
7242   // defaulted on its first declaration, unless it's "an assignment operator,
7243   // and its return type differs or its parameter type is not a reference".
7244   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7245   bool ShouldDeleteForTypeMismatch = false;
7246   unsigned ExpectedParams = 1;
7247   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7248     ExpectedParams = 0;
7249   if (MD->getNumParams() != ExpectedParams) {
7250     // This checks for default arguments: a copy or move constructor with a
7251     // default argument is classified as a default constructor, and assignment
7252     // operations and destructors can't have default arguments.
7253     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7254       << CSM << MD->getSourceRange();
7255     HadError = true;
7256   } else if (MD->isVariadic()) {
7257     if (DeleteOnTypeMismatch)
7258       ShouldDeleteForTypeMismatch = true;
7259     else {
7260       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7261         << CSM << MD->getSourceRange();
7262       HadError = true;
7263     }
7264   }
7265 
7266   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7267 
7268   bool CanHaveConstParam = false;
7269   if (CSM == CXXCopyConstructor)
7270     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7271   else if (CSM == CXXCopyAssignment)
7272     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7273 
7274   QualType ReturnType = Context.VoidTy;
7275   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7276     // Check for return type matching.
7277     ReturnType = Type->getReturnType();
7278 
7279     QualType DeclType = Context.getTypeDeclType(RD);
7280     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7281     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7282 
7283     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7284       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7285         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7286       HadError = true;
7287     }
7288 
7289     // A defaulted special member cannot have cv-qualifiers.
7290     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7291       if (DeleteOnTypeMismatch)
7292         ShouldDeleteForTypeMismatch = true;
7293       else {
7294         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7295           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7296         HadError = true;
7297       }
7298     }
7299   }
7300 
7301   // Check for parameter type matching.
7302   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7303   bool HasConstParam = false;
7304   if (ExpectedParams && ArgType->isReferenceType()) {
7305     // Argument must be reference to possibly-const T.
7306     QualType ReferentType = ArgType->getPointeeType();
7307     HasConstParam = ReferentType.isConstQualified();
7308 
7309     if (ReferentType.isVolatileQualified()) {
7310       if (DeleteOnTypeMismatch)
7311         ShouldDeleteForTypeMismatch = true;
7312       else {
7313         Diag(MD->getLocation(),
7314              diag::err_defaulted_special_member_volatile_param) << CSM;
7315         HadError = true;
7316       }
7317     }
7318 
7319     if (HasConstParam && !CanHaveConstParam) {
7320       if (DeleteOnTypeMismatch)
7321         ShouldDeleteForTypeMismatch = true;
7322       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7323         Diag(MD->getLocation(),
7324              diag::err_defaulted_special_member_copy_const_param)
7325           << (CSM == CXXCopyAssignment);
7326         // FIXME: Explain why this special member can't be const.
7327         HadError = true;
7328       } else {
7329         Diag(MD->getLocation(),
7330              diag::err_defaulted_special_member_move_const_param)
7331           << (CSM == CXXMoveAssignment);
7332         HadError = true;
7333       }
7334     }
7335   } else if (ExpectedParams) {
7336     // A copy assignment operator can take its argument by value, but a
7337     // defaulted one cannot.
7338     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7339     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7340     HadError = true;
7341   }
7342 
7343   // C++11 [dcl.fct.def.default]p2:
7344   //   An explicitly-defaulted function may be declared constexpr only if it
7345   //   would have been implicitly declared as constexpr,
7346   // Do not apply this rule to members of class templates, since core issue 1358
7347   // makes such functions always instantiate to constexpr functions. For
7348   // functions which cannot be constexpr (for non-constructors in C++11 and for
7349   // destructors in C++14 and C++17), this is checked elsewhere.
7350   //
7351   // FIXME: This should not apply if the member is deleted.
7352   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7353                                                      HasConstParam);
7354   if ((getLangOpts().CPlusPlus20 ||
7355        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7356                                   : isa<CXXConstructorDecl>(MD))) &&
7357       MD->isConstexpr() && !Constexpr &&
7358       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7359     Diag(MD->getBeginLoc(), MD->isConsteval()
7360                                 ? diag::err_incorrect_defaulted_consteval
7361                                 : diag::err_incorrect_defaulted_constexpr)
7362         << CSM;
7363     // FIXME: Explain why the special member can't be constexpr.
7364     HadError = true;
7365   }
7366 
7367   if (First) {
7368     // C++2a [dcl.fct.def.default]p3:
7369     //   If a function is explicitly defaulted on its first declaration, it is
7370     //   implicitly considered to be constexpr if the implicit declaration
7371     //   would be.
7372     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7373                                           ? ConstexprSpecKind::Consteval
7374                                           : ConstexprSpecKind::Constexpr)
7375                                    : ConstexprSpecKind::Unspecified);
7376 
7377     if (!Type->hasExceptionSpec()) {
7378       // C++2a [except.spec]p3:
7379       //   If a declaration of a function does not have a noexcept-specifier
7380       //   [and] is defaulted on its first declaration, [...] the exception
7381       //   specification is as specified below
7382       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7383       EPI.ExceptionSpec.Type = EST_Unevaluated;
7384       EPI.ExceptionSpec.SourceDecl = MD;
7385       MD->setType(Context.getFunctionType(ReturnType,
7386                                           llvm::makeArrayRef(&ArgType,
7387                                                              ExpectedParams),
7388                                           EPI));
7389     }
7390   }
7391 
7392   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7393     if (First) {
7394       SetDeclDeleted(MD, MD->getLocation());
7395       if (!inTemplateInstantiation() && !HadError) {
7396         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7397         if (ShouldDeleteForTypeMismatch) {
7398           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7399         } else {
7400           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7401         }
7402       }
7403       if (ShouldDeleteForTypeMismatch && !HadError) {
7404         Diag(MD->getLocation(),
7405              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7406       }
7407     } else {
7408       // C++11 [dcl.fct.def.default]p4:
7409       //   [For a] user-provided explicitly-defaulted function [...] if such a
7410       //   function is implicitly defined as deleted, the program is ill-formed.
7411       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7412       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7413       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7414       HadError = true;
7415     }
7416   }
7417 
7418   return HadError;
7419 }
7420 
7421 namespace {
7422 /// Helper class for building and checking a defaulted comparison.
7423 ///
7424 /// Defaulted functions are built in two phases:
7425 ///
7426 ///  * First, the set of operations that the function will perform are
7427 ///    identified, and some of them are checked. If any of the checked
7428 ///    operations is invalid in certain ways, the comparison function is
7429 ///    defined as deleted and no body is built.
7430 ///  * Then, if the function is not defined as deleted, the body is built.
7431 ///
7432 /// This is accomplished by performing two visitation steps over the eventual
7433 /// body of the function.
7434 template<typename Derived, typename ResultList, typename Result,
7435          typename Subobject>
7436 class DefaultedComparisonVisitor {
7437 public:
7438   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7439 
7440   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7441                              DefaultedComparisonKind DCK)
7442       : S(S), RD(RD), FD(FD), DCK(DCK) {
7443     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7444       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7445       // UnresolvedSet to avoid this copy.
7446       Fns.assign(Info->getUnqualifiedLookups().begin(),
7447                  Info->getUnqualifiedLookups().end());
7448     }
7449   }
7450 
7451   ResultList visit() {
7452     // The type of an lvalue naming a parameter of this function.
7453     QualType ParamLvalType =
7454         FD->getParamDecl(0)->getType().getNonReferenceType();
7455 
7456     ResultList Results;
7457 
7458     switch (DCK) {
7459     case DefaultedComparisonKind::None:
7460       llvm_unreachable("not a defaulted comparison");
7461 
7462     case DefaultedComparisonKind::Equal:
7463     case DefaultedComparisonKind::ThreeWay:
7464       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7465       return Results;
7466 
7467     case DefaultedComparisonKind::NotEqual:
7468     case DefaultedComparisonKind::Relational:
7469       Results.add(getDerived().visitExpandedSubobject(
7470           ParamLvalType, getDerived().getCompleteObject()));
7471       return Results;
7472     }
7473     llvm_unreachable("");
7474   }
7475 
7476 protected:
7477   Derived &getDerived() { return static_cast<Derived&>(*this); }
7478 
7479   /// Visit the expanded list of subobjects of the given type, as specified in
7480   /// C++2a [class.compare.default].
7481   ///
7482   /// \return \c true if the ResultList object said we're done, \c false if not.
7483   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7484                        Qualifiers Quals) {
7485     // C++2a [class.compare.default]p4:
7486     //   The direct base class subobjects of C
7487     for (CXXBaseSpecifier &Base : Record->bases())
7488       if (Results.add(getDerived().visitSubobject(
7489               S.Context.getQualifiedType(Base.getType(), Quals),
7490               getDerived().getBase(&Base))))
7491         return true;
7492 
7493     //   followed by the non-static data members of C
7494     for (FieldDecl *Field : Record->fields()) {
7495       // Recursively expand anonymous structs.
7496       if (Field->isAnonymousStructOrUnion()) {
7497         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7498                             Quals))
7499           return true;
7500         continue;
7501       }
7502 
7503       // Figure out the type of an lvalue denoting this field.
7504       Qualifiers FieldQuals = Quals;
7505       if (Field->isMutable())
7506         FieldQuals.removeConst();
7507       QualType FieldType =
7508           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7509 
7510       if (Results.add(getDerived().visitSubobject(
7511               FieldType, getDerived().getField(Field))))
7512         return true;
7513     }
7514 
7515     //   form a list of subobjects.
7516     return false;
7517   }
7518 
7519   Result visitSubobject(QualType Type, Subobject Subobj) {
7520     //   In that list, any subobject of array type is recursively expanded
7521     const ArrayType *AT = S.Context.getAsArrayType(Type);
7522     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7523       return getDerived().visitSubobjectArray(CAT->getElementType(),
7524                                               CAT->getSize(), Subobj);
7525     return getDerived().visitExpandedSubobject(Type, Subobj);
7526   }
7527 
7528   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7529                              Subobject Subobj) {
7530     return getDerived().visitSubobject(Type, Subobj);
7531   }
7532 
7533 protected:
7534   Sema &S;
7535   CXXRecordDecl *RD;
7536   FunctionDecl *FD;
7537   DefaultedComparisonKind DCK;
7538   UnresolvedSet<16> Fns;
7539 };
7540 
7541 /// Information about a defaulted comparison, as determined by
7542 /// DefaultedComparisonAnalyzer.
7543 struct DefaultedComparisonInfo {
7544   bool Deleted = false;
7545   bool Constexpr = true;
7546   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7547 
7548   static DefaultedComparisonInfo deleted() {
7549     DefaultedComparisonInfo Deleted;
7550     Deleted.Deleted = true;
7551     return Deleted;
7552   }
7553 
7554   bool add(const DefaultedComparisonInfo &R) {
7555     Deleted |= R.Deleted;
7556     Constexpr &= R.Constexpr;
7557     Category = commonComparisonType(Category, R.Category);
7558     return Deleted;
7559   }
7560 };
7561 
7562 /// An element in the expanded list of subobjects of a defaulted comparison, as
7563 /// specified in C++2a [class.compare.default]p4.
7564 struct DefaultedComparisonSubobject {
7565   enum { CompleteObject, Member, Base } Kind;
7566   NamedDecl *Decl;
7567   SourceLocation Loc;
7568 };
7569 
7570 /// A visitor over the notional body of a defaulted comparison that determines
7571 /// whether that body would be deleted or constexpr.
7572 class DefaultedComparisonAnalyzer
7573     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7574                                         DefaultedComparisonInfo,
7575                                         DefaultedComparisonInfo,
7576                                         DefaultedComparisonSubobject> {
7577 public:
7578   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7579 
7580 private:
7581   DiagnosticKind Diagnose;
7582 
7583 public:
7584   using Base = DefaultedComparisonVisitor;
7585   using Result = DefaultedComparisonInfo;
7586   using Subobject = DefaultedComparisonSubobject;
7587 
7588   friend Base;
7589 
7590   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7591                               DefaultedComparisonKind DCK,
7592                               DiagnosticKind Diagnose = NoDiagnostics)
7593       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7594 
7595   Result visit() {
7596     if ((DCK == DefaultedComparisonKind::Equal ||
7597          DCK == DefaultedComparisonKind::ThreeWay) &&
7598         RD->hasVariantMembers()) {
7599       // C++2a [class.compare.default]p2 [P2002R0]:
7600       //   A defaulted comparison operator function for class C is defined as
7601       //   deleted if [...] C has variant members.
7602       if (Diagnose == ExplainDeleted) {
7603         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7604           << FD << RD->isUnion() << RD;
7605       }
7606       return Result::deleted();
7607     }
7608 
7609     return Base::visit();
7610   }
7611 
7612 private:
7613   Subobject getCompleteObject() {
7614     return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
7615   }
7616 
7617   Subobject getBase(CXXBaseSpecifier *Base) {
7618     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7619                      Base->getBaseTypeLoc()};
7620   }
7621 
7622   Subobject getField(FieldDecl *Field) {
7623     return Subobject{Subobject::Member, Field, Field->getLocation()};
7624   }
7625 
7626   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7627     // C++2a [class.compare.default]p2 [P2002R0]:
7628     //   A defaulted <=> or == operator function for class C is defined as
7629     //   deleted if any non-static data member of C is of reference type
7630     if (Type->isReferenceType()) {
7631       if (Diagnose == ExplainDeleted) {
7632         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7633             << FD << RD;
7634       }
7635       return Result::deleted();
7636     }
7637 
7638     // [...] Let xi be an lvalue denoting the ith element [...]
7639     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7640     Expr *Args[] = {&Xi, &Xi};
7641 
7642     // All operators start by trying to apply that same operator recursively.
7643     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7644     assert(OO != OO_None && "not an overloaded operator!");
7645     return visitBinaryOperator(OO, Args, Subobj);
7646   }
7647 
7648   Result
7649   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7650                       Subobject Subobj,
7651                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7652     // Note that there is no need to consider rewritten candidates here if
7653     // we've already found there is no viable 'operator<=>' candidate (and are
7654     // considering synthesizing a '<=>' from '==' and '<').
7655     OverloadCandidateSet CandidateSet(
7656         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7657         OverloadCandidateSet::OperatorRewriteInfo(
7658             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7659 
7660     /// C++2a [class.compare.default]p1 [P2002R0]:
7661     ///   [...] the defaulted function itself is never a candidate for overload
7662     ///   resolution [...]
7663     CandidateSet.exclude(FD);
7664 
7665     if (Args[0]->getType()->isOverloadableType())
7666       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7667     else {
7668       // FIXME: We determine whether this is a valid expression by checking to
7669       // see if there's a viable builtin operator candidate for it. That isn't
7670       // really what the rules ask us to do, but should give the right results.
7671       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7672     }
7673 
7674     Result R;
7675 
7676     OverloadCandidateSet::iterator Best;
7677     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7678     case OR_Success: {
7679       // C++2a [class.compare.secondary]p2 [P2002R0]:
7680       //   The operator function [...] is defined as deleted if [...] the
7681       //   candidate selected by overload resolution is not a rewritten
7682       //   candidate.
7683       if ((DCK == DefaultedComparisonKind::NotEqual ||
7684            DCK == DefaultedComparisonKind::Relational) &&
7685           !Best->RewriteKind) {
7686         if (Diagnose == ExplainDeleted) {
7687           S.Diag(Best->Function->getLocation(),
7688                  diag::note_defaulted_comparison_not_rewritten_callee)
7689               << FD;
7690         }
7691         return Result::deleted();
7692       }
7693 
7694       // Throughout C++2a [class.compare]: if overload resolution does not
7695       // result in a usable function, the candidate function is defined as
7696       // deleted. This requires that we selected an accessible function.
7697       //
7698       // Note that this only considers the access of the function when named
7699       // within the type of the subobject, and not the access path for any
7700       // derived-to-base conversion.
7701       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7702       if (ArgClass && Best->FoundDecl.getDecl() &&
7703           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7704         QualType ObjectType = Subobj.Kind == Subobject::Member
7705                                   ? Args[0]->getType()
7706                                   : S.Context.getRecordType(RD);
7707         if (!S.isMemberAccessibleForDeletion(
7708                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7709                 Diagnose == ExplainDeleted
7710                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7711                           << FD << Subobj.Kind << Subobj.Decl
7712                     : S.PDiag()))
7713           return Result::deleted();
7714       }
7715 
7716       // C++2a [class.compare.default]p3 [P2002R0]:
7717       //   A defaulted comparison function is constexpr-compatible if [...]
7718       //   no overlod resolution performed [...] results in a non-constexpr
7719       //   function.
7720       if (FunctionDecl *BestFD = Best->Function) {
7721         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7722         // If it's not constexpr, explain why not.
7723         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7724           if (Subobj.Kind != Subobject::CompleteObject)
7725             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7726               << Subobj.Kind << Subobj.Decl;
7727           S.Diag(BestFD->getLocation(),
7728                  diag::note_defaulted_comparison_not_constexpr_here);
7729           // Bail out after explaining; we don't want any more notes.
7730           return Result::deleted();
7731         }
7732         R.Constexpr &= BestFD->isConstexpr();
7733       }
7734 
7735       if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7736         if (auto *BestFD = Best->Function) {
7737           // If any callee has an undeduced return type, deduce it now.
7738           // FIXME: It's not clear how a failure here should be handled. For
7739           // now, we produce an eager diagnostic, because that is forward
7740           // compatible with most (all?) other reasonable options.
7741           if (BestFD->getReturnType()->isUndeducedType() &&
7742               S.DeduceReturnType(BestFD, FD->getLocation(),
7743                                  /*Diagnose=*/false)) {
7744             // Don't produce a duplicate error when asked to explain why the
7745             // comparison is deleted: we diagnosed that when initially checking
7746             // the defaulted operator.
7747             if (Diagnose == NoDiagnostics) {
7748               S.Diag(
7749                   FD->getLocation(),
7750                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7751                   << Subobj.Kind << Subobj.Decl;
7752               S.Diag(
7753                   Subobj.Loc,
7754                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7755                   << Subobj.Kind << Subobj.Decl;
7756               S.Diag(BestFD->getLocation(),
7757                      diag::note_defaulted_comparison_cannot_deduce_callee)
7758                   << Subobj.Kind << Subobj.Decl;
7759             }
7760             return Result::deleted();
7761           }
7762           if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7763               BestFD->getCallResultType())) {
7764             R.Category = Info->Kind;
7765           } else {
7766             if (Diagnose == ExplainDeleted) {
7767               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7768                   << Subobj.Kind << Subobj.Decl
7769                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7770               S.Diag(BestFD->getLocation(),
7771                      diag::note_defaulted_comparison_cannot_deduce_callee)
7772                   << Subobj.Kind << Subobj.Decl;
7773             }
7774             return Result::deleted();
7775           }
7776         } else {
7777           Optional<ComparisonCategoryType> Cat =
7778               getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7779           assert(Cat && "no category for builtin comparison?");
7780           R.Category = *Cat;
7781         }
7782       }
7783 
7784       // Note that we might be rewriting to a different operator. That call is
7785       // not considered until we come to actually build the comparison function.
7786       break;
7787     }
7788 
7789     case OR_Ambiguous:
7790       if (Diagnose == ExplainDeleted) {
7791         unsigned Kind = 0;
7792         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7793           Kind = OO == OO_EqualEqual ? 1 : 2;
7794         CandidateSet.NoteCandidates(
7795             PartialDiagnosticAt(
7796                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7797                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7798             S, OCD_AmbiguousCandidates, Args);
7799       }
7800       R = Result::deleted();
7801       break;
7802 
7803     case OR_Deleted:
7804       if (Diagnose == ExplainDeleted) {
7805         if ((DCK == DefaultedComparisonKind::NotEqual ||
7806              DCK == DefaultedComparisonKind::Relational) &&
7807             !Best->RewriteKind) {
7808           S.Diag(Best->Function->getLocation(),
7809                  diag::note_defaulted_comparison_not_rewritten_callee)
7810               << FD;
7811         } else {
7812           S.Diag(Subobj.Loc,
7813                  diag::note_defaulted_comparison_calls_deleted)
7814               << FD << Subobj.Kind << Subobj.Decl;
7815           S.NoteDeletedFunction(Best->Function);
7816         }
7817       }
7818       R = Result::deleted();
7819       break;
7820 
7821     case OR_No_Viable_Function:
7822       // If there's no usable candidate, we're done unless we can rewrite a
7823       // '<=>' in terms of '==' and '<'.
7824       if (OO == OO_Spaceship &&
7825           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7826         // For any kind of comparison category return type, we need a usable
7827         // '==' and a usable '<'.
7828         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7829                                        &CandidateSet)))
7830           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7831         break;
7832       }
7833 
7834       if (Diagnose == ExplainDeleted) {
7835         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7836             << FD << Subobj.Kind << Subobj.Decl;
7837 
7838         // For a three-way comparison, list both the candidates for the
7839         // original operator and the candidates for the synthesized operator.
7840         if (SpaceshipCandidates) {
7841           SpaceshipCandidates->NoteCandidates(
7842               S, Args,
7843               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7844                                                       Args, FD->getLocation()));
7845           S.Diag(Subobj.Loc,
7846                  diag::note_defaulted_comparison_no_viable_function_synthesized)
7847               << (OO == OO_EqualEqual ? 0 : 1);
7848         }
7849 
7850         CandidateSet.NoteCandidates(
7851             S, Args,
7852             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7853                                             FD->getLocation()));
7854       }
7855       R = Result::deleted();
7856       break;
7857     }
7858 
7859     return R;
7860   }
7861 };
7862 
7863 /// A list of statements.
7864 struct StmtListResult {
7865   bool IsInvalid = false;
7866   llvm::SmallVector<Stmt*, 16> Stmts;
7867 
7868   bool add(const StmtResult &S) {
7869     IsInvalid |= S.isInvalid();
7870     if (IsInvalid)
7871       return true;
7872     Stmts.push_back(S.get());
7873     return false;
7874   }
7875 };
7876 
7877 /// A visitor over the notional body of a defaulted comparison that synthesizes
7878 /// the actual body.
7879 class DefaultedComparisonSynthesizer
7880     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7881                                         StmtListResult, StmtResult,
7882                                         std::pair<ExprResult, ExprResult>> {
7883   SourceLocation Loc;
7884   unsigned ArrayDepth = 0;
7885 
7886 public:
7887   using Base = DefaultedComparisonVisitor;
7888   using ExprPair = std::pair<ExprResult, ExprResult>;
7889 
7890   friend Base;
7891 
7892   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7893                                  DefaultedComparisonKind DCK,
7894                                  SourceLocation BodyLoc)
7895       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7896 
7897   /// Build a suitable function body for this defaulted comparison operator.
7898   StmtResult build() {
7899     Sema::CompoundScopeRAII CompoundScope(S);
7900 
7901     StmtListResult Stmts = visit();
7902     if (Stmts.IsInvalid)
7903       return StmtError();
7904 
7905     ExprResult RetVal;
7906     switch (DCK) {
7907     case DefaultedComparisonKind::None:
7908       llvm_unreachable("not a defaulted comparison");
7909 
7910     case DefaultedComparisonKind::Equal: {
7911       // C++2a [class.eq]p3:
7912       //   [...] compar[e] the corresponding elements [...] until the first
7913       //   index i where xi == yi yields [...] false. If no such index exists,
7914       //   V is true. Otherwise, V is false.
7915       //
7916       // Join the comparisons with '&&'s and return the result. Use a right
7917       // fold (traversing the conditions right-to-left), because that
7918       // short-circuits more naturally.
7919       auto OldStmts = std::move(Stmts.Stmts);
7920       Stmts.Stmts.clear();
7921       ExprResult CmpSoFar;
7922       // Finish a particular comparison chain.
7923       auto FinishCmp = [&] {
7924         if (Expr *Prior = CmpSoFar.get()) {
7925           // Convert the last expression to 'return ...;'
7926           if (RetVal.isUnset() && Stmts.Stmts.empty())
7927             RetVal = CmpSoFar;
7928           // Convert any prior comparison to 'if (!(...)) return false;'
7929           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
7930             return true;
7931           CmpSoFar = ExprResult();
7932         }
7933         return false;
7934       };
7935       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
7936         Expr *E = dyn_cast<Expr>(EAsStmt);
7937         if (!E) {
7938           // Found an array comparison.
7939           if (FinishCmp() || Stmts.add(EAsStmt))
7940             return StmtError();
7941           continue;
7942         }
7943 
7944         if (CmpSoFar.isUnset()) {
7945           CmpSoFar = E;
7946           continue;
7947         }
7948         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
7949         if (CmpSoFar.isInvalid())
7950           return StmtError();
7951       }
7952       if (FinishCmp())
7953         return StmtError();
7954       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
7955       //   If no such index exists, V is true.
7956       if (RetVal.isUnset())
7957         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
7958       break;
7959     }
7960 
7961     case DefaultedComparisonKind::ThreeWay: {
7962       // Per C++2a [class.spaceship]p3, as a fallback add:
7963       // return static_cast<R>(std::strong_ordering::equal);
7964       QualType StrongOrdering = S.CheckComparisonCategoryType(
7965           ComparisonCategoryType::StrongOrdering, Loc,
7966           Sema::ComparisonCategoryUsage::DefaultedOperator);
7967       if (StrongOrdering.isNull())
7968         return StmtError();
7969       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
7970                              .getValueInfo(ComparisonCategoryResult::Equal)
7971                              ->VD;
7972       RetVal = getDecl(EqualVD);
7973       if (RetVal.isInvalid())
7974         return StmtError();
7975       RetVal = buildStaticCastToR(RetVal.get());
7976       break;
7977     }
7978 
7979     case DefaultedComparisonKind::NotEqual:
7980     case DefaultedComparisonKind::Relational:
7981       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
7982       break;
7983     }
7984 
7985     // Build the final return statement.
7986     if (RetVal.isInvalid())
7987       return StmtError();
7988     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
7989     if (ReturnStmt.isInvalid())
7990       return StmtError();
7991     Stmts.Stmts.push_back(ReturnStmt.get());
7992 
7993     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
7994   }
7995 
7996 private:
7997   ExprResult getDecl(ValueDecl *VD) {
7998     return S.BuildDeclarationNameExpr(
7999         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8000   }
8001 
8002   ExprResult getParam(unsigned I) {
8003     ParmVarDecl *PD = FD->getParamDecl(I);
8004     return getDecl(PD);
8005   }
8006 
8007   ExprPair getCompleteObject() {
8008     unsigned Param = 0;
8009     ExprResult LHS;
8010     if (isa<CXXMethodDecl>(FD)) {
8011       // LHS is '*this'.
8012       LHS = S.ActOnCXXThis(Loc);
8013       if (!LHS.isInvalid())
8014         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8015     } else {
8016       LHS = getParam(Param++);
8017     }
8018     ExprResult RHS = getParam(Param++);
8019     assert(Param == FD->getNumParams());
8020     return {LHS, RHS};
8021   }
8022 
8023   ExprPair getBase(CXXBaseSpecifier *Base) {
8024     ExprPair Obj = getCompleteObject();
8025     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8026       return {ExprError(), ExprError()};
8027     CXXCastPath Path = {Base};
8028     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8029                                 CK_DerivedToBase, VK_LValue, &Path),
8030             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8031                                 CK_DerivedToBase, VK_LValue, &Path)};
8032   }
8033 
8034   ExprPair getField(FieldDecl *Field) {
8035     ExprPair Obj = getCompleteObject();
8036     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8037       return {ExprError(), ExprError()};
8038 
8039     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8040     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8041     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8042                                       CXXScopeSpec(), Field, Found, NameInfo),
8043             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8044                                       CXXScopeSpec(), Field, Found, NameInfo)};
8045   }
8046 
8047   // FIXME: When expanding a subobject, register a note in the code synthesis
8048   // stack to say which subobject we're comparing.
8049 
8050   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8051     if (Cond.isInvalid())
8052       return StmtError();
8053 
8054     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8055     if (NotCond.isInvalid())
8056       return StmtError();
8057 
8058     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8059     assert(!False.isInvalid() && "should never fail");
8060     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8061     if (ReturnFalse.isInvalid())
8062       return StmtError();
8063 
8064     return S.ActOnIfStmt(Loc, false, Loc, nullptr,
8065                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8066                                           Sema::ConditionKind::Boolean),
8067                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8068   }
8069 
8070   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8071                                  ExprPair Subobj) {
8072     QualType SizeType = S.Context.getSizeType();
8073     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8074 
8075     // Build 'size_t i$n = 0'.
8076     IdentifierInfo *IterationVarName = nullptr;
8077     {
8078       SmallString<8> Str;
8079       llvm::raw_svector_ostream OS(Str);
8080       OS << "i" << ArrayDepth;
8081       IterationVarName = &S.Context.Idents.get(OS.str());
8082     }
8083     VarDecl *IterationVar = VarDecl::Create(
8084         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8085         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8086     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8087     IterationVar->setInit(
8088         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8089     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8090 
8091     auto IterRef = [&] {
8092       ExprResult Ref = S.BuildDeclarationNameExpr(
8093           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8094           IterationVar);
8095       assert(!Ref.isInvalid() && "can't reference our own variable?");
8096       return Ref.get();
8097     };
8098 
8099     // Build 'i$n != Size'.
8100     ExprResult Cond = S.CreateBuiltinBinOp(
8101         Loc, BO_NE, IterRef(),
8102         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8103     assert(!Cond.isInvalid() && "should never fail");
8104 
8105     // Build '++i$n'.
8106     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8107     assert(!Inc.isInvalid() && "should never fail");
8108 
8109     // Build 'a[i$n]' and 'b[i$n]'.
8110     auto Index = [&](ExprResult E) {
8111       if (E.isInvalid())
8112         return ExprError();
8113       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8114     };
8115     Subobj.first = Index(Subobj.first);
8116     Subobj.second = Index(Subobj.second);
8117 
8118     // Compare the array elements.
8119     ++ArrayDepth;
8120     StmtResult Substmt = visitSubobject(Type, Subobj);
8121     --ArrayDepth;
8122 
8123     if (Substmt.isInvalid())
8124       return StmtError();
8125 
8126     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8127     // For outer levels or for an 'operator<=>' we already have a suitable
8128     // statement that returns as necessary.
8129     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8130       assert(DCK == DefaultedComparisonKind::Equal &&
8131              "should have non-expression statement");
8132       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8133       if (Substmt.isInvalid())
8134         return StmtError();
8135     }
8136 
8137     // Build 'for (...) ...'
8138     return S.ActOnForStmt(Loc, Loc, Init,
8139                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8140                                            Sema::ConditionKind::Boolean),
8141                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8142                           Substmt.get());
8143   }
8144 
8145   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8146     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8147       return StmtError();
8148 
8149     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8150     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8151     ExprResult Op;
8152     if (Type->isOverloadableType())
8153       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8154                                    Obj.second.get(), /*PerformADL=*/true,
8155                                    /*AllowRewrittenCandidates=*/true, FD);
8156     else
8157       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8158     if (Op.isInvalid())
8159       return StmtError();
8160 
8161     switch (DCK) {
8162     case DefaultedComparisonKind::None:
8163       llvm_unreachable("not a defaulted comparison");
8164 
8165     case DefaultedComparisonKind::Equal:
8166       // Per C++2a [class.eq]p2, each comparison is individually contextually
8167       // converted to bool.
8168       Op = S.PerformContextuallyConvertToBool(Op.get());
8169       if (Op.isInvalid())
8170         return StmtError();
8171       return Op.get();
8172 
8173     case DefaultedComparisonKind::ThreeWay: {
8174       // Per C++2a [class.spaceship]p3, form:
8175       //   if (R cmp = static_cast<R>(op); cmp != 0)
8176       //     return cmp;
8177       QualType R = FD->getReturnType();
8178       Op = buildStaticCastToR(Op.get());
8179       if (Op.isInvalid())
8180         return StmtError();
8181 
8182       // R cmp = ...;
8183       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8184       VarDecl *VD =
8185           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8186                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8187       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8188       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8189 
8190       // cmp != 0
8191       ExprResult VDRef = getDecl(VD);
8192       if (VDRef.isInvalid())
8193         return StmtError();
8194       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8195       Expr *Zero =
8196           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8197       ExprResult Comp;
8198       if (VDRef.get()->getType()->isOverloadableType())
8199         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8200                                        true, FD);
8201       else
8202         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8203       if (Comp.isInvalid())
8204         return StmtError();
8205       Sema::ConditionResult Cond = S.ActOnCondition(
8206           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8207       if (Cond.isInvalid())
8208         return StmtError();
8209 
8210       // return cmp;
8211       VDRef = getDecl(VD);
8212       if (VDRef.isInvalid())
8213         return StmtError();
8214       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8215       if (ReturnStmt.isInvalid())
8216         return StmtError();
8217 
8218       // if (...)
8219       return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc,
8220                            ReturnStmt.get(),
8221                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8222     }
8223 
8224     case DefaultedComparisonKind::NotEqual:
8225     case DefaultedComparisonKind::Relational:
8226       // C++2a [class.compare.secondary]p2:
8227       //   Otherwise, the operator function yields x @ y.
8228       return Op.get();
8229     }
8230     llvm_unreachable("");
8231   }
8232 
8233   /// Build "static_cast<R>(E)".
8234   ExprResult buildStaticCastToR(Expr *E) {
8235     QualType R = FD->getReturnType();
8236     assert(!R->isUndeducedType() && "type should have been deduced already");
8237 
8238     // Don't bother forming a no-op cast in the common case.
8239     if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8240       return E;
8241     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8242                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8243                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8244   }
8245 };
8246 }
8247 
8248 /// Perform the unqualified lookups that might be needed to form a defaulted
8249 /// comparison function for the given operator.
8250 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8251                                                   UnresolvedSetImpl &Operators,
8252                                                   OverloadedOperatorKind Op) {
8253   auto Lookup = [&](OverloadedOperatorKind OO) {
8254     Self.LookupOverloadedOperatorName(OO, S, Operators);
8255   };
8256 
8257   // Every defaulted operator looks up itself.
8258   Lookup(Op);
8259   // ... and the rewritten form of itself, if any.
8260   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8261     Lookup(ExtraOp);
8262 
8263   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8264   // synthesize a three-way comparison from '<' and '=='. In a dependent
8265   // context, we also need to look up '==' in case we implicitly declare a
8266   // defaulted 'operator=='.
8267   if (Op == OO_Spaceship) {
8268     Lookup(OO_ExclaimEqual);
8269     Lookup(OO_Less);
8270     Lookup(OO_EqualEqual);
8271   }
8272 }
8273 
8274 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8275                                               DefaultedComparisonKind DCK) {
8276   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8277 
8278   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8279   assert(RD && "defaulted comparison is not defaulted in a class");
8280 
8281   // Perform any unqualified lookups we're going to need to default this
8282   // function.
8283   if (S) {
8284     UnresolvedSet<32> Operators;
8285     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8286                                           FD->getOverloadedOperator());
8287     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8288         Context, Operators.pairs()));
8289   }
8290 
8291   // C++2a [class.compare.default]p1:
8292   //   A defaulted comparison operator function for some class C shall be a
8293   //   non-template function declared in the member-specification of C that is
8294   //    -- a non-static const member of C having one parameter of type
8295   //       const C&, or
8296   //    -- a friend of C having two parameters of type const C& or two
8297   //       parameters of type C.
8298   QualType ExpectedParmType1 = Context.getRecordType(RD);
8299   QualType ExpectedParmType2 =
8300       Context.getLValueReferenceType(ExpectedParmType1.withConst());
8301   if (isa<CXXMethodDecl>(FD))
8302     ExpectedParmType1 = ExpectedParmType2;
8303   for (const ParmVarDecl *Param : FD->parameters()) {
8304     if (!Param->getType()->isDependentType() &&
8305         !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8306         !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8307       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8308       // corresponding defaulted 'operator<=>' already.
8309       if (!FD->isImplicit()) {
8310         Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8311             << (int)DCK << Param->getType() << ExpectedParmType1
8312             << !isa<CXXMethodDecl>(FD)
8313             << ExpectedParmType2 << Param->getSourceRange();
8314       }
8315       return true;
8316     }
8317   }
8318   if (FD->getNumParams() == 2 &&
8319       !Context.hasSameType(FD->getParamDecl(0)->getType(),
8320                            FD->getParamDecl(1)->getType())) {
8321     if (!FD->isImplicit()) {
8322       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8323           << (int)DCK
8324           << FD->getParamDecl(0)->getType()
8325           << FD->getParamDecl(0)->getSourceRange()
8326           << FD->getParamDecl(1)->getType()
8327           << FD->getParamDecl(1)->getSourceRange();
8328     }
8329     return true;
8330   }
8331 
8332   // ... non-static const member ...
8333   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8334     assert(!MD->isStatic() && "comparison function cannot be a static member");
8335     if (!MD->isConst()) {
8336       SourceLocation InsertLoc;
8337       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8338         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8339       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8340       // corresponding defaulted 'operator<=>' already.
8341       if (!MD->isImplicit()) {
8342         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8343           << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8344       }
8345 
8346       // Add the 'const' to the type to recover.
8347       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8348       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8349       EPI.TypeQuals.addConst();
8350       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8351                                           FPT->getParamTypes(), EPI));
8352     }
8353   } else {
8354     // A non-member function declared in a class must be a friend.
8355     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8356   }
8357 
8358   // C++2a [class.eq]p1, [class.rel]p1:
8359   //   A [defaulted comparison other than <=>] shall have a declared return
8360   //   type bool.
8361   if (DCK != DefaultedComparisonKind::ThreeWay &&
8362       !FD->getDeclaredReturnType()->isDependentType() &&
8363       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8364     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8365         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8366         << FD->getReturnTypeSourceRange();
8367     return true;
8368   }
8369   // C++2a [class.spaceship]p2 [P2002R0]:
8370   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8371   //   R shall not contain a placeholder type.
8372   if (DCK == DefaultedComparisonKind::ThreeWay &&
8373       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8374       !Context.hasSameType(FD->getDeclaredReturnType(),
8375                            Context.getAutoDeductType())) {
8376     Diag(FD->getLocation(),
8377          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8378         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8379         << FD->getReturnTypeSourceRange();
8380     return true;
8381   }
8382 
8383   // For a defaulted function in a dependent class, defer all remaining checks
8384   // until instantiation.
8385   if (RD->isDependentType())
8386     return false;
8387 
8388   // Determine whether the function should be defined as deleted.
8389   DefaultedComparisonInfo Info =
8390       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8391 
8392   bool First = FD == FD->getCanonicalDecl();
8393 
8394   // If we want to delete the function, then do so; there's nothing else to
8395   // check in that case.
8396   if (Info.Deleted) {
8397     if (!First) {
8398       // C++11 [dcl.fct.def.default]p4:
8399       //   [For a] user-provided explicitly-defaulted function [...] if such a
8400       //   function is implicitly defined as deleted, the program is ill-formed.
8401       //
8402       // This is really just a consequence of the general rule that you can
8403       // only delete a function on its first declaration.
8404       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8405           << FD->isImplicit() << (int)DCK;
8406       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8407                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8408           .visit();
8409       return true;
8410     }
8411 
8412     SetDeclDeleted(FD, FD->getLocation());
8413     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8414       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8415           << (int)DCK;
8416       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8417                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8418           .visit();
8419     }
8420     return false;
8421   }
8422 
8423   // C++2a [class.spaceship]p2:
8424   //   The return type is deduced as the common comparison type of R0, R1, ...
8425   if (DCK == DefaultedComparisonKind::ThreeWay &&
8426       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8427     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8428     if (RetLoc.isInvalid())
8429       RetLoc = FD->getBeginLoc();
8430     // FIXME: Should we really care whether we have the complete type and the
8431     // 'enumerator' constants here? A forward declaration seems sufficient.
8432     QualType Cat = CheckComparisonCategoryType(
8433         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8434     if (Cat.isNull())
8435       return true;
8436     Context.adjustDeducedFunctionResultType(
8437         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8438   }
8439 
8440   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8441   //   An explicitly-defaulted function that is not defined as deleted may be
8442   //   declared constexpr or consteval only if it is constexpr-compatible.
8443   // C++2a [class.compare.default]p3 [P2002R0]:
8444   //   A defaulted comparison function is constexpr-compatible if it satisfies
8445   //   the requirements for a constexpr function [...]
8446   // The only relevant requirements are that the parameter and return types are
8447   // literal types. The remaining conditions are checked by the analyzer.
8448   if (FD->isConstexpr()) {
8449     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8450         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8451         !Info.Constexpr) {
8452       Diag(FD->getBeginLoc(),
8453            diag::err_incorrect_defaulted_comparison_constexpr)
8454           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8455       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8456                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8457           .visit();
8458     }
8459   }
8460 
8461   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8462   //   If a constexpr-compatible function is explicitly defaulted on its first
8463   //   declaration, it is implicitly considered to be constexpr.
8464   // FIXME: Only applying this to the first declaration seems problematic, as
8465   // simple reorderings can affect the meaning of the program.
8466   if (First && !FD->isConstexpr() && Info.Constexpr)
8467     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8468 
8469   // C++2a [except.spec]p3:
8470   //   If a declaration of a function does not have a noexcept-specifier
8471   //   [and] is defaulted on its first declaration, [...] the exception
8472   //   specification is as specified below
8473   if (FD->getExceptionSpecType() == EST_None) {
8474     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8475     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8476     EPI.ExceptionSpec.Type = EST_Unevaluated;
8477     EPI.ExceptionSpec.SourceDecl = FD;
8478     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8479                                         FPT->getParamTypes(), EPI));
8480   }
8481 
8482   return false;
8483 }
8484 
8485 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8486                                              FunctionDecl *Spaceship) {
8487   Sema::CodeSynthesisContext Ctx;
8488   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8489   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8490   Ctx.Entity = Spaceship;
8491   pushCodeSynthesisContext(Ctx);
8492 
8493   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8494     EqualEqual->setImplicit();
8495 
8496   popCodeSynthesisContext();
8497 }
8498 
8499 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8500                                      DefaultedComparisonKind DCK) {
8501   assert(FD->isDefaulted() && !FD->isDeleted() &&
8502          !FD->doesThisDeclarationHaveABody());
8503   if (FD->willHaveBody() || FD->isInvalidDecl())
8504     return;
8505 
8506   SynthesizedFunctionScope Scope(*this, FD);
8507 
8508   // Add a context note for diagnostics produced after this point.
8509   Scope.addContextNote(UseLoc);
8510 
8511   {
8512     // Build and set up the function body.
8513     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8514     SourceLocation BodyLoc =
8515         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8516     StmtResult Body =
8517         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8518     if (Body.isInvalid()) {
8519       FD->setInvalidDecl();
8520       return;
8521     }
8522     FD->setBody(Body.get());
8523     FD->markUsed(Context);
8524   }
8525 
8526   // The exception specification is needed because we are defining the
8527   // function. Note that this will reuse the body we just built.
8528   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8529 
8530   if (ASTMutationListener *L = getASTMutationListener())
8531     L->CompletedImplicitDefinition(FD);
8532 }
8533 
8534 static Sema::ImplicitExceptionSpecification
8535 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8536                                         FunctionDecl *FD,
8537                                         Sema::DefaultedComparisonKind DCK) {
8538   ComputingExceptionSpec CES(S, FD, Loc);
8539   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8540 
8541   if (FD->isInvalidDecl())
8542     return ExceptSpec;
8543 
8544   // The common case is that we just defined the comparison function. In that
8545   // case, just look at whether the body can throw.
8546   if (FD->hasBody()) {
8547     ExceptSpec.CalledStmt(FD->getBody());
8548   } else {
8549     // Otherwise, build a body so we can check it. This should ideally only
8550     // happen when we're not actually marking the function referenced. (This is
8551     // only really important for efficiency: we don't want to build and throw
8552     // away bodies for comparison functions more than we strictly need to.)
8553 
8554     // Pretend to synthesize the function body in an unevaluated context.
8555     // Note that we can't actually just go ahead and define the function here:
8556     // we are not permitted to mark its callees as referenced.
8557     Sema::SynthesizedFunctionScope Scope(S, FD);
8558     EnterExpressionEvaluationContext Context(
8559         S, Sema::ExpressionEvaluationContext::Unevaluated);
8560 
8561     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8562     SourceLocation BodyLoc =
8563         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8564     StmtResult Body =
8565         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8566     if (!Body.isInvalid())
8567       ExceptSpec.CalledStmt(Body.get());
8568 
8569     // FIXME: Can we hold onto this body and just transform it to potentially
8570     // evaluated when we're asked to define the function rather than rebuilding
8571     // it? Either that, or we should only build the bits of the body that we
8572     // need (the expressions, not the statements).
8573   }
8574 
8575   return ExceptSpec;
8576 }
8577 
8578 void Sema::CheckDelayedMemberExceptionSpecs() {
8579   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8580   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8581 
8582   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8583   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8584 
8585   // Perform any deferred checking of exception specifications for virtual
8586   // destructors.
8587   for (auto &Check : Overriding)
8588     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8589 
8590   // Perform any deferred checking of exception specifications for befriended
8591   // special members.
8592   for (auto &Check : Equivalent)
8593     CheckEquivalentExceptionSpec(Check.second, Check.first);
8594 }
8595 
8596 namespace {
8597 /// CRTP base class for visiting operations performed by a special member
8598 /// function (or inherited constructor).
8599 template<typename Derived>
8600 struct SpecialMemberVisitor {
8601   Sema &S;
8602   CXXMethodDecl *MD;
8603   Sema::CXXSpecialMember CSM;
8604   Sema::InheritedConstructorInfo *ICI;
8605 
8606   // Properties of the special member, computed for convenience.
8607   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8608 
8609   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8610                        Sema::InheritedConstructorInfo *ICI)
8611       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8612     switch (CSM) {
8613     case Sema::CXXDefaultConstructor:
8614     case Sema::CXXCopyConstructor:
8615     case Sema::CXXMoveConstructor:
8616       IsConstructor = true;
8617       break;
8618     case Sema::CXXCopyAssignment:
8619     case Sema::CXXMoveAssignment:
8620       IsAssignment = true;
8621       break;
8622     case Sema::CXXDestructor:
8623       break;
8624     case Sema::CXXInvalid:
8625       llvm_unreachable("invalid special member kind");
8626     }
8627 
8628     if (MD->getNumParams()) {
8629       if (const ReferenceType *RT =
8630               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8631         ConstArg = RT->getPointeeType().isConstQualified();
8632     }
8633   }
8634 
8635   Derived &getDerived() { return static_cast<Derived&>(*this); }
8636 
8637   /// Is this a "move" special member?
8638   bool isMove() const {
8639     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8640   }
8641 
8642   /// Look up the corresponding special member in the given class.
8643   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8644                                              unsigned Quals, bool IsMutable) {
8645     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8646                                        ConstArg && !IsMutable);
8647   }
8648 
8649   /// Look up the constructor for the specified base class to see if it's
8650   /// overridden due to this being an inherited constructor.
8651   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8652     if (!ICI)
8653       return {};
8654     assert(CSM == Sema::CXXDefaultConstructor);
8655     auto *BaseCtor =
8656       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8657     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8658       return MD;
8659     return {};
8660   }
8661 
8662   /// A base or member subobject.
8663   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8664 
8665   /// Get the location to use for a subobject in diagnostics.
8666   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8667     // FIXME: For an indirect virtual base, the direct base leading to
8668     // the indirect virtual base would be a more useful choice.
8669     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8670       return B->getBaseTypeLoc();
8671     else
8672       return Subobj.get<FieldDecl*>()->getLocation();
8673   }
8674 
8675   enum BasesToVisit {
8676     /// Visit all non-virtual (direct) bases.
8677     VisitNonVirtualBases,
8678     /// Visit all direct bases, virtual or not.
8679     VisitDirectBases,
8680     /// Visit all non-virtual bases, and all virtual bases if the class
8681     /// is not abstract.
8682     VisitPotentiallyConstructedBases,
8683     /// Visit all direct or virtual bases.
8684     VisitAllBases
8685   };
8686 
8687   // Visit the bases and members of the class.
8688   bool visit(BasesToVisit Bases) {
8689     CXXRecordDecl *RD = MD->getParent();
8690 
8691     if (Bases == VisitPotentiallyConstructedBases)
8692       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8693 
8694     for (auto &B : RD->bases())
8695       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8696           getDerived().visitBase(&B))
8697         return true;
8698 
8699     if (Bases == VisitAllBases)
8700       for (auto &B : RD->vbases())
8701         if (getDerived().visitBase(&B))
8702           return true;
8703 
8704     for (auto *F : RD->fields())
8705       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8706           getDerived().visitField(F))
8707         return true;
8708 
8709     return false;
8710   }
8711 };
8712 }
8713 
8714 namespace {
8715 struct SpecialMemberDeletionInfo
8716     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8717   bool Diagnose;
8718 
8719   SourceLocation Loc;
8720 
8721   bool AllFieldsAreConst;
8722 
8723   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8724                             Sema::CXXSpecialMember CSM,
8725                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8726       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8727         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8728 
8729   bool inUnion() const { return MD->getParent()->isUnion(); }
8730 
8731   Sema::CXXSpecialMember getEffectiveCSM() {
8732     return ICI ? Sema::CXXInvalid : CSM;
8733   }
8734 
8735   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8736 
8737   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8738   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8739 
8740   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8741   bool shouldDeleteForField(FieldDecl *FD);
8742   bool shouldDeleteForAllConstMembers();
8743 
8744   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8745                                      unsigned Quals);
8746   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8747                                     Sema::SpecialMemberOverloadResult SMOR,
8748                                     bool IsDtorCallInCtor);
8749 
8750   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8751 };
8752 }
8753 
8754 /// Is the given special member inaccessible when used on the given
8755 /// sub-object.
8756 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8757                                              CXXMethodDecl *target) {
8758   /// If we're operating on a base class, the object type is the
8759   /// type of this special member.
8760   QualType objectTy;
8761   AccessSpecifier access = target->getAccess();
8762   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8763     objectTy = S.Context.getTypeDeclType(MD->getParent());
8764     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8765 
8766   // If we're operating on a field, the object type is the type of the field.
8767   } else {
8768     objectTy = S.Context.getTypeDeclType(target->getParent());
8769   }
8770 
8771   return S.isMemberAccessibleForDeletion(
8772       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8773 }
8774 
8775 /// Check whether we should delete a special member due to the implicit
8776 /// definition containing a call to a special member of a subobject.
8777 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8778     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8779     bool IsDtorCallInCtor) {
8780   CXXMethodDecl *Decl = SMOR.getMethod();
8781   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8782 
8783   int DiagKind = -1;
8784 
8785   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8786     DiagKind = !Decl ? 0 : 1;
8787   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8788     DiagKind = 2;
8789   else if (!isAccessible(Subobj, Decl))
8790     DiagKind = 3;
8791   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8792            !Decl->isTrivial()) {
8793     // A member of a union must have a trivial corresponding special member.
8794     // As a weird special case, a destructor call from a union's constructor
8795     // must be accessible and non-deleted, but need not be trivial. Such a
8796     // destructor is never actually called, but is semantically checked as
8797     // if it were.
8798     DiagKind = 4;
8799   }
8800 
8801   if (DiagKind == -1)
8802     return false;
8803 
8804   if (Diagnose) {
8805     if (Field) {
8806       S.Diag(Field->getLocation(),
8807              diag::note_deleted_special_member_class_subobject)
8808         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8809         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8810     } else {
8811       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8812       S.Diag(Base->getBeginLoc(),
8813              diag::note_deleted_special_member_class_subobject)
8814           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8815           << Base->getType() << DiagKind << IsDtorCallInCtor
8816           << /*IsObjCPtr*/false;
8817     }
8818 
8819     if (DiagKind == 1)
8820       S.NoteDeletedFunction(Decl);
8821     // FIXME: Explain inaccessibility if DiagKind == 3.
8822   }
8823 
8824   return true;
8825 }
8826 
8827 /// Check whether we should delete a special member function due to having a
8828 /// direct or virtual base class or non-static data member of class type M.
8829 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8830     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8831   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8832   bool IsMutable = Field && Field->isMutable();
8833 
8834   // C++11 [class.ctor]p5:
8835   // -- any direct or virtual base class, or non-static data member with no
8836   //    brace-or-equal-initializer, has class type M (or array thereof) and
8837   //    either M has no default constructor or overload resolution as applied
8838   //    to M's default constructor results in an ambiguity or in a function
8839   //    that is deleted or inaccessible
8840   // C++11 [class.copy]p11, C++11 [class.copy]p23:
8841   // -- a direct or virtual base class B that cannot be copied/moved because
8842   //    overload resolution, as applied to B's corresponding special member,
8843   //    results in an ambiguity or a function that is deleted or inaccessible
8844   //    from the defaulted special member
8845   // C++11 [class.dtor]p5:
8846   // -- any direct or virtual base class [...] has a type with a destructor
8847   //    that is deleted or inaccessible
8848   if (!(CSM == Sema::CXXDefaultConstructor &&
8849         Field && Field->hasInClassInitializer()) &&
8850       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8851                                    false))
8852     return true;
8853 
8854   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8855   // -- any direct or virtual base class or non-static data member has a
8856   //    type with a destructor that is deleted or inaccessible
8857   if (IsConstructor) {
8858     Sema::SpecialMemberOverloadResult SMOR =
8859         S.LookupSpecialMember(Class, Sema::CXXDestructor,
8860                               false, false, false, false, false);
8861     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8862       return true;
8863   }
8864 
8865   return false;
8866 }
8867 
8868 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8869     FieldDecl *FD, QualType FieldType) {
8870   // The defaulted special functions are defined as deleted if this is a variant
8871   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8872   // type under ARC.
8873   if (!FieldType.hasNonTrivialObjCLifetime())
8874     return false;
8875 
8876   // Don't make the defaulted default constructor defined as deleted if the
8877   // member has an in-class initializer.
8878   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8879     return false;
8880 
8881   if (Diagnose) {
8882     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8883     S.Diag(FD->getLocation(),
8884            diag::note_deleted_special_member_class_subobject)
8885         << getEffectiveCSM() << ParentClass << /*IsField*/true
8886         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8887   }
8888 
8889   return true;
8890 }
8891 
8892 /// Check whether we should delete a special member function due to the class
8893 /// having a particular direct or virtual base class.
8894 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8895   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8896   // If program is correct, BaseClass cannot be null, but if it is, the error
8897   // must be reported elsewhere.
8898   if (!BaseClass)
8899     return false;
8900   // If we have an inheriting constructor, check whether we're calling an
8901   // inherited constructor instead of a default constructor.
8902   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8903   if (auto *BaseCtor = SMOR.getMethod()) {
8904     // Note that we do not check access along this path; other than that,
8905     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8906     // FIXME: Check that the base has a usable destructor! Sink this into
8907     // shouldDeleteForClassSubobject.
8908     if (BaseCtor->isDeleted() && Diagnose) {
8909       S.Diag(Base->getBeginLoc(),
8910              diag::note_deleted_special_member_class_subobject)
8911           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8912           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8913           << /*IsObjCPtr*/false;
8914       S.NoteDeletedFunction(BaseCtor);
8915     }
8916     return BaseCtor->isDeleted();
8917   }
8918   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8919 }
8920 
8921 /// Check whether we should delete a special member function due to the class
8922 /// having a particular non-static data member.
8923 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8924   QualType FieldType = S.Context.getBaseElementType(FD->getType());
8925   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8926 
8927   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
8928     return true;
8929 
8930   if (CSM == Sema::CXXDefaultConstructor) {
8931     // For a default constructor, all references must be initialized in-class
8932     // and, if a union, it must have a non-const member.
8933     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
8934       if (Diagnose)
8935         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8936           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
8937       return true;
8938     }
8939     // C++11 [class.ctor]p5: any non-variant non-static data member of
8940     // const-qualified type (or array thereof) with no
8941     // brace-or-equal-initializer does not have a user-provided default
8942     // constructor.
8943     if (!inUnion() && FieldType.isConstQualified() &&
8944         !FD->hasInClassInitializer() &&
8945         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
8946       if (Diagnose)
8947         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8948           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
8949       return true;
8950     }
8951 
8952     if (inUnion() && !FieldType.isConstQualified())
8953       AllFieldsAreConst = false;
8954   } else if (CSM == Sema::CXXCopyConstructor) {
8955     // For a copy constructor, data members must not be of rvalue reference
8956     // type.
8957     if (FieldType->isRValueReferenceType()) {
8958       if (Diagnose)
8959         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
8960           << MD->getParent() << FD << FieldType;
8961       return true;
8962     }
8963   } else if (IsAssignment) {
8964     // For an assignment operator, data members must not be of reference type.
8965     if (FieldType->isReferenceType()) {
8966       if (Diagnose)
8967         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8968           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
8969       return true;
8970     }
8971     if (!FieldRecord && FieldType.isConstQualified()) {
8972       // C++11 [class.copy]p23:
8973       // -- a non-static data member of const non-class type (or array thereof)
8974       if (Diagnose)
8975         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8976           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
8977       return true;
8978     }
8979   }
8980 
8981   if (FieldRecord) {
8982     // Some additional restrictions exist on the variant members.
8983     if (!inUnion() && FieldRecord->isUnion() &&
8984         FieldRecord->isAnonymousStructOrUnion()) {
8985       bool AllVariantFieldsAreConst = true;
8986 
8987       // FIXME: Handle anonymous unions declared within anonymous unions.
8988       for (auto *UI : FieldRecord->fields()) {
8989         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
8990 
8991         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
8992           return true;
8993 
8994         if (!UnionFieldType.isConstQualified())
8995           AllVariantFieldsAreConst = false;
8996 
8997         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
8998         if (UnionFieldRecord &&
8999             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9000                                           UnionFieldType.getCVRQualifiers()))
9001           return true;
9002       }
9003 
9004       // At least one member in each anonymous union must be non-const
9005       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9006           !FieldRecord->field_empty()) {
9007         if (Diagnose)
9008           S.Diag(FieldRecord->getLocation(),
9009                  diag::note_deleted_default_ctor_all_const)
9010             << !!ICI << MD->getParent() << /*anonymous union*/1;
9011         return true;
9012       }
9013 
9014       // Don't check the implicit member of the anonymous union type.
9015       // This is technically non-conformant, but sanity demands it.
9016       return false;
9017     }
9018 
9019     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9020                                       FieldType.getCVRQualifiers()))
9021       return true;
9022   }
9023 
9024   return false;
9025 }
9026 
9027 /// C++11 [class.ctor] p5:
9028 ///   A defaulted default constructor for a class X is defined as deleted if
9029 /// X is a union and all of its variant members are of const-qualified type.
9030 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9031   // This is a silly definition, because it gives an empty union a deleted
9032   // default constructor. Don't do that.
9033   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9034     bool AnyFields = false;
9035     for (auto *F : MD->getParent()->fields())
9036       if ((AnyFields = !F->isUnnamedBitfield()))
9037         break;
9038     if (!AnyFields)
9039       return false;
9040     if (Diagnose)
9041       S.Diag(MD->getParent()->getLocation(),
9042              diag::note_deleted_default_ctor_all_const)
9043         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9044     return true;
9045   }
9046   return false;
9047 }
9048 
9049 /// Determine whether a defaulted special member function should be defined as
9050 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9051 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9052 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9053                                      InheritedConstructorInfo *ICI,
9054                                      bool Diagnose) {
9055   if (MD->isInvalidDecl())
9056     return false;
9057   CXXRecordDecl *RD = MD->getParent();
9058   assert(!RD->isDependentType() && "do deletion after instantiation");
9059   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9060     return false;
9061 
9062   // C++11 [expr.lambda.prim]p19:
9063   //   The closure type associated with a lambda-expression has a
9064   //   deleted (8.4.3) default constructor and a deleted copy
9065   //   assignment operator.
9066   // C++2a adds back these operators if the lambda has no lambda-capture.
9067   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9068       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9069     if (Diagnose)
9070       Diag(RD->getLocation(), diag::note_lambda_decl);
9071     return true;
9072   }
9073 
9074   // For an anonymous struct or union, the copy and assignment special members
9075   // will never be used, so skip the check. For an anonymous union declared at
9076   // namespace scope, the constructor and destructor are used.
9077   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9078       RD->isAnonymousStructOrUnion())
9079     return false;
9080 
9081   // C++11 [class.copy]p7, p18:
9082   //   If the class definition declares a move constructor or move assignment
9083   //   operator, an implicitly declared copy constructor or copy assignment
9084   //   operator is defined as deleted.
9085   if (MD->isImplicit() &&
9086       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9087     CXXMethodDecl *UserDeclaredMove = nullptr;
9088 
9089     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9090     // deletion of the corresponding copy operation, not both copy operations.
9091     // MSVC 2015 has adopted the standards conforming behavior.
9092     bool DeletesOnlyMatchingCopy =
9093         getLangOpts().MSVCCompat &&
9094         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9095 
9096     if (RD->hasUserDeclaredMoveConstructor() &&
9097         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9098       if (!Diagnose) return true;
9099 
9100       // Find any user-declared move constructor.
9101       for (auto *I : RD->ctors()) {
9102         if (I->isMoveConstructor()) {
9103           UserDeclaredMove = I;
9104           break;
9105         }
9106       }
9107       assert(UserDeclaredMove);
9108     } else if (RD->hasUserDeclaredMoveAssignment() &&
9109                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9110       if (!Diagnose) return true;
9111 
9112       // Find any user-declared move assignment operator.
9113       for (auto *I : RD->methods()) {
9114         if (I->isMoveAssignmentOperator()) {
9115           UserDeclaredMove = I;
9116           break;
9117         }
9118       }
9119       assert(UserDeclaredMove);
9120     }
9121 
9122     if (UserDeclaredMove) {
9123       Diag(UserDeclaredMove->getLocation(),
9124            diag::note_deleted_copy_user_declared_move)
9125         << (CSM == CXXCopyAssignment) << RD
9126         << UserDeclaredMove->isMoveAssignmentOperator();
9127       return true;
9128     }
9129   }
9130 
9131   // Do access control from the special member function
9132   ContextRAII MethodContext(*this, MD);
9133 
9134   // C++11 [class.dtor]p5:
9135   // -- for a virtual destructor, lookup of the non-array deallocation function
9136   //    results in an ambiguity or in a function that is deleted or inaccessible
9137   if (CSM == CXXDestructor && MD->isVirtual()) {
9138     FunctionDecl *OperatorDelete = nullptr;
9139     DeclarationName Name =
9140       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9141     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9142                                  OperatorDelete, /*Diagnose*/false)) {
9143       if (Diagnose)
9144         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9145       return true;
9146     }
9147   }
9148 
9149   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9150 
9151   // Per DR1611, do not consider virtual bases of constructors of abstract
9152   // classes, since we are not going to construct them.
9153   // Per DR1658, do not consider virtual bases of destructors of abstract
9154   // classes either.
9155   // Per DR2180, for assignment operators we only assign (and thus only
9156   // consider) direct bases.
9157   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9158                                  : SMI.VisitPotentiallyConstructedBases))
9159     return true;
9160 
9161   if (SMI.shouldDeleteForAllConstMembers())
9162     return true;
9163 
9164   if (getLangOpts().CUDA) {
9165     // We should delete the special member in CUDA mode if target inference
9166     // failed.
9167     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9168     // is treated as certain special member, which may not reflect what special
9169     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9170     // expects CSM to match MD, therefore recalculate CSM.
9171     assert(ICI || CSM == getSpecialMember(MD));
9172     auto RealCSM = CSM;
9173     if (ICI)
9174       RealCSM = getSpecialMember(MD);
9175 
9176     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9177                                                    SMI.ConstArg, Diagnose);
9178   }
9179 
9180   return false;
9181 }
9182 
9183 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9184   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9185   assert(DFK && "not a defaultable function");
9186   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9187 
9188   if (DFK.isSpecialMember()) {
9189     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9190                               nullptr, /*Diagnose=*/true);
9191   } else {
9192     DefaultedComparisonAnalyzer(
9193         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9194         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9195         .visit();
9196   }
9197 }
9198 
9199 /// Perform lookup for a special member of the specified kind, and determine
9200 /// whether it is trivial. If the triviality can be determined without the
9201 /// lookup, skip it. This is intended for use when determining whether a
9202 /// special member of a containing object is trivial, and thus does not ever
9203 /// perform overload resolution for default constructors.
9204 ///
9205 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9206 /// member that was most likely to be intended to be trivial, if any.
9207 ///
9208 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9209 /// determine whether the special member is trivial.
9210 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9211                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9212                                      bool ConstRHS,
9213                                      Sema::TrivialABIHandling TAH,
9214                                      CXXMethodDecl **Selected) {
9215   if (Selected)
9216     *Selected = nullptr;
9217 
9218   switch (CSM) {
9219   case Sema::CXXInvalid:
9220     llvm_unreachable("not a special member");
9221 
9222   case Sema::CXXDefaultConstructor:
9223     // C++11 [class.ctor]p5:
9224     //   A default constructor is trivial if:
9225     //    - all the [direct subobjects] have trivial default constructors
9226     //
9227     // Note, no overload resolution is performed in this case.
9228     if (RD->hasTrivialDefaultConstructor())
9229       return true;
9230 
9231     if (Selected) {
9232       // If there's a default constructor which could have been trivial, dig it
9233       // out. Otherwise, if there's any user-provided default constructor, point
9234       // to that as an example of why there's not a trivial one.
9235       CXXConstructorDecl *DefCtor = nullptr;
9236       if (RD->needsImplicitDefaultConstructor())
9237         S.DeclareImplicitDefaultConstructor(RD);
9238       for (auto *CI : RD->ctors()) {
9239         if (!CI->isDefaultConstructor())
9240           continue;
9241         DefCtor = CI;
9242         if (!DefCtor->isUserProvided())
9243           break;
9244       }
9245 
9246       *Selected = DefCtor;
9247     }
9248 
9249     return false;
9250 
9251   case Sema::CXXDestructor:
9252     // C++11 [class.dtor]p5:
9253     //   A destructor is trivial if:
9254     //    - all the direct [subobjects] have trivial destructors
9255     if (RD->hasTrivialDestructor() ||
9256         (TAH == Sema::TAH_ConsiderTrivialABI &&
9257          RD->hasTrivialDestructorForCall()))
9258       return true;
9259 
9260     if (Selected) {
9261       if (RD->needsImplicitDestructor())
9262         S.DeclareImplicitDestructor(RD);
9263       *Selected = RD->getDestructor();
9264     }
9265 
9266     return false;
9267 
9268   case Sema::CXXCopyConstructor:
9269     // C++11 [class.copy]p12:
9270     //   A copy constructor is trivial if:
9271     //    - the constructor selected to copy each direct [subobject] is trivial
9272     if (RD->hasTrivialCopyConstructor() ||
9273         (TAH == Sema::TAH_ConsiderTrivialABI &&
9274          RD->hasTrivialCopyConstructorForCall())) {
9275       if (Quals == Qualifiers::Const)
9276         // We must either select the trivial copy constructor or reach an
9277         // ambiguity; no need to actually perform overload resolution.
9278         return true;
9279     } else if (!Selected) {
9280       return false;
9281     }
9282     // In C++98, we are not supposed to perform overload resolution here, but we
9283     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9284     // cases like B as having a non-trivial copy constructor:
9285     //   struct A { template<typename T> A(T&); };
9286     //   struct B { mutable A a; };
9287     goto NeedOverloadResolution;
9288 
9289   case Sema::CXXCopyAssignment:
9290     // C++11 [class.copy]p25:
9291     //   A copy assignment operator is trivial if:
9292     //    - the assignment operator selected to copy each direct [subobject] is
9293     //      trivial
9294     if (RD->hasTrivialCopyAssignment()) {
9295       if (Quals == Qualifiers::Const)
9296         return true;
9297     } else if (!Selected) {
9298       return false;
9299     }
9300     // In C++98, we are not supposed to perform overload resolution here, but we
9301     // treat that as a language defect.
9302     goto NeedOverloadResolution;
9303 
9304   case Sema::CXXMoveConstructor:
9305   case Sema::CXXMoveAssignment:
9306   NeedOverloadResolution:
9307     Sema::SpecialMemberOverloadResult SMOR =
9308         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9309 
9310     // The standard doesn't describe how to behave if the lookup is ambiguous.
9311     // We treat it as not making the member non-trivial, just like the standard
9312     // mandates for the default constructor. This should rarely matter, because
9313     // the member will also be deleted.
9314     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9315       return true;
9316 
9317     if (!SMOR.getMethod()) {
9318       assert(SMOR.getKind() ==
9319              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9320       return false;
9321     }
9322 
9323     // We deliberately don't check if we found a deleted special member. We're
9324     // not supposed to!
9325     if (Selected)
9326       *Selected = SMOR.getMethod();
9327 
9328     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9329         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9330       return SMOR.getMethod()->isTrivialForCall();
9331     return SMOR.getMethod()->isTrivial();
9332   }
9333 
9334   llvm_unreachable("unknown special method kind");
9335 }
9336 
9337 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9338   for (auto *CI : RD->ctors())
9339     if (!CI->isImplicit())
9340       return CI;
9341 
9342   // Look for constructor templates.
9343   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9344   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9345     if (CXXConstructorDecl *CD =
9346           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9347       return CD;
9348   }
9349 
9350   return nullptr;
9351 }
9352 
9353 /// The kind of subobject we are checking for triviality. The values of this
9354 /// enumeration are used in diagnostics.
9355 enum TrivialSubobjectKind {
9356   /// The subobject is a base class.
9357   TSK_BaseClass,
9358   /// The subobject is a non-static data member.
9359   TSK_Field,
9360   /// The object is actually the complete object.
9361   TSK_CompleteObject
9362 };
9363 
9364 /// Check whether the special member selected for a given type would be trivial.
9365 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9366                                       QualType SubType, bool ConstRHS,
9367                                       Sema::CXXSpecialMember CSM,
9368                                       TrivialSubobjectKind Kind,
9369                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9370   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9371   if (!SubRD)
9372     return true;
9373 
9374   CXXMethodDecl *Selected;
9375   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9376                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9377     return true;
9378 
9379   if (Diagnose) {
9380     if (ConstRHS)
9381       SubType.addConst();
9382 
9383     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9384       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9385         << Kind << SubType.getUnqualifiedType();
9386       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9387         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9388     } else if (!Selected)
9389       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9390         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9391     else if (Selected->isUserProvided()) {
9392       if (Kind == TSK_CompleteObject)
9393         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9394           << Kind << SubType.getUnqualifiedType() << CSM;
9395       else {
9396         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9397           << Kind << SubType.getUnqualifiedType() << CSM;
9398         S.Diag(Selected->getLocation(), diag::note_declared_at);
9399       }
9400     } else {
9401       if (Kind != TSK_CompleteObject)
9402         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9403           << Kind << SubType.getUnqualifiedType() << CSM;
9404 
9405       // Explain why the defaulted or deleted special member isn't trivial.
9406       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9407                                Diagnose);
9408     }
9409   }
9410 
9411   return false;
9412 }
9413 
9414 /// Check whether the members of a class type allow a special member to be
9415 /// trivial.
9416 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9417                                      Sema::CXXSpecialMember CSM,
9418                                      bool ConstArg,
9419                                      Sema::TrivialABIHandling TAH,
9420                                      bool Diagnose) {
9421   for (const auto *FI : RD->fields()) {
9422     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9423       continue;
9424 
9425     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9426 
9427     // Pretend anonymous struct or union members are members of this class.
9428     if (FI->isAnonymousStructOrUnion()) {
9429       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9430                                     CSM, ConstArg, TAH, Diagnose))
9431         return false;
9432       continue;
9433     }
9434 
9435     // C++11 [class.ctor]p5:
9436     //   A default constructor is trivial if [...]
9437     //    -- no non-static data member of its class has a
9438     //       brace-or-equal-initializer
9439     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9440       if (Diagnose)
9441         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9442             << FI;
9443       return false;
9444     }
9445 
9446     // Objective C ARC 4.3.5:
9447     //   [...] nontrivally ownership-qualified types are [...] not trivially
9448     //   default constructible, copy constructible, move constructible, copy
9449     //   assignable, move assignable, or destructible [...]
9450     if (FieldType.hasNonTrivialObjCLifetime()) {
9451       if (Diagnose)
9452         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9453           << RD << FieldType.getObjCLifetime();
9454       return false;
9455     }
9456 
9457     bool ConstRHS = ConstArg && !FI->isMutable();
9458     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9459                                    CSM, TSK_Field, TAH, Diagnose))
9460       return false;
9461   }
9462 
9463   return true;
9464 }
9465 
9466 /// Diagnose why the specified class does not have a trivial special member of
9467 /// the given kind.
9468 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9469   QualType Ty = Context.getRecordType(RD);
9470 
9471   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9472   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9473                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9474                             /*Diagnose*/true);
9475 }
9476 
9477 /// Determine whether a defaulted or deleted special member function is trivial,
9478 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9479 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9480 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9481                                   TrivialABIHandling TAH, bool Diagnose) {
9482   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9483 
9484   CXXRecordDecl *RD = MD->getParent();
9485 
9486   bool ConstArg = false;
9487 
9488   // C++11 [class.copy]p12, p25: [DR1593]
9489   //   A [special member] is trivial if [...] its parameter-type-list is
9490   //   equivalent to the parameter-type-list of an implicit declaration [...]
9491   switch (CSM) {
9492   case CXXDefaultConstructor:
9493   case CXXDestructor:
9494     // Trivial default constructors and destructors cannot have parameters.
9495     break;
9496 
9497   case CXXCopyConstructor:
9498   case CXXCopyAssignment: {
9499     // Trivial copy operations always have const, non-volatile parameter types.
9500     ConstArg = true;
9501     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9502     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9503     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9504       if (Diagnose)
9505         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9506           << Param0->getSourceRange() << Param0->getType()
9507           << Context.getLValueReferenceType(
9508                Context.getRecordType(RD).withConst());
9509       return false;
9510     }
9511     break;
9512   }
9513 
9514   case CXXMoveConstructor:
9515   case CXXMoveAssignment: {
9516     // Trivial move operations always have non-cv-qualified parameters.
9517     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9518     const RValueReferenceType *RT =
9519       Param0->getType()->getAs<RValueReferenceType>();
9520     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9521       if (Diagnose)
9522         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9523           << Param0->getSourceRange() << Param0->getType()
9524           << Context.getRValueReferenceType(Context.getRecordType(RD));
9525       return false;
9526     }
9527     break;
9528   }
9529 
9530   case CXXInvalid:
9531     llvm_unreachable("not a special member");
9532   }
9533 
9534   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9535     if (Diagnose)
9536       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9537            diag::note_nontrivial_default_arg)
9538         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9539     return false;
9540   }
9541   if (MD->isVariadic()) {
9542     if (Diagnose)
9543       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9544     return false;
9545   }
9546 
9547   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9548   //   A copy/move [constructor or assignment operator] is trivial if
9549   //    -- the [member] selected to copy/move each direct base class subobject
9550   //       is trivial
9551   //
9552   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9553   //   A [default constructor or destructor] is trivial if
9554   //    -- all the direct base classes have trivial [default constructors or
9555   //       destructors]
9556   for (const auto &BI : RD->bases())
9557     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9558                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9559       return false;
9560 
9561   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9562   //   A copy/move [constructor or assignment operator] for a class X is
9563   //   trivial if
9564   //    -- for each non-static data member of X that is of class type (or array
9565   //       thereof), the constructor selected to copy/move that member is
9566   //       trivial
9567   //
9568   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9569   //   A [default constructor or destructor] is trivial if
9570   //    -- for all of the non-static data members of its class that are of class
9571   //       type (or array thereof), each such class has a trivial [default
9572   //       constructor or destructor]
9573   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9574     return false;
9575 
9576   // C++11 [class.dtor]p5:
9577   //   A destructor is trivial if [...]
9578   //    -- the destructor is not virtual
9579   if (CSM == CXXDestructor && MD->isVirtual()) {
9580     if (Diagnose)
9581       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9582     return false;
9583   }
9584 
9585   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9586   //   A [special member] for class X is trivial if [...]
9587   //    -- class X has no virtual functions and no virtual base classes
9588   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9589     if (!Diagnose)
9590       return false;
9591 
9592     if (RD->getNumVBases()) {
9593       // Check for virtual bases. We already know that the corresponding
9594       // member in all bases is trivial, so vbases must all be direct.
9595       CXXBaseSpecifier &BS = *RD->vbases_begin();
9596       assert(BS.isVirtual());
9597       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9598       return false;
9599     }
9600 
9601     // Must have a virtual method.
9602     for (const auto *MI : RD->methods()) {
9603       if (MI->isVirtual()) {
9604         SourceLocation MLoc = MI->getBeginLoc();
9605         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9606         return false;
9607       }
9608     }
9609 
9610     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9611   }
9612 
9613   // Looks like it's trivial!
9614   return true;
9615 }
9616 
9617 namespace {
9618 struct FindHiddenVirtualMethod {
9619   Sema *S;
9620   CXXMethodDecl *Method;
9621   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9622   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9623 
9624 private:
9625   /// Check whether any most overridden method from MD in Methods
9626   static bool CheckMostOverridenMethods(
9627       const CXXMethodDecl *MD,
9628       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9629     if (MD->size_overridden_methods() == 0)
9630       return Methods.count(MD->getCanonicalDecl());
9631     for (const CXXMethodDecl *O : MD->overridden_methods())
9632       if (CheckMostOverridenMethods(O, Methods))
9633         return true;
9634     return false;
9635   }
9636 
9637 public:
9638   /// Member lookup function that determines whether a given C++
9639   /// method overloads virtual methods in a base class without overriding any,
9640   /// to be used with CXXRecordDecl::lookupInBases().
9641   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9642     RecordDecl *BaseRecord =
9643         Specifier->getType()->castAs<RecordType>()->getDecl();
9644 
9645     DeclarationName Name = Method->getDeclName();
9646     assert(Name.getNameKind() == DeclarationName::Identifier);
9647 
9648     bool foundSameNameMethod = false;
9649     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9650     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
9651          Path.Decls = Path.Decls.slice(1)) {
9652       NamedDecl *D = Path.Decls.front();
9653       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9654         MD = MD->getCanonicalDecl();
9655         foundSameNameMethod = true;
9656         // Interested only in hidden virtual methods.
9657         if (!MD->isVirtual())
9658           continue;
9659         // If the method we are checking overrides a method from its base
9660         // don't warn about the other overloaded methods. Clang deviates from
9661         // GCC by only diagnosing overloads of inherited virtual functions that
9662         // do not override any other virtual functions in the base. GCC's
9663         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9664         // function from a base class. These cases may be better served by a
9665         // warning (not specific to virtual functions) on call sites when the
9666         // call would select a different function from the base class, were it
9667         // visible.
9668         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9669         if (!S->IsOverload(Method, MD, false))
9670           return true;
9671         // Collect the overload only if its hidden.
9672         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9673           overloadedMethods.push_back(MD);
9674       }
9675     }
9676 
9677     if (foundSameNameMethod)
9678       OverloadedMethods.append(overloadedMethods.begin(),
9679                                overloadedMethods.end());
9680     return foundSameNameMethod;
9681   }
9682 };
9683 } // end anonymous namespace
9684 
9685 /// Add the most overriden methods from MD to Methods
9686 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9687                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9688   if (MD->size_overridden_methods() == 0)
9689     Methods.insert(MD->getCanonicalDecl());
9690   else
9691     for (const CXXMethodDecl *O : MD->overridden_methods())
9692       AddMostOverridenMethods(O, Methods);
9693 }
9694 
9695 /// Check if a method overloads virtual methods in a base class without
9696 /// overriding any.
9697 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9698                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9699   if (!MD->getDeclName().isIdentifier())
9700     return;
9701 
9702   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9703                      /*bool RecordPaths=*/false,
9704                      /*bool DetectVirtual=*/false);
9705   FindHiddenVirtualMethod FHVM;
9706   FHVM.Method = MD;
9707   FHVM.S = this;
9708 
9709   // Keep the base methods that were overridden or introduced in the subclass
9710   // by 'using' in a set. A base method not in this set is hidden.
9711   CXXRecordDecl *DC = MD->getParent();
9712   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9713   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9714     NamedDecl *ND = *I;
9715     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9716       ND = shad->getTargetDecl();
9717     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9718       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9719   }
9720 
9721   if (DC->lookupInBases(FHVM, Paths))
9722     OverloadedMethods = FHVM.OverloadedMethods;
9723 }
9724 
9725 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9726                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9727   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9728     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9729     PartialDiagnostic PD = PDiag(
9730          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9731     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9732     Diag(overloadedMD->getLocation(), PD);
9733   }
9734 }
9735 
9736 /// Diagnose methods which overload virtual methods in a base class
9737 /// without overriding any.
9738 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9739   if (MD->isInvalidDecl())
9740     return;
9741 
9742   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9743     return;
9744 
9745   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9746   FindHiddenVirtualMethods(MD, OverloadedMethods);
9747   if (!OverloadedMethods.empty()) {
9748     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9749       << MD << (OverloadedMethods.size() > 1);
9750 
9751     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9752   }
9753 }
9754 
9755 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9756   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9757     // No diagnostics if this is a template instantiation.
9758     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9759       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9760            diag::ext_cannot_use_trivial_abi) << &RD;
9761       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9762            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9763     }
9764     RD.dropAttr<TrivialABIAttr>();
9765   };
9766 
9767   // Ill-formed if the copy and move constructors are deleted.
9768   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9769     // If the type is dependent, then assume it might have
9770     // implicit copy or move ctor because we won't know yet at this point.
9771     if (RD.isDependentType())
9772       return true;
9773     if (RD.needsImplicitCopyConstructor() &&
9774         !RD.defaultedCopyConstructorIsDeleted())
9775       return true;
9776     if (RD.needsImplicitMoveConstructor() &&
9777         !RD.defaultedMoveConstructorIsDeleted())
9778       return true;
9779     for (const CXXConstructorDecl *CD : RD.ctors())
9780       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9781         return true;
9782     return false;
9783   };
9784 
9785   if (!HasNonDeletedCopyOrMoveConstructor()) {
9786     PrintDiagAndRemoveAttr(0);
9787     return;
9788   }
9789 
9790   // Ill-formed if the struct has virtual functions.
9791   if (RD.isPolymorphic()) {
9792     PrintDiagAndRemoveAttr(1);
9793     return;
9794   }
9795 
9796   for (const auto &B : RD.bases()) {
9797     // Ill-formed if the base class is non-trivial for the purpose of calls or a
9798     // virtual base.
9799     if (!B.getType()->isDependentType() &&
9800         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9801       PrintDiagAndRemoveAttr(2);
9802       return;
9803     }
9804 
9805     if (B.isVirtual()) {
9806       PrintDiagAndRemoveAttr(3);
9807       return;
9808     }
9809   }
9810 
9811   for (const auto *FD : RD.fields()) {
9812     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9813     // non-trivial for the purpose of calls.
9814     QualType FT = FD->getType();
9815     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9816       PrintDiagAndRemoveAttr(4);
9817       return;
9818     }
9819 
9820     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9821       if (!RT->isDependentType() &&
9822           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9823         PrintDiagAndRemoveAttr(5);
9824         return;
9825       }
9826   }
9827 }
9828 
9829 void Sema::ActOnFinishCXXMemberSpecification(
9830     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9831     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9832   if (!TagDecl)
9833     return;
9834 
9835   AdjustDeclIfTemplate(TagDecl);
9836 
9837   for (const ParsedAttr &AL : AttrList) {
9838     if (AL.getKind() != ParsedAttr::AT_Visibility)
9839       continue;
9840     AL.setInvalid();
9841     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9842   }
9843 
9844   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9845               // strict aliasing violation!
9846               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9847               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9848 
9849   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9850 }
9851 
9852 /// Find the equality comparison functions that should be implicitly declared
9853 /// in a given class definition, per C++2a [class.compare.default]p3.
9854 static void findImplicitlyDeclaredEqualityComparisons(
9855     ASTContext &Ctx, CXXRecordDecl *RD,
9856     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9857   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9858   if (!RD->lookup(EqEq).empty())
9859     // Member operator== explicitly declared: no implicit operator==s.
9860     return;
9861 
9862   // Traverse friends looking for an '==' or a '<=>'.
9863   for (FriendDecl *Friend : RD->friends()) {
9864     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9865     if (!FD) continue;
9866 
9867     if (FD->getOverloadedOperator() == OO_EqualEqual) {
9868       // Friend operator== explicitly declared: no implicit operator==s.
9869       Spaceships.clear();
9870       return;
9871     }
9872 
9873     if (FD->getOverloadedOperator() == OO_Spaceship &&
9874         FD->isExplicitlyDefaulted())
9875       Spaceships.push_back(FD);
9876   }
9877 
9878   // Look for members named 'operator<=>'.
9879   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9880   for (NamedDecl *ND : RD->lookup(Cmp)) {
9881     // Note that we could find a non-function here (either a function template
9882     // or a using-declaration). Neither case results in an implicit
9883     // 'operator=='.
9884     if (auto *FD = dyn_cast<FunctionDecl>(ND))
9885       if (FD->isExplicitlyDefaulted())
9886         Spaceships.push_back(FD);
9887   }
9888 }
9889 
9890 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9891 /// special functions, such as the default constructor, copy
9892 /// constructor, or destructor, to the given C++ class (C++
9893 /// [special]p1).  This routine can only be executed just before the
9894 /// definition of the class is complete.
9895 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9896   // Don't add implicit special members to templated classes.
9897   // FIXME: This means unqualified lookups for 'operator=' within a class
9898   // template don't work properly.
9899   if (!ClassDecl->isDependentType()) {
9900     if (ClassDecl->needsImplicitDefaultConstructor()) {
9901       ++getASTContext().NumImplicitDefaultConstructors;
9902 
9903       if (ClassDecl->hasInheritedConstructor())
9904         DeclareImplicitDefaultConstructor(ClassDecl);
9905     }
9906 
9907     if (ClassDecl->needsImplicitCopyConstructor()) {
9908       ++getASTContext().NumImplicitCopyConstructors;
9909 
9910       // If the properties or semantics of the copy constructor couldn't be
9911       // determined while the class was being declared, force a declaration
9912       // of it now.
9913       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9914           ClassDecl->hasInheritedConstructor())
9915         DeclareImplicitCopyConstructor(ClassDecl);
9916       // For the MS ABI we need to know whether the copy ctor is deleted. A
9917       // prerequisite for deleting the implicit copy ctor is that the class has
9918       // a move ctor or move assignment that is either user-declared or whose
9919       // semantics are inherited from a subobject. FIXME: We should provide a
9920       // more direct way for CodeGen to ask whether the constructor was deleted.
9921       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9922                (ClassDecl->hasUserDeclaredMoveConstructor() ||
9923                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9924                 ClassDecl->hasUserDeclaredMoveAssignment() ||
9925                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
9926         DeclareImplicitCopyConstructor(ClassDecl);
9927     }
9928 
9929     if (getLangOpts().CPlusPlus11 &&
9930         ClassDecl->needsImplicitMoveConstructor()) {
9931       ++getASTContext().NumImplicitMoveConstructors;
9932 
9933       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9934           ClassDecl->hasInheritedConstructor())
9935         DeclareImplicitMoveConstructor(ClassDecl);
9936     }
9937 
9938     if (ClassDecl->needsImplicitCopyAssignment()) {
9939       ++getASTContext().NumImplicitCopyAssignmentOperators;
9940 
9941       // If we have a dynamic class, then the copy assignment operator may be
9942       // virtual, so we have to declare it immediately. This ensures that, e.g.,
9943       // it shows up in the right place in the vtable and that we diagnose
9944       // problems with the implicit exception specification.
9945       if (ClassDecl->isDynamicClass() ||
9946           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9947           ClassDecl->hasInheritedAssignment())
9948         DeclareImplicitCopyAssignment(ClassDecl);
9949     }
9950 
9951     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9952       ++getASTContext().NumImplicitMoveAssignmentOperators;
9953 
9954       // Likewise for the move assignment operator.
9955       if (ClassDecl->isDynamicClass() ||
9956           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9957           ClassDecl->hasInheritedAssignment())
9958         DeclareImplicitMoveAssignment(ClassDecl);
9959     }
9960 
9961     if (ClassDecl->needsImplicitDestructor()) {
9962       ++getASTContext().NumImplicitDestructors;
9963 
9964       // If we have a dynamic class, then the destructor may be virtual, so we
9965       // have to declare the destructor immediately. This ensures that, e.g., it
9966       // shows up in the right place in the vtable and that we diagnose problems
9967       // with the implicit exception specification.
9968       if (ClassDecl->isDynamicClass() ||
9969           ClassDecl->needsOverloadResolutionForDestructor())
9970         DeclareImplicitDestructor(ClassDecl);
9971     }
9972   }
9973 
9974   // C++2a [class.compare.default]p3:
9975   //   If the member-specification does not explicitly declare any member or
9976   //   friend named operator==, an == operator function is declared implicitly
9977   //   for each defaulted three-way comparison operator function defined in
9978   //   the member-specification
9979   // FIXME: Consider doing this lazily.
9980   // We do this during the initial parse for a class template, not during
9981   // instantiation, so that we can handle unqualified lookups for 'operator=='
9982   // when parsing the template.
9983   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
9984     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
9985     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
9986                                               DefaultedSpaceships);
9987     for (auto *FD : DefaultedSpaceships)
9988       DeclareImplicitEqualityComparison(ClassDecl, FD);
9989   }
9990 }
9991 
9992 unsigned
9993 Sema::ActOnReenterTemplateScope(Decl *D,
9994                                 llvm::function_ref<Scope *()> EnterScope) {
9995   if (!D)
9996     return 0;
9997   AdjustDeclIfTemplate(D);
9998 
9999   // In order to get name lookup right, reenter template scopes in order from
10000   // outermost to innermost.
10001   SmallVector<TemplateParameterList *, 4> ParameterLists;
10002   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10003 
10004   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10005     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10006       ParameterLists.push_back(DD->getTemplateParameterList(i));
10007 
10008     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10009       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10010         ParameterLists.push_back(FTD->getTemplateParameters());
10011     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10012       LookupDC = VD->getDeclContext();
10013 
10014       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10015         ParameterLists.push_back(VTD->getTemplateParameters());
10016       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10017         ParameterLists.push_back(PSD->getTemplateParameters());
10018     }
10019   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10020     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10021       ParameterLists.push_back(TD->getTemplateParameterList(i));
10022 
10023     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10024       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10025         ParameterLists.push_back(CTD->getTemplateParameters());
10026       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10027         ParameterLists.push_back(PSD->getTemplateParameters());
10028     }
10029   }
10030   // FIXME: Alias declarations and concepts.
10031 
10032   unsigned Count = 0;
10033   Scope *InnermostTemplateScope = nullptr;
10034   for (TemplateParameterList *Params : ParameterLists) {
10035     // Ignore explicit specializations; they don't contribute to the template
10036     // depth.
10037     if (Params->size() == 0)
10038       continue;
10039 
10040     InnermostTemplateScope = EnterScope();
10041     for (NamedDecl *Param : *Params) {
10042       if (Param->getDeclName()) {
10043         InnermostTemplateScope->AddDecl(Param);
10044         IdResolver.AddDecl(Param);
10045       }
10046     }
10047     ++Count;
10048   }
10049 
10050   // Associate the new template scopes with the corresponding entities.
10051   if (InnermostTemplateScope) {
10052     assert(LookupDC && "no enclosing DeclContext for template lookup");
10053     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10054   }
10055 
10056   return Count;
10057 }
10058 
10059 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10060   if (!RecordD) return;
10061   AdjustDeclIfTemplate(RecordD);
10062   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10063   PushDeclContext(S, Record);
10064 }
10065 
10066 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10067   if (!RecordD) return;
10068   PopDeclContext();
10069 }
10070 
10071 /// This is used to implement the constant expression evaluation part of the
10072 /// attribute enable_if extension. There is nothing in standard C++ which would
10073 /// require reentering parameters.
10074 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10075   if (!Param)
10076     return;
10077 
10078   S->AddDecl(Param);
10079   if (Param->getDeclName())
10080     IdResolver.AddDecl(Param);
10081 }
10082 
10083 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10084 /// parsing a top-level (non-nested) C++ class, and we are now
10085 /// parsing those parts of the given Method declaration that could
10086 /// not be parsed earlier (C++ [class.mem]p2), such as default
10087 /// arguments. This action should enter the scope of the given
10088 /// Method declaration as if we had just parsed the qualified method
10089 /// name. However, it should not bring the parameters into scope;
10090 /// that will be performed by ActOnDelayedCXXMethodParameter.
10091 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10092 }
10093 
10094 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10095 /// C++ method declaration. We're (re-)introducing the given
10096 /// function parameter into scope for use in parsing later parts of
10097 /// the method declaration. For example, we could see an
10098 /// ActOnParamDefaultArgument event for this parameter.
10099 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10100   if (!ParamD)
10101     return;
10102 
10103   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10104 
10105   S->AddDecl(Param);
10106   if (Param->getDeclName())
10107     IdResolver.AddDecl(Param);
10108 }
10109 
10110 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10111 /// processing the delayed method declaration for Method. The method
10112 /// declaration is now considered finished. There may be a separate
10113 /// ActOnStartOfFunctionDef action later (not necessarily
10114 /// immediately!) for this method, if it was also defined inside the
10115 /// class body.
10116 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10117   if (!MethodD)
10118     return;
10119 
10120   AdjustDeclIfTemplate(MethodD);
10121 
10122   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10123 
10124   // Now that we have our default arguments, check the constructor
10125   // again. It could produce additional diagnostics or affect whether
10126   // the class has implicitly-declared destructors, among other
10127   // things.
10128   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10129     CheckConstructor(Constructor);
10130 
10131   // Check the default arguments, which we may have added.
10132   if (!Method->isInvalidDecl())
10133     CheckCXXDefaultArguments(Method);
10134 }
10135 
10136 // Emit the given diagnostic for each non-address-space qualifier.
10137 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10138 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10139   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10140   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10141     bool DiagOccured = false;
10142     FTI.MethodQualifiers->forEachQualifier(
10143         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10144                                    SourceLocation SL) {
10145           // This diagnostic should be emitted on any qualifier except an addr
10146           // space qualifier. However, forEachQualifier currently doesn't visit
10147           // addr space qualifiers, so there's no way to write this condition
10148           // right now; we just diagnose on everything.
10149           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10150           DiagOccured = true;
10151         });
10152     if (DiagOccured)
10153       D.setInvalidType();
10154   }
10155 }
10156 
10157 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10158 /// the well-formedness of the constructor declarator @p D with type @p
10159 /// R. If there are any errors in the declarator, this routine will
10160 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10161 /// will be updated to reflect a well-formed type for the constructor and
10162 /// returned.
10163 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10164                                           StorageClass &SC) {
10165   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10166 
10167   // C++ [class.ctor]p3:
10168   //   A constructor shall not be virtual (10.3) or static (9.4). A
10169   //   constructor can be invoked for a const, volatile or const
10170   //   volatile object. A constructor shall not be declared const,
10171   //   volatile, or const volatile (9.3.2).
10172   if (isVirtual) {
10173     if (!D.isInvalidType())
10174       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10175         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10176         << SourceRange(D.getIdentifierLoc());
10177     D.setInvalidType();
10178   }
10179   if (SC == SC_Static) {
10180     if (!D.isInvalidType())
10181       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10182         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10183         << SourceRange(D.getIdentifierLoc());
10184     D.setInvalidType();
10185     SC = SC_None;
10186   }
10187 
10188   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10189     diagnoseIgnoredQualifiers(
10190         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10191         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10192         D.getDeclSpec().getRestrictSpecLoc(),
10193         D.getDeclSpec().getAtomicSpecLoc());
10194     D.setInvalidType();
10195   }
10196 
10197   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10198 
10199   // C++0x [class.ctor]p4:
10200   //   A constructor shall not be declared with a ref-qualifier.
10201   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10202   if (FTI.hasRefQualifier()) {
10203     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10204       << FTI.RefQualifierIsLValueRef
10205       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10206     D.setInvalidType();
10207   }
10208 
10209   // Rebuild the function type "R" without any type qualifiers (in
10210   // case any of the errors above fired) and with "void" as the
10211   // return type, since constructors don't have return types.
10212   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10213   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10214     return R;
10215 
10216   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10217   EPI.TypeQuals = Qualifiers();
10218   EPI.RefQualifier = RQ_None;
10219 
10220   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10221 }
10222 
10223 /// CheckConstructor - Checks a fully-formed constructor for
10224 /// well-formedness, issuing any diagnostics required. Returns true if
10225 /// the constructor declarator is invalid.
10226 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10227   CXXRecordDecl *ClassDecl
10228     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10229   if (!ClassDecl)
10230     return Constructor->setInvalidDecl();
10231 
10232   // C++ [class.copy]p3:
10233   //   A declaration of a constructor for a class X is ill-formed if
10234   //   its first parameter is of type (optionally cv-qualified) X and
10235   //   either there are no other parameters or else all other
10236   //   parameters have default arguments.
10237   if (!Constructor->isInvalidDecl() &&
10238       Constructor->hasOneParamOrDefaultArgs() &&
10239       Constructor->getTemplateSpecializationKind() !=
10240           TSK_ImplicitInstantiation) {
10241     QualType ParamType = Constructor->getParamDecl(0)->getType();
10242     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10243     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10244       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10245       const char *ConstRef
10246         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10247                                                         : " const &";
10248       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10249         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10250 
10251       // FIXME: Rather that making the constructor invalid, we should endeavor
10252       // to fix the type.
10253       Constructor->setInvalidDecl();
10254     }
10255   }
10256 }
10257 
10258 /// CheckDestructor - Checks a fully-formed destructor definition for
10259 /// well-formedness, issuing any diagnostics required.  Returns true
10260 /// on error.
10261 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10262   CXXRecordDecl *RD = Destructor->getParent();
10263 
10264   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10265     SourceLocation Loc;
10266 
10267     if (!Destructor->isImplicit())
10268       Loc = Destructor->getLocation();
10269     else
10270       Loc = RD->getLocation();
10271 
10272     // If we have a virtual destructor, look up the deallocation function
10273     if (FunctionDecl *OperatorDelete =
10274             FindDeallocationFunctionForDestructor(Loc, RD)) {
10275       Expr *ThisArg = nullptr;
10276 
10277       // If the notional 'delete this' expression requires a non-trivial
10278       // conversion from 'this' to the type of a destroying operator delete's
10279       // first parameter, perform that conversion now.
10280       if (OperatorDelete->isDestroyingOperatorDelete()) {
10281         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10282         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10283           // C++ [class.dtor]p13:
10284           //   ... as if for the expression 'delete this' appearing in a
10285           //   non-virtual destructor of the destructor's class.
10286           ContextRAII SwitchContext(*this, Destructor);
10287           ExprResult This =
10288               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10289           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10290           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10291           if (This.isInvalid()) {
10292             // FIXME: Register this as a context note so that it comes out
10293             // in the right order.
10294             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10295             return true;
10296           }
10297           ThisArg = This.get();
10298         }
10299       }
10300 
10301       DiagnoseUseOfDecl(OperatorDelete, Loc);
10302       MarkFunctionReferenced(Loc, OperatorDelete);
10303       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10304     }
10305   }
10306 
10307   return false;
10308 }
10309 
10310 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10311 /// the well-formednes of the destructor declarator @p D with type @p
10312 /// R. If there are any errors in the declarator, this routine will
10313 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10314 /// will be updated to reflect a well-formed type for the destructor and
10315 /// returned.
10316 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10317                                          StorageClass& SC) {
10318   // C++ [class.dtor]p1:
10319   //   [...] A typedef-name that names a class is a class-name
10320   //   (7.1.3); however, a typedef-name that names a class shall not
10321   //   be used as the identifier in the declarator for a destructor
10322   //   declaration.
10323   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10324   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10325     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10326       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10327   else if (const TemplateSpecializationType *TST =
10328              DeclaratorType->getAs<TemplateSpecializationType>())
10329     if (TST->isTypeAlias())
10330       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10331         << DeclaratorType << 1;
10332 
10333   // C++ [class.dtor]p2:
10334   //   A destructor is used to destroy objects of its class type. A
10335   //   destructor takes no parameters, and no return type can be
10336   //   specified for it (not even void). The address of a destructor
10337   //   shall not be taken. A destructor shall not be static. A
10338   //   destructor can be invoked for a const, volatile or const
10339   //   volatile object. A destructor shall not be declared const,
10340   //   volatile or const volatile (9.3.2).
10341   if (SC == SC_Static) {
10342     if (!D.isInvalidType())
10343       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10344         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10345         << SourceRange(D.getIdentifierLoc())
10346         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10347 
10348     SC = SC_None;
10349   }
10350   if (!D.isInvalidType()) {
10351     // Destructors don't have return types, but the parser will
10352     // happily parse something like:
10353     //
10354     //   class X {
10355     //     float ~X();
10356     //   };
10357     //
10358     // The return type will be eliminated later.
10359     if (D.getDeclSpec().hasTypeSpecifier())
10360       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10361         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10362         << SourceRange(D.getIdentifierLoc());
10363     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10364       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10365                                 SourceLocation(),
10366                                 D.getDeclSpec().getConstSpecLoc(),
10367                                 D.getDeclSpec().getVolatileSpecLoc(),
10368                                 D.getDeclSpec().getRestrictSpecLoc(),
10369                                 D.getDeclSpec().getAtomicSpecLoc());
10370       D.setInvalidType();
10371     }
10372   }
10373 
10374   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10375 
10376   // C++0x [class.dtor]p2:
10377   //   A destructor shall not be declared with a ref-qualifier.
10378   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10379   if (FTI.hasRefQualifier()) {
10380     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10381       << FTI.RefQualifierIsLValueRef
10382       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10383     D.setInvalidType();
10384   }
10385 
10386   // Make sure we don't have any parameters.
10387   if (FTIHasNonVoidParameters(FTI)) {
10388     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10389 
10390     // Delete the parameters.
10391     FTI.freeParams();
10392     D.setInvalidType();
10393   }
10394 
10395   // Make sure the destructor isn't variadic.
10396   if (FTI.isVariadic) {
10397     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10398     D.setInvalidType();
10399   }
10400 
10401   // Rebuild the function type "R" without any type qualifiers or
10402   // parameters (in case any of the errors above fired) and with
10403   // "void" as the return type, since destructors don't have return
10404   // types.
10405   if (!D.isInvalidType())
10406     return R;
10407 
10408   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10409   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10410   EPI.Variadic = false;
10411   EPI.TypeQuals = Qualifiers();
10412   EPI.RefQualifier = RQ_None;
10413   return Context.getFunctionType(Context.VoidTy, None, EPI);
10414 }
10415 
10416 static void extendLeft(SourceRange &R, SourceRange Before) {
10417   if (Before.isInvalid())
10418     return;
10419   R.setBegin(Before.getBegin());
10420   if (R.getEnd().isInvalid())
10421     R.setEnd(Before.getEnd());
10422 }
10423 
10424 static void extendRight(SourceRange &R, SourceRange After) {
10425   if (After.isInvalid())
10426     return;
10427   if (R.getBegin().isInvalid())
10428     R.setBegin(After.getBegin());
10429   R.setEnd(After.getEnd());
10430 }
10431 
10432 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10433 /// well-formednes of the conversion function declarator @p D with
10434 /// type @p R. If there are any errors in the declarator, this routine
10435 /// will emit diagnostics and return true. Otherwise, it will return
10436 /// false. Either way, the type @p R will be updated to reflect a
10437 /// well-formed type for the conversion operator.
10438 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10439                                      StorageClass& SC) {
10440   // C++ [class.conv.fct]p1:
10441   //   Neither parameter types nor return type can be specified. The
10442   //   type of a conversion function (8.3.5) is "function taking no
10443   //   parameter returning conversion-type-id."
10444   if (SC == SC_Static) {
10445     if (!D.isInvalidType())
10446       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10447         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10448         << D.getName().getSourceRange();
10449     D.setInvalidType();
10450     SC = SC_None;
10451   }
10452 
10453   TypeSourceInfo *ConvTSI = nullptr;
10454   QualType ConvType =
10455       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10456 
10457   const DeclSpec &DS = D.getDeclSpec();
10458   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10459     // Conversion functions don't have return types, but the parser will
10460     // happily parse something like:
10461     //
10462     //   class X {
10463     //     float operator bool();
10464     //   };
10465     //
10466     // The return type will be changed later anyway.
10467     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10468       << SourceRange(DS.getTypeSpecTypeLoc())
10469       << SourceRange(D.getIdentifierLoc());
10470     D.setInvalidType();
10471   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10472     // It's also plausible that the user writes type qualifiers in the wrong
10473     // place, such as:
10474     //   struct S { const operator int(); };
10475     // FIXME: we could provide a fixit to move the qualifiers onto the
10476     // conversion type.
10477     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10478         << SourceRange(D.getIdentifierLoc()) << 0;
10479     D.setInvalidType();
10480   }
10481 
10482   const auto *Proto = R->castAs<FunctionProtoType>();
10483 
10484   // Make sure we don't have any parameters.
10485   if (Proto->getNumParams() > 0) {
10486     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10487 
10488     // Delete the parameters.
10489     D.getFunctionTypeInfo().freeParams();
10490     D.setInvalidType();
10491   } else if (Proto->isVariadic()) {
10492     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10493     D.setInvalidType();
10494   }
10495 
10496   // Diagnose "&operator bool()" and other such nonsense.  This
10497   // is actually a gcc extension which we don't support.
10498   if (Proto->getReturnType() != ConvType) {
10499     bool NeedsTypedef = false;
10500     SourceRange Before, After;
10501 
10502     // Walk the chunks and extract information on them for our diagnostic.
10503     bool PastFunctionChunk = false;
10504     for (auto &Chunk : D.type_objects()) {
10505       switch (Chunk.Kind) {
10506       case DeclaratorChunk::Function:
10507         if (!PastFunctionChunk) {
10508           if (Chunk.Fun.HasTrailingReturnType) {
10509             TypeSourceInfo *TRT = nullptr;
10510             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10511             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10512           }
10513           PastFunctionChunk = true;
10514           break;
10515         }
10516         LLVM_FALLTHROUGH;
10517       case DeclaratorChunk::Array:
10518         NeedsTypedef = true;
10519         extendRight(After, Chunk.getSourceRange());
10520         break;
10521 
10522       case DeclaratorChunk::Pointer:
10523       case DeclaratorChunk::BlockPointer:
10524       case DeclaratorChunk::Reference:
10525       case DeclaratorChunk::MemberPointer:
10526       case DeclaratorChunk::Pipe:
10527         extendLeft(Before, Chunk.getSourceRange());
10528         break;
10529 
10530       case DeclaratorChunk::Paren:
10531         extendLeft(Before, Chunk.Loc);
10532         extendRight(After, Chunk.EndLoc);
10533         break;
10534       }
10535     }
10536 
10537     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10538                          After.isValid()  ? After.getBegin() :
10539                                             D.getIdentifierLoc();
10540     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10541     DB << Before << After;
10542 
10543     if (!NeedsTypedef) {
10544       DB << /*don't need a typedef*/0;
10545 
10546       // If we can provide a correct fix-it hint, do so.
10547       if (After.isInvalid() && ConvTSI) {
10548         SourceLocation InsertLoc =
10549             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10550         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10551            << FixItHint::CreateInsertionFromRange(
10552                   InsertLoc, CharSourceRange::getTokenRange(Before))
10553            << FixItHint::CreateRemoval(Before);
10554       }
10555     } else if (!Proto->getReturnType()->isDependentType()) {
10556       DB << /*typedef*/1 << Proto->getReturnType();
10557     } else if (getLangOpts().CPlusPlus11) {
10558       DB << /*alias template*/2 << Proto->getReturnType();
10559     } else {
10560       DB << /*might not be fixable*/3;
10561     }
10562 
10563     // Recover by incorporating the other type chunks into the result type.
10564     // Note, this does *not* change the name of the function. This is compatible
10565     // with the GCC extension:
10566     //   struct S { &operator int(); } s;
10567     //   int &r = s.operator int(); // ok in GCC
10568     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10569     ConvType = Proto->getReturnType();
10570   }
10571 
10572   // C++ [class.conv.fct]p4:
10573   //   The conversion-type-id shall not represent a function type nor
10574   //   an array type.
10575   if (ConvType->isArrayType()) {
10576     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10577     ConvType = Context.getPointerType(ConvType);
10578     D.setInvalidType();
10579   } else if (ConvType->isFunctionType()) {
10580     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10581     ConvType = Context.getPointerType(ConvType);
10582     D.setInvalidType();
10583   }
10584 
10585   // Rebuild the function type "R" without any parameters (in case any
10586   // of the errors above fired) and with the conversion type as the
10587   // return type.
10588   if (D.isInvalidType())
10589     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10590 
10591   // C++0x explicit conversion operators.
10592   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10593     Diag(DS.getExplicitSpecLoc(),
10594          getLangOpts().CPlusPlus11
10595              ? diag::warn_cxx98_compat_explicit_conversion_functions
10596              : diag::ext_explicit_conversion_functions)
10597         << SourceRange(DS.getExplicitSpecRange());
10598 }
10599 
10600 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10601 /// the declaration of the given C++ conversion function. This routine
10602 /// is responsible for recording the conversion function in the C++
10603 /// class, if possible.
10604 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10605   assert(Conversion && "Expected to receive a conversion function declaration");
10606 
10607   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10608 
10609   // Make sure we aren't redeclaring the conversion function.
10610   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10611   // C++ [class.conv.fct]p1:
10612   //   [...] A conversion function is never used to convert a
10613   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10614   //   same object type (or a reference to it), to a (possibly
10615   //   cv-qualified) base class of that type (or a reference to it),
10616   //   or to (possibly cv-qualified) void.
10617   QualType ClassType
10618     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10619   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10620     ConvType = ConvTypeRef->getPointeeType();
10621   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10622       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10623     /* Suppress diagnostics for instantiations. */;
10624   else if (Conversion->size_overridden_methods() != 0)
10625     /* Suppress diagnostics for overriding virtual function in a base class. */;
10626   else if (ConvType->isRecordType()) {
10627     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10628     if (ConvType == ClassType)
10629       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10630         << ClassType;
10631     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10632       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10633         <<  ClassType << ConvType;
10634   } else if (ConvType->isVoidType()) {
10635     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10636       << ClassType << ConvType;
10637   }
10638 
10639   if (FunctionTemplateDecl *ConversionTemplate
10640                                 = Conversion->getDescribedFunctionTemplate())
10641     return ConversionTemplate;
10642 
10643   return Conversion;
10644 }
10645 
10646 namespace {
10647 /// Utility class to accumulate and print a diagnostic listing the invalid
10648 /// specifier(s) on a declaration.
10649 struct BadSpecifierDiagnoser {
10650   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10651       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10652   ~BadSpecifierDiagnoser() {
10653     Diagnostic << Specifiers;
10654   }
10655 
10656   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10657     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10658   }
10659   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10660     return check(SpecLoc,
10661                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10662   }
10663   void check(SourceLocation SpecLoc, const char *Spec) {
10664     if (SpecLoc.isInvalid()) return;
10665     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10666     if (!Specifiers.empty()) Specifiers += " ";
10667     Specifiers += Spec;
10668   }
10669 
10670   Sema &S;
10671   Sema::SemaDiagnosticBuilder Diagnostic;
10672   std::string Specifiers;
10673 };
10674 }
10675 
10676 /// Check the validity of a declarator that we parsed for a deduction-guide.
10677 /// These aren't actually declarators in the grammar, so we need to check that
10678 /// the user didn't specify any pieces that are not part of the deduction-guide
10679 /// grammar.
10680 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10681                                          StorageClass &SC) {
10682   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10683   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10684   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10685 
10686   // C++ [temp.deduct.guide]p3:
10687   //   A deduction-gide shall be declared in the same scope as the
10688   //   corresponding class template.
10689   if (!CurContext->getRedeclContext()->Equals(
10690           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10691     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10692       << GuidedTemplateDecl;
10693     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10694   }
10695 
10696   auto &DS = D.getMutableDeclSpec();
10697   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10698   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10699       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10700       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10701     BadSpecifierDiagnoser Diagnoser(
10702         *this, D.getIdentifierLoc(),
10703         diag::err_deduction_guide_invalid_specifier);
10704 
10705     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10706     DS.ClearStorageClassSpecs();
10707     SC = SC_None;
10708 
10709     // 'explicit' is permitted.
10710     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10711     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10712     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10713     DS.ClearConstexprSpec();
10714 
10715     Diagnoser.check(DS.getConstSpecLoc(), "const");
10716     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10717     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10718     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10719     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10720     DS.ClearTypeQualifiers();
10721 
10722     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10723     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10724     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10725     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10726     DS.ClearTypeSpecType();
10727   }
10728 
10729   if (D.isInvalidType())
10730     return;
10731 
10732   // Check the declarator is simple enough.
10733   bool FoundFunction = false;
10734   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10735     if (Chunk.Kind == DeclaratorChunk::Paren)
10736       continue;
10737     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10738       Diag(D.getDeclSpec().getBeginLoc(),
10739            diag::err_deduction_guide_with_complex_decl)
10740           << D.getSourceRange();
10741       break;
10742     }
10743     if (!Chunk.Fun.hasTrailingReturnType()) {
10744       Diag(D.getName().getBeginLoc(),
10745            diag::err_deduction_guide_no_trailing_return_type);
10746       break;
10747     }
10748 
10749     // Check that the return type is written as a specialization of
10750     // the template specified as the deduction-guide's name.
10751     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10752     TypeSourceInfo *TSI = nullptr;
10753     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10754     assert(TSI && "deduction guide has valid type but invalid return type?");
10755     bool AcceptableReturnType = false;
10756     bool MightInstantiateToSpecialization = false;
10757     if (auto RetTST =
10758             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10759       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10760       bool TemplateMatches =
10761           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10762       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10763         AcceptableReturnType = true;
10764       else {
10765         // This could still instantiate to the right type, unless we know it
10766         // names the wrong class template.
10767         auto *TD = SpecifiedName.getAsTemplateDecl();
10768         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10769                                              !TemplateMatches);
10770       }
10771     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10772       MightInstantiateToSpecialization = true;
10773     }
10774 
10775     if (!AcceptableReturnType) {
10776       Diag(TSI->getTypeLoc().getBeginLoc(),
10777            diag::err_deduction_guide_bad_trailing_return_type)
10778           << GuidedTemplate << TSI->getType()
10779           << MightInstantiateToSpecialization
10780           << TSI->getTypeLoc().getSourceRange();
10781     }
10782 
10783     // Keep going to check that we don't have any inner declarator pieces (we
10784     // could still have a function returning a pointer to a function).
10785     FoundFunction = true;
10786   }
10787 
10788   if (D.isFunctionDefinition())
10789     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10790 }
10791 
10792 //===----------------------------------------------------------------------===//
10793 // Namespace Handling
10794 //===----------------------------------------------------------------------===//
10795 
10796 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10797 /// reopened.
10798 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10799                                             SourceLocation Loc,
10800                                             IdentifierInfo *II, bool *IsInline,
10801                                             NamespaceDecl *PrevNS) {
10802   assert(*IsInline != PrevNS->isInline());
10803 
10804   // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10805   // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10806   // inline namespaces, with the intention of bringing names into namespace std.
10807   //
10808   // We support this just well enough to get that case working; this is not
10809   // sufficient to support reopening namespaces as inline in general.
10810   if (*IsInline && II && II->getName().startswith("__atomic") &&
10811       S.getSourceManager().isInSystemHeader(Loc)) {
10812     // Mark all prior declarations of the namespace as inline.
10813     for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10814          NS = NS->getPreviousDecl())
10815       NS->setInline(*IsInline);
10816     // Patch up the lookup table for the containing namespace. This isn't really
10817     // correct, but it's good enough for this particular case.
10818     for (auto *I : PrevNS->decls())
10819       if (auto *ND = dyn_cast<NamedDecl>(I))
10820         PrevNS->getParent()->makeDeclVisibleInContext(ND);
10821     return;
10822   }
10823 
10824   if (PrevNS->isInline())
10825     // The user probably just forgot the 'inline', so suggest that it
10826     // be added back.
10827     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10828       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10829   else
10830     S.Diag(Loc, diag::err_inline_namespace_mismatch);
10831 
10832   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10833   *IsInline = PrevNS->isInline();
10834 }
10835 
10836 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10837 /// definition.
10838 Decl *Sema::ActOnStartNamespaceDef(
10839     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10840     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10841     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10842   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10843   // For anonymous namespace, take the location of the left brace.
10844   SourceLocation Loc = II ? IdentLoc : LBrace;
10845   bool IsInline = InlineLoc.isValid();
10846   bool IsInvalid = false;
10847   bool IsStd = false;
10848   bool AddToKnown = false;
10849   Scope *DeclRegionScope = NamespcScope->getParent();
10850 
10851   NamespaceDecl *PrevNS = nullptr;
10852   if (II) {
10853     // C++ [namespace.def]p2:
10854     //   The identifier in an original-namespace-definition shall not
10855     //   have been previously defined in the declarative region in
10856     //   which the original-namespace-definition appears. The
10857     //   identifier in an original-namespace-definition is the name of
10858     //   the namespace. Subsequently in that declarative region, it is
10859     //   treated as an original-namespace-name.
10860     //
10861     // Since namespace names are unique in their scope, and we don't
10862     // look through using directives, just look for any ordinary names
10863     // as if by qualified name lookup.
10864     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10865                    ForExternalRedeclaration);
10866     LookupQualifiedName(R, CurContext->getRedeclContext());
10867     NamedDecl *PrevDecl =
10868         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10869     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10870 
10871     if (PrevNS) {
10872       // This is an extended namespace definition.
10873       if (IsInline != PrevNS->isInline())
10874         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10875                                         &IsInline, PrevNS);
10876     } else if (PrevDecl) {
10877       // This is an invalid name redefinition.
10878       Diag(Loc, diag::err_redefinition_different_kind)
10879         << II;
10880       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10881       IsInvalid = true;
10882       // Continue on to push Namespc as current DeclContext and return it.
10883     } else if (II->isStr("std") &&
10884                CurContext->getRedeclContext()->isTranslationUnit()) {
10885       // This is the first "real" definition of the namespace "std", so update
10886       // our cache of the "std" namespace to point at this definition.
10887       PrevNS = getStdNamespace();
10888       IsStd = true;
10889       AddToKnown = !IsInline;
10890     } else {
10891       // We've seen this namespace for the first time.
10892       AddToKnown = !IsInline;
10893     }
10894   } else {
10895     // Anonymous namespaces.
10896 
10897     // Determine whether the parent already has an anonymous namespace.
10898     DeclContext *Parent = CurContext->getRedeclContext();
10899     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10900       PrevNS = TU->getAnonymousNamespace();
10901     } else {
10902       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10903       PrevNS = ND->getAnonymousNamespace();
10904     }
10905 
10906     if (PrevNS && IsInline != PrevNS->isInline())
10907       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10908                                       &IsInline, PrevNS);
10909   }
10910 
10911   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10912                                                  StartLoc, Loc, II, PrevNS);
10913   if (IsInvalid)
10914     Namespc->setInvalidDecl();
10915 
10916   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10917   AddPragmaAttributes(DeclRegionScope, Namespc);
10918 
10919   // FIXME: Should we be merging attributes?
10920   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10921     PushNamespaceVisibilityAttr(Attr, Loc);
10922 
10923   if (IsStd)
10924     StdNamespace = Namespc;
10925   if (AddToKnown)
10926     KnownNamespaces[Namespc] = false;
10927 
10928   if (II) {
10929     PushOnScopeChains(Namespc, DeclRegionScope);
10930   } else {
10931     // Link the anonymous namespace into its parent.
10932     DeclContext *Parent = CurContext->getRedeclContext();
10933     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10934       TU->setAnonymousNamespace(Namespc);
10935     } else {
10936       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10937     }
10938 
10939     CurContext->addDecl(Namespc);
10940 
10941     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
10942     //   behaves as if it were replaced by
10943     //     namespace unique { /* empty body */ }
10944     //     using namespace unique;
10945     //     namespace unique { namespace-body }
10946     //   where all occurrences of 'unique' in a translation unit are
10947     //   replaced by the same identifier and this identifier differs
10948     //   from all other identifiers in the entire program.
10949 
10950     // We just create the namespace with an empty name and then add an
10951     // implicit using declaration, just like the standard suggests.
10952     //
10953     // CodeGen enforces the "universally unique" aspect by giving all
10954     // declarations semantically contained within an anonymous
10955     // namespace internal linkage.
10956 
10957     if (!PrevNS) {
10958       UD = UsingDirectiveDecl::Create(Context, Parent,
10959                                       /* 'using' */ LBrace,
10960                                       /* 'namespace' */ SourceLocation(),
10961                                       /* qualifier */ NestedNameSpecifierLoc(),
10962                                       /* identifier */ SourceLocation(),
10963                                       Namespc,
10964                                       /* Ancestor */ Parent);
10965       UD->setImplicit();
10966       Parent->addDecl(UD);
10967     }
10968   }
10969 
10970   ActOnDocumentableDecl(Namespc);
10971 
10972   // Although we could have an invalid decl (i.e. the namespace name is a
10973   // redefinition), push it as current DeclContext and try to continue parsing.
10974   // FIXME: We should be able to push Namespc here, so that the each DeclContext
10975   // for the namespace has the declarations that showed up in that particular
10976   // namespace definition.
10977   PushDeclContext(NamespcScope, Namespc);
10978   return Namespc;
10979 }
10980 
10981 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
10982 /// is a namespace alias, returns the namespace it points to.
10983 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
10984   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
10985     return AD->getNamespace();
10986   return dyn_cast_or_null<NamespaceDecl>(D);
10987 }
10988 
10989 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
10990 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
10991 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
10992   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
10993   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
10994   Namespc->setRBraceLoc(RBrace);
10995   PopDeclContext();
10996   if (Namespc->hasAttr<VisibilityAttr>())
10997     PopPragmaVisibility(true, RBrace);
10998   // If this namespace contains an export-declaration, export it now.
10999   if (DeferredExportedNamespaces.erase(Namespc))
11000     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11001 }
11002 
11003 CXXRecordDecl *Sema::getStdBadAlloc() const {
11004   return cast_or_null<CXXRecordDecl>(
11005                                   StdBadAlloc.get(Context.getExternalSource()));
11006 }
11007 
11008 EnumDecl *Sema::getStdAlignValT() const {
11009   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11010 }
11011 
11012 NamespaceDecl *Sema::getStdNamespace() const {
11013   return cast_or_null<NamespaceDecl>(
11014                                  StdNamespace.get(Context.getExternalSource()));
11015 }
11016 
11017 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11018   if (!StdExperimentalNamespaceCache) {
11019     if (auto Std = getStdNamespace()) {
11020       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11021                           SourceLocation(), LookupNamespaceName);
11022       if (!LookupQualifiedName(Result, Std) ||
11023           !(StdExperimentalNamespaceCache =
11024                 Result.getAsSingle<NamespaceDecl>()))
11025         Result.suppressDiagnostics();
11026     }
11027   }
11028   return StdExperimentalNamespaceCache;
11029 }
11030 
11031 namespace {
11032 
11033 enum UnsupportedSTLSelect {
11034   USS_InvalidMember,
11035   USS_MissingMember,
11036   USS_NonTrivial,
11037   USS_Other
11038 };
11039 
11040 struct InvalidSTLDiagnoser {
11041   Sema &S;
11042   SourceLocation Loc;
11043   QualType TyForDiags;
11044 
11045   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11046                       const VarDecl *VD = nullptr) {
11047     {
11048       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11049                << TyForDiags << ((int)Sel);
11050       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11051         assert(!Name.empty());
11052         D << Name;
11053       }
11054     }
11055     if (Sel == USS_InvalidMember) {
11056       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11057           << VD << VD->getSourceRange();
11058     }
11059     return QualType();
11060   }
11061 };
11062 } // namespace
11063 
11064 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11065                                            SourceLocation Loc,
11066                                            ComparisonCategoryUsage Usage) {
11067   assert(getLangOpts().CPlusPlus &&
11068          "Looking for comparison category type outside of C++.");
11069 
11070   // Use an elaborated type for diagnostics which has a name containing the
11071   // prepended 'std' namespace but not any inline namespace names.
11072   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11073     auto *NNS =
11074         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11075     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11076   };
11077 
11078   // Check if we've already successfully checked the comparison category type
11079   // before. If so, skip checking it again.
11080   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11081   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11082     // The only thing we need to check is that the type has a reachable
11083     // definition in the current context.
11084     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11085       return QualType();
11086 
11087     return Info->getType();
11088   }
11089 
11090   // If lookup failed
11091   if (!Info) {
11092     std::string NameForDiags = "std::";
11093     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11094     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11095         << NameForDiags << (int)Usage;
11096     return QualType();
11097   }
11098 
11099   assert(Info->Kind == Kind);
11100   assert(Info->Record);
11101 
11102   // Update the Record decl in case we encountered a forward declaration on our
11103   // first pass. FIXME: This is a bit of a hack.
11104   if (Info->Record->hasDefinition())
11105     Info->Record = Info->Record->getDefinition();
11106 
11107   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11108     return QualType();
11109 
11110   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11111 
11112   if (!Info->Record->isTriviallyCopyable())
11113     return UnsupportedSTLError(USS_NonTrivial);
11114 
11115   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11116     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11117     // Tolerate empty base classes.
11118     if (Base->isEmpty())
11119       continue;
11120     // Reject STL implementations which have at least one non-empty base.
11121     return UnsupportedSTLError();
11122   }
11123 
11124   // Check that the STL has implemented the types using a single integer field.
11125   // This expectation allows better codegen for builtin operators. We require:
11126   //   (1) The class has exactly one field.
11127   //   (2) The field is an integral or enumeration type.
11128   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11129   if (std::distance(FIt, FEnd) != 1 ||
11130       !FIt->getType()->isIntegralOrEnumerationType()) {
11131     return UnsupportedSTLError();
11132   }
11133 
11134   // Build each of the require values and store them in Info.
11135   for (ComparisonCategoryResult CCR :
11136        ComparisonCategories::getPossibleResultsForType(Kind)) {
11137     StringRef MemName = ComparisonCategories::getResultString(CCR);
11138     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11139 
11140     if (!ValInfo)
11141       return UnsupportedSTLError(USS_MissingMember, MemName);
11142 
11143     VarDecl *VD = ValInfo->VD;
11144     assert(VD && "should not be null!");
11145 
11146     // Attempt to diagnose reasons why the STL definition of this type
11147     // might be foobar, including it failing to be a constant expression.
11148     // TODO Handle more ways the lookup or result can be invalid.
11149     if (!VD->isStaticDataMember() ||
11150         !VD->isUsableInConstantExpressions(Context))
11151       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11152 
11153     // Attempt to evaluate the var decl as a constant expression and extract
11154     // the value of its first field as a ICE. If this fails, the STL
11155     // implementation is not supported.
11156     if (!ValInfo->hasValidIntValue())
11157       return UnsupportedSTLError();
11158 
11159     MarkVariableReferenced(Loc, VD);
11160   }
11161 
11162   // We've successfully built the required types and expressions. Update
11163   // the cache and return the newly cached value.
11164   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11165   return Info->getType();
11166 }
11167 
11168 /// Retrieve the special "std" namespace, which may require us to
11169 /// implicitly define the namespace.
11170 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11171   if (!StdNamespace) {
11172     // The "std" namespace has not yet been defined, so build one implicitly.
11173     StdNamespace = NamespaceDecl::Create(Context,
11174                                          Context.getTranslationUnitDecl(),
11175                                          /*Inline=*/false,
11176                                          SourceLocation(), SourceLocation(),
11177                                          &PP.getIdentifierTable().get("std"),
11178                                          /*PrevDecl=*/nullptr);
11179     getStdNamespace()->setImplicit(true);
11180   }
11181 
11182   return getStdNamespace();
11183 }
11184 
11185 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11186   assert(getLangOpts().CPlusPlus &&
11187          "Looking for std::initializer_list outside of C++.");
11188 
11189   // We're looking for implicit instantiations of
11190   // template <typename E> class std::initializer_list.
11191 
11192   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11193     return false;
11194 
11195   ClassTemplateDecl *Template = nullptr;
11196   const TemplateArgument *Arguments = nullptr;
11197 
11198   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11199 
11200     ClassTemplateSpecializationDecl *Specialization =
11201         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11202     if (!Specialization)
11203       return false;
11204 
11205     Template = Specialization->getSpecializedTemplate();
11206     Arguments = Specialization->getTemplateArgs().data();
11207   } else if (const TemplateSpecializationType *TST =
11208                  Ty->getAs<TemplateSpecializationType>()) {
11209     Template = dyn_cast_or_null<ClassTemplateDecl>(
11210         TST->getTemplateName().getAsTemplateDecl());
11211     Arguments = TST->getArgs();
11212   }
11213   if (!Template)
11214     return false;
11215 
11216   if (!StdInitializerList) {
11217     // Haven't recognized std::initializer_list yet, maybe this is it.
11218     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11219     if (TemplateClass->getIdentifier() !=
11220             &PP.getIdentifierTable().get("initializer_list") ||
11221         !getStdNamespace()->InEnclosingNamespaceSetOf(
11222             TemplateClass->getDeclContext()))
11223       return false;
11224     // This is a template called std::initializer_list, but is it the right
11225     // template?
11226     TemplateParameterList *Params = Template->getTemplateParameters();
11227     if (Params->getMinRequiredArguments() != 1)
11228       return false;
11229     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11230       return false;
11231 
11232     // It's the right template.
11233     StdInitializerList = Template;
11234   }
11235 
11236   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11237     return false;
11238 
11239   // This is an instance of std::initializer_list. Find the argument type.
11240   if (Element)
11241     *Element = Arguments[0].getAsType();
11242   return true;
11243 }
11244 
11245 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11246   NamespaceDecl *Std = S.getStdNamespace();
11247   if (!Std) {
11248     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11249     return nullptr;
11250   }
11251 
11252   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11253                       Loc, Sema::LookupOrdinaryName);
11254   if (!S.LookupQualifiedName(Result, Std)) {
11255     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11256     return nullptr;
11257   }
11258   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11259   if (!Template) {
11260     Result.suppressDiagnostics();
11261     // We found something weird. Complain about the first thing we found.
11262     NamedDecl *Found = *Result.begin();
11263     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11264     return nullptr;
11265   }
11266 
11267   // We found some template called std::initializer_list. Now verify that it's
11268   // correct.
11269   TemplateParameterList *Params = Template->getTemplateParameters();
11270   if (Params->getMinRequiredArguments() != 1 ||
11271       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11272     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11273     return nullptr;
11274   }
11275 
11276   return Template;
11277 }
11278 
11279 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11280   if (!StdInitializerList) {
11281     StdInitializerList = LookupStdInitializerList(*this, Loc);
11282     if (!StdInitializerList)
11283       return QualType();
11284   }
11285 
11286   TemplateArgumentListInfo Args(Loc, Loc);
11287   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11288                                        Context.getTrivialTypeSourceInfo(Element,
11289                                                                         Loc)));
11290   return Context.getCanonicalType(
11291       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11292 }
11293 
11294 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11295   // C++ [dcl.init.list]p2:
11296   //   A constructor is an initializer-list constructor if its first parameter
11297   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11298   //   std::initializer_list<E> for some type E, and either there are no other
11299   //   parameters or else all other parameters have default arguments.
11300   if (!Ctor->hasOneParamOrDefaultArgs())
11301     return false;
11302 
11303   QualType ArgType = Ctor->getParamDecl(0)->getType();
11304   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11305     ArgType = RT->getPointeeType().getUnqualifiedType();
11306 
11307   return isStdInitializerList(ArgType, nullptr);
11308 }
11309 
11310 /// Determine whether a using statement is in a context where it will be
11311 /// apply in all contexts.
11312 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11313   switch (CurContext->getDeclKind()) {
11314     case Decl::TranslationUnit:
11315       return true;
11316     case Decl::LinkageSpec:
11317       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11318     default:
11319       return false;
11320   }
11321 }
11322 
11323 namespace {
11324 
11325 // Callback to only accept typo corrections that are namespaces.
11326 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11327 public:
11328   bool ValidateCandidate(const TypoCorrection &candidate) override {
11329     if (NamedDecl *ND = candidate.getCorrectionDecl())
11330       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11331     return false;
11332   }
11333 
11334   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11335     return std::make_unique<NamespaceValidatorCCC>(*this);
11336   }
11337 };
11338 
11339 }
11340 
11341 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11342                                        CXXScopeSpec &SS,
11343                                        SourceLocation IdentLoc,
11344                                        IdentifierInfo *Ident) {
11345   R.clear();
11346   NamespaceValidatorCCC CCC{};
11347   if (TypoCorrection Corrected =
11348           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11349                         Sema::CTK_ErrorRecovery)) {
11350     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11351       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11352       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11353                               Ident->getName().equals(CorrectedStr);
11354       S.diagnoseTypo(Corrected,
11355                      S.PDiag(diag::err_using_directive_member_suggest)
11356                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11357                      S.PDiag(diag::note_namespace_defined_here));
11358     } else {
11359       S.diagnoseTypo(Corrected,
11360                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11361                      S.PDiag(diag::note_namespace_defined_here));
11362     }
11363     R.addDecl(Corrected.getFoundDecl());
11364     return true;
11365   }
11366   return false;
11367 }
11368 
11369 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11370                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11371                                 SourceLocation IdentLoc,
11372                                 IdentifierInfo *NamespcName,
11373                                 const ParsedAttributesView &AttrList) {
11374   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11375   assert(NamespcName && "Invalid NamespcName.");
11376   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11377 
11378   // This can only happen along a recovery path.
11379   while (S->isTemplateParamScope())
11380     S = S->getParent();
11381   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11382 
11383   UsingDirectiveDecl *UDir = nullptr;
11384   NestedNameSpecifier *Qualifier = nullptr;
11385   if (SS.isSet())
11386     Qualifier = SS.getScopeRep();
11387 
11388   // Lookup namespace name.
11389   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11390   LookupParsedName(R, S, &SS);
11391   if (R.isAmbiguous())
11392     return nullptr;
11393 
11394   if (R.empty()) {
11395     R.clear();
11396     // Allow "using namespace std;" or "using namespace ::std;" even if
11397     // "std" hasn't been defined yet, for GCC compatibility.
11398     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11399         NamespcName->isStr("std")) {
11400       Diag(IdentLoc, diag::ext_using_undefined_std);
11401       R.addDecl(getOrCreateStdNamespace());
11402       R.resolveKind();
11403     }
11404     // Otherwise, attempt typo correction.
11405     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11406   }
11407 
11408   if (!R.empty()) {
11409     NamedDecl *Named = R.getRepresentativeDecl();
11410     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11411     assert(NS && "expected namespace decl");
11412 
11413     // The use of a nested name specifier may trigger deprecation warnings.
11414     DiagnoseUseOfDecl(Named, IdentLoc);
11415 
11416     // C++ [namespace.udir]p1:
11417     //   A using-directive specifies that the names in the nominated
11418     //   namespace can be used in the scope in which the
11419     //   using-directive appears after the using-directive. During
11420     //   unqualified name lookup (3.4.1), the names appear as if they
11421     //   were declared in the nearest enclosing namespace which
11422     //   contains both the using-directive and the nominated
11423     //   namespace. [Note: in this context, "contains" means "contains
11424     //   directly or indirectly". ]
11425 
11426     // Find enclosing context containing both using-directive and
11427     // nominated namespace.
11428     DeclContext *CommonAncestor = NS;
11429     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11430       CommonAncestor = CommonAncestor->getParent();
11431 
11432     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11433                                       SS.getWithLocInContext(Context),
11434                                       IdentLoc, Named, CommonAncestor);
11435 
11436     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11437         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11438       Diag(IdentLoc, diag::warn_using_directive_in_header);
11439     }
11440 
11441     PushUsingDirective(S, UDir);
11442   } else {
11443     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11444   }
11445 
11446   if (UDir)
11447     ProcessDeclAttributeList(S, UDir, AttrList);
11448 
11449   return UDir;
11450 }
11451 
11452 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11453   // If the scope has an associated entity and the using directive is at
11454   // namespace or translation unit scope, add the UsingDirectiveDecl into
11455   // its lookup structure so qualified name lookup can find it.
11456   DeclContext *Ctx = S->getEntity();
11457   if (Ctx && !Ctx->isFunctionOrMethod())
11458     Ctx->addDecl(UDir);
11459   else
11460     // Otherwise, it is at block scope. The using-directives will affect lookup
11461     // only to the end of the scope.
11462     S->PushUsingDirective(UDir);
11463 }
11464 
11465 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11466                                   SourceLocation UsingLoc,
11467                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11468                                   UnqualifiedId &Name,
11469                                   SourceLocation EllipsisLoc,
11470                                   const ParsedAttributesView &AttrList) {
11471   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11472 
11473   if (SS.isEmpty()) {
11474     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11475     return nullptr;
11476   }
11477 
11478   switch (Name.getKind()) {
11479   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11480   case UnqualifiedIdKind::IK_Identifier:
11481   case UnqualifiedIdKind::IK_OperatorFunctionId:
11482   case UnqualifiedIdKind::IK_LiteralOperatorId:
11483   case UnqualifiedIdKind::IK_ConversionFunctionId:
11484     break;
11485 
11486   case UnqualifiedIdKind::IK_ConstructorName:
11487   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11488     // C++11 inheriting constructors.
11489     Diag(Name.getBeginLoc(),
11490          getLangOpts().CPlusPlus11
11491              ? diag::warn_cxx98_compat_using_decl_constructor
11492              : diag::err_using_decl_constructor)
11493         << SS.getRange();
11494 
11495     if (getLangOpts().CPlusPlus11) break;
11496 
11497     return nullptr;
11498 
11499   case UnqualifiedIdKind::IK_DestructorName:
11500     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11501     return nullptr;
11502 
11503   case UnqualifiedIdKind::IK_TemplateId:
11504     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11505         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11506     return nullptr;
11507 
11508   case UnqualifiedIdKind::IK_DeductionGuideName:
11509     llvm_unreachable("cannot parse qualified deduction guide name");
11510   }
11511 
11512   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11513   DeclarationName TargetName = TargetNameInfo.getName();
11514   if (!TargetName)
11515     return nullptr;
11516 
11517   // Warn about access declarations.
11518   if (UsingLoc.isInvalid()) {
11519     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11520                                  ? diag::err_access_decl
11521                                  : diag::warn_access_decl_deprecated)
11522         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11523   }
11524 
11525   if (EllipsisLoc.isInvalid()) {
11526     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11527         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11528       return nullptr;
11529   } else {
11530     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11531         !TargetNameInfo.containsUnexpandedParameterPack()) {
11532       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11533         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11534       EllipsisLoc = SourceLocation();
11535     }
11536   }
11537 
11538   NamedDecl *UD =
11539       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11540                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11541                             /*IsInstantiation*/false);
11542   if (UD)
11543     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11544 
11545   return UD;
11546 }
11547 
11548 /// Determine whether a using declaration considers the given
11549 /// declarations as "equivalent", e.g., if they are redeclarations of
11550 /// the same entity or are both typedefs of the same type.
11551 static bool
11552 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11553   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11554     return true;
11555 
11556   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11557     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11558       return Context.hasSameType(TD1->getUnderlyingType(),
11559                                  TD2->getUnderlyingType());
11560 
11561   return false;
11562 }
11563 
11564 
11565 /// Determines whether to create a using shadow decl for a particular
11566 /// decl, given the set of decls existing prior to this using lookup.
11567 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11568                                 const LookupResult &Previous,
11569                                 UsingShadowDecl *&PrevShadow) {
11570   // Diagnose finding a decl which is not from a base class of the
11571   // current class.  We do this now because there are cases where this
11572   // function will silently decide not to build a shadow decl, which
11573   // will pre-empt further diagnostics.
11574   //
11575   // We don't need to do this in C++11 because we do the check once on
11576   // the qualifier.
11577   //
11578   // FIXME: diagnose the following if we care enough:
11579   //   struct A { int foo; };
11580   //   struct B : A { using A::foo; };
11581   //   template <class T> struct C : A {};
11582   //   template <class T> struct D : C<T> { using B::foo; } // <---
11583   // This is invalid (during instantiation) in C++03 because B::foo
11584   // resolves to the using decl in B, which is not a base class of D<T>.
11585   // We can't diagnose it immediately because C<T> is an unknown
11586   // specialization.  The UsingShadowDecl in D<T> then points directly
11587   // to A::foo, which will look well-formed when we instantiate.
11588   // The right solution is to not collapse the shadow-decl chain.
11589   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11590     DeclContext *OrigDC = Orig->getDeclContext();
11591 
11592     // Handle enums and anonymous structs.
11593     if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11594     CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11595     while (OrigRec->isAnonymousStructOrUnion())
11596       OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11597 
11598     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11599       if (OrigDC == CurContext) {
11600         Diag(Using->getLocation(),
11601              diag::err_using_decl_nested_name_specifier_is_current_class)
11602           << Using->getQualifierLoc().getSourceRange();
11603         Diag(Orig->getLocation(), diag::note_using_decl_target);
11604         Using->setInvalidDecl();
11605         return true;
11606       }
11607 
11608       Diag(Using->getQualifierLoc().getBeginLoc(),
11609            diag::err_using_decl_nested_name_specifier_is_not_base_class)
11610         << Using->getQualifier()
11611         << cast<CXXRecordDecl>(CurContext)
11612         << Using->getQualifierLoc().getSourceRange();
11613       Diag(Orig->getLocation(), diag::note_using_decl_target);
11614       Using->setInvalidDecl();
11615       return true;
11616     }
11617   }
11618 
11619   if (Previous.empty()) return false;
11620 
11621   NamedDecl *Target = Orig;
11622   if (isa<UsingShadowDecl>(Target))
11623     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11624 
11625   // If the target happens to be one of the previous declarations, we
11626   // don't have a conflict.
11627   //
11628   // FIXME: but we might be increasing its access, in which case we
11629   // should redeclare it.
11630   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11631   bool FoundEquivalentDecl = false;
11632   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11633          I != E; ++I) {
11634     NamedDecl *D = (*I)->getUnderlyingDecl();
11635     // We can have UsingDecls in our Previous results because we use the same
11636     // LookupResult for checking whether the UsingDecl itself is a valid
11637     // redeclaration.
11638     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11639       continue;
11640 
11641     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11642       // C++ [class.mem]p19:
11643       //   If T is the name of a class, then [every named member other than
11644       //   a non-static data member] shall have a name different from T
11645       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11646           !isa<IndirectFieldDecl>(Target) &&
11647           !isa<UnresolvedUsingValueDecl>(Target) &&
11648           DiagnoseClassNameShadow(
11649               CurContext,
11650               DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11651         return true;
11652     }
11653 
11654     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11655       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11656         PrevShadow = Shadow;
11657       FoundEquivalentDecl = true;
11658     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11659       // We don't conflict with an existing using shadow decl of an equivalent
11660       // declaration, but we're not a redeclaration of it.
11661       FoundEquivalentDecl = true;
11662     }
11663 
11664     if (isVisible(D))
11665       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11666   }
11667 
11668   if (FoundEquivalentDecl)
11669     return false;
11670 
11671   if (FunctionDecl *FD = Target->getAsFunction()) {
11672     NamedDecl *OldDecl = nullptr;
11673     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11674                           /*IsForUsingDecl*/ true)) {
11675     case Ovl_Overload:
11676       return false;
11677 
11678     case Ovl_NonFunction:
11679       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11680       break;
11681 
11682     // We found a decl with the exact signature.
11683     case Ovl_Match:
11684       // If we're in a record, we want to hide the target, so we
11685       // return true (without a diagnostic) to tell the caller not to
11686       // build a shadow decl.
11687       if (CurContext->isRecord())
11688         return true;
11689 
11690       // If we're not in a record, this is an error.
11691       Diag(Using->getLocation(), diag::err_using_decl_conflict);
11692       break;
11693     }
11694 
11695     Diag(Target->getLocation(), diag::note_using_decl_target);
11696     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11697     Using->setInvalidDecl();
11698     return true;
11699   }
11700 
11701   // Target is not a function.
11702 
11703   if (isa<TagDecl>(Target)) {
11704     // No conflict between a tag and a non-tag.
11705     if (!Tag) return false;
11706 
11707     Diag(Using->getLocation(), diag::err_using_decl_conflict);
11708     Diag(Target->getLocation(), diag::note_using_decl_target);
11709     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11710     Using->setInvalidDecl();
11711     return true;
11712   }
11713 
11714   // No conflict between a tag and a non-tag.
11715   if (!NonTag) return false;
11716 
11717   Diag(Using->getLocation(), diag::err_using_decl_conflict);
11718   Diag(Target->getLocation(), diag::note_using_decl_target);
11719   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11720   Using->setInvalidDecl();
11721   return true;
11722 }
11723 
11724 /// Determine whether a direct base class is a virtual base class.
11725 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11726   if (!Derived->getNumVBases())
11727     return false;
11728   for (auto &B : Derived->bases())
11729     if (B.getType()->getAsCXXRecordDecl() == Base)
11730       return B.isVirtual();
11731   llvm_unreachable("not a direct base class");
11732 }
11733 
11734 /// Builds a shadow declaration corresponding to a 'using' declaration.
11735 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11736                                             UsingDecl *UD,
11737                                             NamedDecl *Orig,
11738                                             UsingShadowDecl *PrevDecl) {
11739   // If we resolved to another shadow declaration, just coalesce them.
11740   NamedDecl *Target = Orig;
11741   if (isa<UsingShadowDecl>(Target)) {
11742     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11743     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11744   }
11745 
11746   NamedDecl *NonTemplateTarget = Target;
11747   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11748     NonTemplateTarget = TargetTD->getTemplatedDecl();
11749 
11750   UsingShadowDecl *Shadow;
11751   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11752     bool IsVirtualBase =
11753         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11754                             UD->getQualifier()->getAsRecordDecl());
11755     Shadow = ConstructorUsingShadowDecl::Create(
11756         Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11757   } else {
11758     Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11759                                      Target);
11760   }
11761   UD->addShadowDecl(Shadow);
11762 
11763   Shadow->setAccess(UD->getAccess());
11764   if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11765     Shadow->setInvalidDecl();
11766 
11767   Shadow->setPreviousDecl(PrevDecl);
11768 
11769   if (S)
11770     PushOnScopeChains(Shadow, S);
11771   else
11772     CurContext->addDecl(Shadow);
11773 
11774 
11775   return Shadow;
11776 }
11777 
11778 /// Hides a using shadow declaration.  This is required by the current
11779 /// using-decl implementation when a resolvable using declaration in a
11780 /// class is followed by a declaration which would hide or override
11781 /// one or more of the using decl's targets; for example:
11782 ///
11783 ///   struct Base { void foo(int); };
11784 ///   struct Derived : Base {
11785 ///     using Base::foo;
11786 ///     void foo(int);
11787 ///   };
11788 ///
11789 /// The governing language is C++03 [namespace.udecl]p12:
11790 ///
11791 ///   When a using-declaration brings names from a base class into a
11792 ///   derived class scope, member functions in the derived class
11793 ///   override and/or hide member functions with the same name and
11794 ///   parameter types in a base class (rather than conflicting).
11795 ///
11796 /// There are two ways to implement this:
11797 ///   (1) optimistically create shadow decls when they're not hidden
11798 ///       by existing declarations, or
11799 ///   (2) don't create any shadow decls (or at least don't make them
11800 ///       visible) until we've fully parsed/instantiated the class.
11801 /// The problem with (1) is that we might have to retroactively remove
11802 /// a shadow decl, which requires several O(n) operations because the
11803 /// decl structures are (very reasonably) not designed for removal.
11804 /// (2) avoids this but is very fiddly and phase-dependent.
11805 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11806   if (Shadow->getDeclName().getNameKind() ==
11807         DeclarationName::CXXConversionFunctionName)
11808     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11809 
11810   // Remove it from the DeclContext...
11811   Shadow->getDeclContext()->removeDecl(Shadow);
11812 
11813   // ...and the scope, if applicable...
11814   if (S) {
11815     S->RemoveDecl(Shadow);
11816     IdResolver.RemoveDecl(Shadow);
11817   }
11818 
11819   // ...and the using decl.
11820   Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11821 
11822   // TODO: complain somehow if Shadow was used.  It shouldn't
11823   // be possible for this to happen, because...?
11824 }
11825 
11826 /// Find the base specifier for a base class with the given type.
11827 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11828                                                 QualType DesiredBase,
11829                                                 bool &AnyDependentBases) {
11830   // Check whether the named type is a direct base class.
11831   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11832     .getUnqualifiedType();
11833   for (auto &Base : Derived->bases()) {
11834     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11835     if (CanonicalDesiredBase == BaseType)
11836       return &Base;
11837     if (BaseType->isDependentType())
11838       AnyDependentBases = true;
11839   }
11840   return nullptr;
11841 }
11842 
11843 namespace {
11844 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11845 public:
11846   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11847                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11848       : HasTypenameKeyword(HasTypenameKeyword),
11849         IsInstantiation(IsInstantiation), OldNNS(NNS),
11850         RequireMemberOf(RequireMemberOf) {}
11851 
11852   bool ValidateCandidate(const TypoCorrection &Candidate) override {
11853     NamedDecl *ND = Candidate.getCorrectionDecl();
11854 
11855     // Keywords are not valid here.
11856     if (!ND || isa<NamespaceDecl>(ND))
11857       return false;
11858 
11859     // Completely unqualified names are invalid for a 'using' declaration.
11860     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11861       return false;
11862 
11863     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11864     // reject.
11865 
11866     if (RequireMemberOf) {
11867       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11868       if (FoundRecord && FoundRecord->isInjectedClassName()) {
11869         // No-one ever wants a using-declaration to name an injected-class-name
11870         // of a base class, unless they're declaring an inheriting constructor.
11871         ASTContext &Ctx = ND->getASTContext();
11872         if (!Ctx.getLangOpts().CPlusPlus11)
11873           return false;
11874         QualType FoundType = Ctx.getRecordType(FoundRecord);
11875 
11876         // Check that the injected-class-name is named as a member of its own
11877         // type; we don't want to suggest 'using Derived::Base;', since that
11878         // means something else.
11879         NestedNameSpecifier *Specifier =
11880             Candidate.WillReplaceSpecifier()
11881                 ? Candidate.getCorrectionSpecifier()
11882                 : OldNNS;
11883         if (!Specifier->getAsType() ||
11884             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11885           return false;
11886 
11887         // Check that this inheriting constructor declaration actually names a
11888         // direct base class of the current class.
11889         bool AnyDependentBases = false;
11890         if (!findDirectBaseWithType(RequireMemberOf,
11891                                     Ctx.getRecordType(FoundRecord),
11892                                     AnyDependentBases) &&
11893             !AnyDependentBases)
11894           return false;
11895       } else {
11896         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11897         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11898           return false;
11899 
11900         // FIXME: Check that the base class member is accessible?
11901       }
11902     } else {
11903       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11904       if (FoundRecord && FoundRecord->isInjectedClassName())
11905         return false;
11906     }
11907 
11908     if (isa<TypeDecl>(ND))
11909       return HasTypenameKeyword || !IsInstantiation;
11910 
11911     return !HasTypenameKeyword;
11912   }
11913 
11914   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11915     return std::make_unique<UsingValidatorCCC>(*this);
11916   }
11917 
11918 private:
11919   bool HasTypenameKeyword;
11920   bool IsInstantiation;
11921   NestedNameSpecifier *OldNNS;
11922   CXXRecordDecl *RequireMemberOf;
11923 };
11924 } // end anonymous namespace
11925 
11926 /// Builds a using declaration.
11927 ///
11928 /// \param IsInstantiation - Whether this call arises from an
11929 ///   instantiation of an unresolved using declaration.  We treat
11930 ///   the lookup differently for these declarations.
11931 NamedDecl *Sema::BuildUsingDeclaration(
11932     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11933     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11934     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11935     const ParsedAttributesView &AttrList, bool IsInstantiation) {
11936   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11937   SourceLocation IdentLoc = NameInfo.getLoc();
11938   assert(IdentLoc.isValid() && "Invalid TargetName location.");
11939 
11940   // FIXME: We ignore attributes for now.
11941 
11942   // For an inheriting constructor declaration, the name of the using
11943   // declaration is the name of a constructor in this class, not in the
11944   // base class.
11945   DeclarationNameInfo UsingName = NameInfo;
11946   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11947     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11948       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11949           Context.getCanonicalType(Context.getRecordType(RD))));
11950 
11951   // Do the redeclaration lookup in the current scope.
11952   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11953                         ForVisibleRedeclaration);
11954   Previous.setHideTags(false);
11955   if (S) {
11956     LookupName(Previous, S);
11957 
11958     // It is really dumb that we have to do this.
11959     LookupResult::Filter F = Previous.makeFilter();
11960     while (F.hasNext()) {
11961       NamedDecl *D = F.next();
11962       if (!isDeclInScope(D, CurContext, S))
11963         F.erase();
11964       // If we found a local extern declaration that's not ordinarily visible,
11965       // and this declaration is being added to a non-block scope, ignore it.
11966       // We're only checking for scope conflicts here, not also for violations
11967       // of the linkage rules.
11968       else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11969                !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11970         F.erase();
11971     }
11972     F.done();
11973   } else {
11974     assert(IsInstantiation && "no scope in non-instantiation");
11975     if (CurContext->isRecord())
11976       LookupQualifiedName(Previous, CurContext);
11977     else {
11978       // No redeclaration check is needed here; in non-member contexts we
11979       // diagnosed all possible conflicts with other using-declarations when
11980       // building the template:
11981       //
11982       // For a dependent non-type using declaration, the only valid case is
11983       // if we instantiate to a single enumerator. We check for conflicts
11984       // between shadow declarations we introduce, and we check in the template
11985       // definition for conflicts between a non-type using declaration and any
11986       // other declaration, which together covers all cases.
11987       //
11988       // A dependent typename using declaration will never successfully
11989       // instantiate, since it will always name a class member, so we reject
11990       // that in the template definition.
11991     }
11992   }
11993 
11994   // Check for invalid redeclarations.
11995   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
11996                                   SS, IdentLoc, Previous))
11997     return nullptr;
11998 
11999   // Check for bad qualifiers.
12000   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12001                               IdentLoc))
12002     return nullptr;
12003 
12004   DeclContext *LookupContext = computeDeclContext(SS);
12005   NamedDecl *D;
12006   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12007   if (!LookupContext || EllipsisLoc.isValid()) {
12008     if (HasTypenameKeyword) {
12009       // FIXME: not all declaration name kinds are legal here
12010       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12011                                               UsingLoc, TypenameLoc,
12012                                               QualifierLoc,
12013                                               IdentLoc, NameInfo.getName(),
12014                                               EllipsisLoc);
12015     } else {
12016       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12017                                            QualifierLoc, NameInfo, EllipsisLoc);
12018     }
12019     D->setAccess(AS);
12020     CurContext->addDecl(D);
12021     return D;
12022   }
12023 
12024   auto Build = [&](bool Invalid) {
12025     UsingDecl *UD =
12026         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12027                           UsingName, HasTypenameKeyword);
12028     UD->setAccess(AS);
12029     CurContext->addDecl(UD);
12030     UD->setInvalidDecl(Invalid);
12031     return UD;
12032   };
12033   auto BuildInvalid = [&]{ return Build(true); };
12034   auto BuildValid = [&]{ return Build(false); };
12035 
12036   if (RequireCompleteDeclContext(SS, LookupContext))
12037     return BuildInvalid();
12038 
12039   // Look up the target name.
12040   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12041 
12042   // Unlike most lookups, we don't always want to hide tag
12043   // declarations: tag names are visible through the using declaration
12044   // even if hidden by ordinary names, *except* in a dependent context
12045   // where it's important for the sanity of two-phase lookup.
12046   if (!IsInstantiation)
12047     R.setHideTags(false);
12048 
12049   // For the purposes of this lookup, we have a base object type
12050   // equal to that of the current context.
12051   if (CurContext->isRecord()) {
12052     R.setBaseObjectType(
12053                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12054   }
12055 
12056   LookupQualifiedName(R, LookupContext);
12057 
12058   // Try to correct typos if possible. If constructor name lookup finds no
12059   // results, that means the named class has no explicit constructors, and we
12060   // suppressed declaring implicit ones (probably because it's dependent or
12061   // invalid).
12062   if (R.empty() &&
12063       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12064     // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
12065     // it will believe that glibc provides a ::gets in cases where it does not,
12066     // and will try to pull it into namespace std with a using-declaration.
12067     // Just ignore the using-declaration in that case.
12068     auto *II = NameInfo.getName().getAsIdentifierInfo();
12069     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12070         CurContext->isStdNamespace() &&
12071         isa<TranslationUnitDecl>(LookupContext) &&
12072         getSourceManager().isInSystemHeader(UsingLoc))
12073       return nullptr;
12074     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12075                           dyn_cast<CXXRecordDecl>(CurContext));
12076     if (TypoCorrection Corrected =
12077             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12078                         CTK_ErrorRecovery)) {
12079       // We reject candidates where DroppedSpecifier == true, hence the
12080       // literal '0' below.
12081       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12082                                 << NameInfo.getName() << LookupContext << 0
12083                                 << SS.getRange());
12084 
12085       // If we picked a correction with no attached Decl we can't do anything
12086       // useful with it, bail out.
12087       NamedDecl *ND = Corrected.getCorrectionDecl();
12088       if (!ND)
12089         return BuildInvalid();
12090 
12091       // If we corrected to an inheriting constructor, handle it as one.
12092       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12093       if (RD && RD->isInjectedClassName()) {
12094         // The parent of the injected class name is the class itself.
12095         RD = cast<CXXRecordDecl>(RD->getParent());
12096 
12097         // Fix up the information we'll use to build the using declaration.
12098         if (Corrected.WillReplaceSpecifier()) {
12099           NestedNameSpecifierLocBuilder Builder;
12100           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12101                               QualifierLoc.getSourceRange());
12102           QualifierLoc = Builder.getWithLocInContext(Context);
12103         }
12104 
12105         // In this case, the name we introduce is the name of a derived class
12106         // constructor.
12107         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12108         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12109             Context.getCanonicalType(Context.getRecordType(CurClass))));
12110         UsingName.setNamedTypeInfo(nullptr);
12111         for (auto *Ctor : LookupConstructors(RD))
12112           R.addDecl(Ctor);
12113         R.resolveKind();
12114       } else {
12115         // FIXME: Pick up all the declarations if we found an overloaded
12116         // function.
12117         UsingName.setName(ND->getDeclName());
12118         R.addDecl(ND);
12119       }
12120     } else {
12121       Diag(IdentLoc, diag::err_no_member)
12122         << NameInfo.getName() << LookupContext << SS.getRange();
12123       return BuildInvalid();
12124     }
12125   }
12126 
12127   if (R.isAmbiguous())
12128     return BuildInvalid();
12129 
12130   if (HasTypenameKeyword) {
12131     // If we asked for a typename and got a non-type decl, error out.
12132     if (!R.getAsSingle<TypeDecl>()) {
12133       Diag(IdentLoc, diag::err_using_typename_non_type);
12134       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12135         Diag((*I)->getUnderlyingDecl()->getLocation(),
12136              diag::note_using_decl_target);
12137       return BuildInvalid();
12138     }
12139   } else {
12140     // If we asked for a non-typename and we got a type, error out,
12141     // but only if this is an instantiation of an unresolved using
12142     // decl.  Otherwise just silently find the type name.
12143     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12144       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12145       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12146       return BuildInvalid();
12147     }
12148   }
12149 
12150   // C++14 [namespace.udecl]p6:
12151   // A using-declaration shall not name a namespace.
12152   if (R.getAsSingle<NamespaceDecl>()) {
12153     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12154       << SS.getRange();
12155     return BuildInvalid();
12156   }
12157 
12158   // C++14 [namespace.udecl]p7:
12159   // A using-declaration shall not name a scoped enumerator.
12160   if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12161     if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12162       Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12163         << SS.getRange();
12164       return BuildInvalid();
12165     }
12166   }
12167 
12168   UsingDecl *UD = BuildValid();
12169 
12170   // Some additional rules apply to inheriting constructors.
12171   if (UsingName.getName().getNameKind() ==
12172         DeclarationName::CXXConstructorName) {
12173     // Suppress access diagnostics; the access check is instead performed at the
12174     // point of use for an inheriting constructor.
12175     R.suppressDiagnostics();
12176     if (CheckInheritingConstructorUsingDecl(UD))
12177       return UD;
12178   }
12179 
12180   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12181     UsingShadowDecl *PrevDecl = nullptr;
12182     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12183       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12184   }
12185 
12186   return UD;
12187 }
12188 
12189 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12190                                     ArrayRef<NamedDecl *> Expansions) {
12191   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12192          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12193          isa<UsingPackDecl>(InstantiatedFrom));
12194 
12195   auto *UPD =
12196       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12197   UPD->setAccess(InstantiatedFrom->getAccess());
12198   CurContext->addDecl(UPD);
12199   return UPD;
12200 }
12201 
12202 /// Additional checks for a using declaration referring to a constructor name.
12203 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12204   assert(!UD->hasTypename() && "expecting a constructor name");
12205 
12206   const Type *SourceType = UD->getQualifier()->getAsType();
12207   assert(SourceType &&
12208          "Using decl naming constructor doesn't have type in scope spec.");
12209   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12210 
12211   // Check whether the named type is a direct base class.
12212   bool AnyDependentBases = false;
12213   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12214                                       AnyDependentBases);
12215   if (!Base && !AnyDependentBases) {
12216     Diag(UD->getUsingLoc(),
12217          diag::err_using_decl_constructor_not_in_direct_base)
12218       << UD->getNameInfo().getSourceRange()
12219       << QualType(SourceType, 0) << TargetClass;
12220     UD->setInvalidDecl();
12221     return true;
12222   }
12223 
12224   if (Base)
12225     Base->setInheritConstructors();
12226 
12227   return false;
12228 }
12229 
12230 /// Checks that the given using declaration is not an invalid
12231 /// redeclaration.  Note that this is checking only for the using decl
12232 /// itself, not for any ill-formedness among the UsingShadowDecls.
12233 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12234                                        bool HasTypenameKeyword,
12235                                        const CXXScopeSpec &SS,
12236                                        SourceLocation NameLoc,
12237                                        const LookupResult &Prev) {
12238   NestedNameSpecifier *Qual = SS.getScopeRep();
12239 
12240   // C++03 [namespace.udecl]p8:
12241   // C++0x [namespace.udecl]p10:
12242   //   A using-declaration is a declaration and can therefore be used
12243   //   repeatedly where (and only where) multiple declarations are
12244   //   allowed.
12245   //
12246   // That's in non-member contexts.
12247   if (!CurContext->getRedeclContext()->isRecord()) {
12248     // A dependent qualifier outside a class can only ever resolve to an
12249     // enumeration type. Therefore it conflicts with any other non-type
12250     // declaration in the same scope.
12251     // FIXME: How should we check for dependent type-type conflicts at block
12252     // scope?
12253     if (Qual->isDependent() && !HasTypenameKeyword) {
12254       for (auto *D : Prev) {
12255         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12256           bool OldCouldBeEnumerator =
12257               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12258           Diag(NameLoc,
12259                OldCouldBeEnumerator ? diag::err_redefinition
12260                                     : diag::err_redefinition_different_kind)
12261               << Prev.getLookupName();
12262           Diag(D->getLocation(), diag::note_previous_definition);
12263           return true;
12264         }
12265       }
12266     }
12267     return false;
12268   }
12269 
12270   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12271     NamedDecl *D = *I;
12272 
12273     bool DTypename;
12274     NestedNameSpecifier *DQual;
12275     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12276       DTypename = UD->hasTypename();
12277       DQual = UD->getQualifier();
12278     } else if (UnresolvedUsingValueDecl *UD
12279                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12280       DTypename = false;
12281       DQual = UD->getQualifier();
12282     } else if (UnresolvedUsingTypenameDecl *UD
12283                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12284       DTypename = true;
12285       DQual = UD->getQualifier();
12286     } else continue;
12287 
12288     // using decls differ if one says 'typename' and the other doesn't.
12289     // FIXME: non-dependent using decls?
12290     if (HasTypenameKeyword != DTypename) continue;
12291 
12292     // using decls differ if they name different scopes (but note that
12293     // template instantiation can cause this check to trigger when it
12294     // didn't before instantiation).
12295     if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12296         Context.getCanonicalNestedNameSpecifier(DQual))
12297       continue;
12298 
12299     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12300     Diag(D->getLocation(), diag::note_using_decl) << 1;
12301     return true;
12302   }
12303 
12304   return false;
12305 }
12306 
12307 
12308 /// Checks that the given nested-name qualifier used in a using decl
12309 /// in the current context is appropriately related to the current
12310 /// scope.  If an error is found, diagnoses it and returns true.
12311 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12312                                    bool HasTypename,
12313                                    const CXXScopeSpec &SS,
12314                                    const DeclarationNameInfo &NameInfo,
12315                                    SourceLocation NameLoc) {
12316   DeclContext *NamedContext = computeDeclContext(SS);
12317 
12318   if (!CurContext->isRecord()) {
12319     // C++03 [namespace.udecl]p3:
12320     // C++0x [namespace.udecl]p8:
12321     //   A using-declaration for a class member shall be a member-declaration.
12322 
12323     // If we weren't able to compute a valid scope, it might validly be a
12324     // dependent class scope or a dependent enumeration unscoped scope. If
12325     // we have a 'typename' keyword, the scope must resolve to a class type.
12326     if ((HasTypename && !NamedContext) ||
12327         (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12328       auto *RD = NamedContext
12329                      ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12330                      : nullptr;
12331       if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12332         RD = nullptr;
12333 
12334       Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12335         << SS.getRange();
12336 
12337       // If we have a complete, non-dependent source type, try to suggest a
12338       // way to get the same effect.
12339       if (!RD)
12340         return true;
12341 
12342       // Find what this using-declaration was referring to.
12343       LookupResult R(*this, NameInfo, LookupOrdinaryName);
12344       R.setHideTags(false);
12345       R.suppressDiagnostics();
12346       LookupQualifiedName(R, RD);
12347 
12348       if (R.getAsSingle<TypeDecl>()) {
12349         if (getLangOpts().CPlusPlus11) {
12350           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12351           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12352             << 0 // alias declaration
12353             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12354                                           NameInfo.getName().getAsString() +
12355                                               " = ");
12356         } else {
12357           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12358           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12359           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12360             << 1 // typedef declaration
12361             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12362             << FixItHint::CreateInsertion(
12363                    InsertLoc, " " + NameInfo.getName().getAsString());
12364         }
12365       } else if (R.getAsSingle<VarDecl>()) {
12366         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12367         // repeating the type of the static data member here.
12368         FixItHint FixIt;
12369         if (getLangOpts().CPlusPlus11) {
12370           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12371           FixIt = FixItHint::CreateReplacement(
12372               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12373         }
12374 
12375         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12376           << 2 // reference declaration
12377           << FixIt;
12378       } else if (R.getAsSingle<EnumConstantDecl>()) {
12379         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12380         // repeating the type of the enumeration here, and we can't do so if
12381         // the type is anonymous.
12382         FixItHint FixIt;
12383         if (getLangOpts().CPlusPlus11) {
12384           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12385           FixIt = FixItHint::CreateReplacement(
12386               UsingLoc,
12387               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12388         }
12389 
12390         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12391           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12392           << FixIt;
12393       }
12394       return true;
12395     }
12396 
12397     // Otherwise, this might be valid.
12398     return false;
12399   }
12400 
12401   // The current scope is a record.
12402 
12403   // If the named context is dependent, we can't decide much.
12404   if (!NamedContext) {
12405     // FIXME: in C++0x, we can diagnose if we can prove that the
12406     // nested-name-specifier does not refer to a base class, which is
12407     // still possible in some cases.
12408 
12409     // Otherwise we have to conservatively report that things might be
12410     // okay.
12411     return false;
12412   }
12413 
12414   if (!NamedContext->isRecord()) {
12415     // Ideally this would point at the last name in the specifier,
12416     // but we don't have that level of source info.
12417     Diag(SS.getRange().getBegin(),
12418          diag::err_using_decl_nested_name_specifier_is_not_class)
12419       << SS.getScopeRep() << SS.getRange();
12420     return true;
12421   }
12422 
12423   if (!NamedContext->isDependentContext() &&
12424       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12425     return true;
12426 
12427   if (getLangOpts().CPlusPlus11) {
12428     // C++11 [namespace.udecl]p3:
12429     //   In a using-declaration used as a member-declaration, the
12430     //   nested-name-specifier shall name a base class of the class
12431     //   being defined.
12432 
12433     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12434                                  cast<CXXRecordDecl>(NamedContext))) {
12435       if (CurContext == NamedContext) {
12436         Diag(NameLoc,
12437              diag::err_using_decl_nested_name_specifier_is_current_class)
12438           << SS.getRange();
12439         return true;
12440       }
12441 
12442       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12443         Diag(SS.getRange().getBegin(),
12444              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12445           << SS.getScopeRep()
12446           << cast<CXXRecordDecl>(CurContext)
12447           << SS.getRange();
12448       }
12449       return true;
12450     }
12451 
12452     return false;
12453   }
12454 
12455   // C++03 [namespace.udecl]p4:
12456   //   A using-declaration used as a member-declaration shall refer
12457   //   to a member of a base class of the class being defined [etc.].
12458 
12459   // Salient point: SS doesn't have to name a base class as long as
12460   // lookup only finds members from base classes.  Therefore we can
12461   // diagnose here only if we can prove that that can't happen,
12462   // i.e. if the class hierarchies provably don't intersect.
12463 
12464   // TODO: it would be nice if "definitely valid" results were cached
12465   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12466   // need to be repeated.
12467 
12468   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12469   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12470     Bases.insert(Base);
12471     return true;
12472   };
12473 
12474   // Collect all bases. Return false if we find a dependent base.
12475   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12476     return false;
12477 
12478   // Returns true if the base is dependent or is one of the accumulated base
12479   // classes.
12480   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12481     return !Bases.count(Base);
12482   };
12483 
12484   // Return false if the class has a dependent base or if it or one
12485   // of its bases is present in the base set of the current context.
12486   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12487       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12488     return false;
12489 
12490   Diag(SS.getRange().getBegin(),
12491        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12492     << SS.getScopeRep()
12493     << cast<CXXRecordDecl>(CurContext)
12494     << SS.getRange();
12495 
12496   return true;
12497 }
12498 
12499 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12500                                   MultiTemplateParamsArg TemplateParamLists,
12501                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12502                                   const ParsedAttributesView &AttrList,
12503                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12504   // Skip up to the relevant declaration scope.
12505   while (S->isTemplateParamScope())
12506     S = S->getParent();
12507   assert((S->getFlags() & Scope::DeclScope) &&
12508          "got alias-declaration outside of declaration scope");
12509 
12510   if (Type.isInvalid())
12511     return nullptr;
12512 
12513   bool Invalid = false;
12514   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12515   TypeSourceInfo *TInfo = nullptr;
12516   GetTypeFromParser(Type.get(), &TInfo);
12517 
12518   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12519     return nullptr;
12520 
12521   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12522                                       UPPC_DeclarationType)) {
12523     Invalid = true;
12524     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12525                                              TInfo->getTypeLoc().getBeginLoc());
12526   }
12527 
12528   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12529                         TemplateParamLists.size()
12530                             ? forRedeclarationInCurContext()
12531                             : ForVisibleRedeclaration);
12532   LookupName(Previous, S);
12533 
12534   // Warn about shadowing the name of a template parameter.
12535   if (Previous.isSingleResult() &&
12536       Previous.getFoundDecl()->isTemplateParameter()) {
12537     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12538     Previous.clear();
12539   }
12540 
12541   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12542          "name in alias declaration must be an identifier");
12543   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12544                                                Name.StartLocation,
12545                                                Name.Identifier, TInfo);
12546 
12547   NewTD->setAccess(AS);
12548 
12549   if (Invalid)
12550     NewTD->setInvalidDecl();
12551 
12552   ProcessDeclAttributeList(S, NewTD, AttrList);
12553   AddPragmaAttributes(S, NewTD);
12554 
12555   CheckTypedefForVariablyModifiedType(S, NewTD);
12556   Invalid |= NewTD->isInvalidDecl();
12557 
12558   bool Redeclaration = false;
12559 
12560   NamedDecl *NewND;
12561   if (TemplateParamLists.size()) {
12562     TypeAliasTemplateDecl *OldDecl = nullptr;
12563     TemplateParameterList *OldTemplateParams = nullptr;
12564 
12565     if (TemplateParamLists.size() != 1) {
12566       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12567         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12568          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12569     }
12570     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12571 
12572     // Check that we can declare a template here.
12573     if (CheckTemplateDeclScope(S, TemplateParams))
12574       return nullptr;
12575 
12576     // Only consider previous declarations in the same scope.
12577     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12578                          /*ExplicitInstantiationOrSpecialization*/false);
12579     if (!Previous.empty()) {
12580       Redeclaration = true;
12581 
12582       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12583       if (!OldDecl && !Invalid) {
12584         Diag(UsingLoc, diag::err_redefinition_different_kind)
12585           << Name.Identifier;
12586 
12587         NamedDecl *OldD = Previous.getRepresentativeDecl();
12588         if (OldD->getLocation().isValid())
12589           Diag(OldD->getLocation(), diag::note_previous_definition);
12590 
12591         Invalid = true;
12592       }
12593 
12594       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12595         if (TemplateParameterListsAreEqual(TemplateParams,
12596                                            OldDecl->getTemplateParameters(),
12597                                            /*Complain=*/true,
12598                                            TPL_TemplateMatch))
12599           OldTemplateParams =
12600               OldDecl->getMostRecentDecl()->getTemplateParameters();
12601         else
12602           Invalid = true;
12603 
12604         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12605         if (!Invalid &&
12606             !Context.hasSameType(OldTD->getUnderlyingType(),
12607                                  NewTD->getUnderlyingType())) {
12608           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12609           // but we can't reasonably accept it.
12610           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12611             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12612           if (OldTD->getLocation().isValid())
12613             Diag(OldTD->getLocation(), diag::note_previous_definition);
12614           Invalid = true;
12615         }
12616       }
12617     }
12618 
12619     // Merge any previous default template arguments into our parameters,
12620     // and check the parameter list.
12621     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12622                                    TPC_TypeAliasTemplate))
12623       return nullptr;
12624 
12625     TypeAliasTemplateDecl *NewDecl =
12626       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12627                                     Name.Identifier, TemplateParams,
12628                                     NewTD);
12629     NewTD->setDescribedAliasTemplate(NewDecl);
12630 
12631     NewDecl->setAccess(AS);
12632 
12633     if (Invalid)
12634       NewDecl->setInvalidDecl();
12635     else if (OldDecl) {
12636       NewDecl->setPreviousDecl(OldDecl);
12637       CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12638     }
12639 
12640     NewND = NewDecl;
12641   } else {
12642     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12643       setTagNameForLinkagePurposes(TD, NewTD);
12644       handleTagNumbering(TD, S);
12645     }
12646     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12647     NewND = NewTD;
12648   }
12649 
12650   PushOnScopeChains(NewND, S);
12651   ActOnDocumentableDecl(NewND);
12652   return NewND;
12653 }
12654 
12655 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12656                                    SourceLocation AliasLoc,
12657                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
12658                                    SourceLocation IdentLoc,
12659                                    IdentifierInfo *Ident) {
12660 
12661   // Lookup the namespace name.
12662   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12663   LookupParsedName(R, S, &SS);
12664 
12665   if (R.isAmbiguous())
12666     return nullptr;
12667 
12668   if (R.empty()) {
12669     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12670       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12671       return nullptr;
12672     }
12673   }
12674   assert(!R.isAmbiguous() && !R.empty());
12675   NamedDecl *ND = R.getRepresentativeDecl();
12676 
12677   // Check if we have a previous declaration with the same name.
12678   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12679                      ForVisibleRedeclaration);
12680   LookupName(PrevR, S);
12681 
12682   // Check we're not shadowing a template parameter.
12683   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12684     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12685     PrevR.clear();
12686   }
12687 
12688   // Filter out any other lookup result from an enclosing scope.
12689   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12690                        /*AllowInlineNamespace*/false);
12691 
12692   // Find the previous declaration and check that we can redeclare it.
12693   NamespaceAliasDecl *Prev = nullptr;
12694   if (PrevR.isSingleResult()) {
12695     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12696     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12697       // We already have an alias with the same name that points to the same
12698       // namespace; check that it matches.
12699       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12700         Prev = AD;
12701       } else if (isVisible(PrevDecl)) {
12702         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12703           << Alias;
12704         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12705           << AD->getNamespace();
12706         return nullptr;
12707       }
12708     } else if (isVisible(PrevDecl)) {
12709       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12710                             ? diag::err_redefinition
12711                             : diag::err_redefinition_different_kind;
12712       Diag(AliasLoc, DiagID) << Alias;
12713       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12714       return nullptr;
12715     }
12716   }
12717 
12718   // The use of a nested name specifier may trigger deprecation warnings.
12719   DiagnoseUseOfDecl(ND, IdentLoc);
12720 
12721   NamespaceAliasDecl *AliasDecl =
12722     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12723                                Alias, SS.getWithLocInContext(Context),
12724                                IdentLoc, ND);
12725   if (Prev)
12726     AliasDecl->setPreviousDecl(Prev);
12727 
12728   PushOnScopeChains(AliasDecl, S);
12729   return AliasDecl;
12730 }
12731 
12732 namespace {
12733 struct SpecialMemberExceptionSpecInfo
12734     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12735   SourceLocation Loc;
12736   Sema::ImplicitExceptionSpecification ExceptSpec;
12737 
12738   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12739                                  Sema::CXXSpecialMember CSM,
12740                                  Sema::InheritedConstructorInfo *ICI,
12741                                  SourceLocation Loc)
12742       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12743 
12744   bool visitBase(CXXBaseSpecifier *Base);
12745   bool visitField(FieldDecl *FD);
12746 
12747   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12748                            unsigned Quals);
12749 
12750   void visitSubobjectCall(Subobject Subobj,
12751                           Sema::SpecialMemberOverloadResult SMOR);
12752 };
12753 }
12754 
12755 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12756   auto *RT = Base->getType()->getAs<RecordType>();
12757   if (!RT)
12758     return false;
12759 
12760   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12761   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12762   if (auto *BaseCtor = SMOR.getMethod()) {
12763     visitSubobjectCall(Base, BaseCtor);
12764     return false;
12765   }
12766 
12767   visitClassSubobject(BaseClass, Base, 0);
12768   return false;
12769 }
12770 
12771 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12772   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12773     Expr *E = FD->getInClassInitializer();
12774     if (!E)
12775       // FIXME: It's a little wasteful to build and throw away a
12776       // CXXDefaultInitExpr here.
12777       // FIXME: We should have a single context note pointing at Loc, and
12778       // this location should be MD->getLocation() instead, since that's
12779       // the location where we actually use the default init expression.
12780       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12781     if (E)
12782       ExceptSpec.CalledExpr(E);
12783   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12784                             ->getAs<RecordType>()) {
12785     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12786                         FD->getType().getCVRQualifiers());
12787   }
12788   return false;
12789 }
12790 
12791 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12792                                                          Subobject Subobj,
12793                                                          unsigned Quals) {
12794   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12795   bool IsMutable = Field && Field->isMutable();
12796   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12797 }
12798 
12799 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12800     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12801   // Note, if lookup fails, it doesn't matter what exception specification we
12802   // choose because the special member will be deleted.
12803   if (CXXMethodDecl *MD = SMOR.getMethod())
12804     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12805 }
12806 
12807 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12808   llvm::APSInt Result;
12809   ExprResult Converted = CheckConvertedConstantExpression(
12810       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12811   ExplicitSpec.setExpr(Converted.get());
12812   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12813     ExplicitSpec.setKind(Result.getBoolValue()
12814                              ? ExplicitSpecKind::ResolvedTrue
12815                              : ExplicitSpecKind::ResolvedFalse);
12816     return true;
12817   }
12818   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12819   return false;
12820 }
12821 
12822 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12823   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12824   if (!ExplicitExpr->isTypeDependent())
12825     tryResolveExplicitSpecifier(ES);
12826   return ES;
12827 }
12828 
12829 static Sema::ImplicitExceptionSpecification
12830 ComputeDefaultedSpecialMemberExceptionSpec(
12831     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12832     Sema::InheritedConstructorInfo *ICI) {
12833   ComputingExceptionSpec CES(S, MD, Loc);
12834 
12835   CXXRecordDecl *ClassDecl = MD->getParent();
12836 
12837   // C++ [except.spec]p14:
12838   //   An implicitly declared special member function (Clause 12) shall have an
12839   //   exception-specification. [...]
12840   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12841   if (ClassDecl->isInvalidDecl())
12842     return Info.ExceptSpec;
12843 
12844   // FIXME: If this diagnostic fires, we're probably missing a check for
12845   // attempting to resolve an exception specification before it's known
12846   // at a higher level.
12847   if (S.RequireCompleteType(MD->getLocation(),
12848                             S.Context.getRecordType(ClassDecl),
12849                             diag::err_exception_spec_incomplete_type))
12850     return Info.ExceptSpec;
12851 
12852   // C++1z [except.spec]p7:
12853   //   [Look for exceptions thrown by] a constructor selected [...] to
12854   //   initialize a potentially constructed subobject,
12855   // C++1z [except.spec]p8:
12856   //   The exception specification for an implicitly-declared destructor, or a
12857   //   destructor without a noexcept-specifier, is potentially-throwing if and
12858   //   only if any of the destructors for any of its potentially constructed
12859   //   subojects is potentially throwing.
12860   // FIXME: We respect the first rule but ignore the "potentially constructed"
12861   // in the second rule to resolve a core issue (no number yet) that would have
12862   // us reject:
12863   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12864   //   struct B : A {};
12865   //   struct C : B { void f(); };
12866   // ... due to giving B::~B() a non-throwing exception specification.
12867   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12868                                 : Info.VisitAllBases);
12869 
12870   return Info.ExceptSpec;
12871 }
12872 
12873 namespace {
12874 /// RAII object to register a special member as being currently declared.
12875 struct DeclaringSpecialMember {
12876   Sema &S;
12877   Sema::SpecialMemberDecl D;
12878   Sema::ContextRAII SavedContext;
12879   bool WasAlreadyBeingDeclared;
12880 
12881   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12882       : S(S), D(RD, CSM), SavedContext(S, RD) {
12883     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12884     if (WasAlreadyBeingDeclared)
12885       // This almost never happens, but if it does, ensure that our cache
12886       // doesn't contain a stale result.
12887       S.SpecialMemberCache.clear();
12888     else {
12889       // Register a note to be produced if we encounter an error while
12890       // declaring the special member.
12891       Sema::CodeSynthesisContext Ctx;
12892       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12893       // FIXME: We don't have a location to use here. Using the class's
12894       // location maintains the fiction that we declare all special members
12895       // with the class, but (1) it's not clear that lying about that helps our
12896       // users understand what's going on, and (2) there may be outer contexts
12897       // on the stack (some of which are relevant) and printing them exposes
12898       // our lies.
12899       Ctx.PointOfInstantiation = RD->getLocation();
12900       Ctx.Entity = RD;
12901       Ctx.SpecialMember = CSM;
12902       S.pushCodeSynthesisContext(Ctx);
12903     }
12904   }
12905   ~DeclaringSpecialMember() {
12906     if (!WasAlreadyBeingDeclared) {
12907       S.SpecialMembersBeingDeclared.erase(D);
12908       S.popCodeSynthesisContext();
12909     }
12910   }
12911 
12912   /// Are we already trying to declare this special member?
12913   bool isAlreadyBeingDeclared() const {
12914     return WasAlreadyBeingDeclared;
12915   }
12916 };
12917 }
12918 
12919 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12920   // Look up any existing declarations, but don't trigger declaration of all
12921   // implicit special members with this name.
12922   DeclarationName Name = FD->getDeclName();
12923   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12924                  ForExternalRedeclaration);
12925   for (auto *D : FD->getParent()->lookup(Name))
12926     if (auto *Acceptable = R.getAcceptableDecl(D))
12927       R.addDecl(Acceptable);
12928   R.resolveKind();
12929   R.suppressDiagnostics();
12930 
12931   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12932 }
12933 
12934 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12935                                           QualType ResultTy,
12936                                           ArrayRef<QualType> Args) {
12937   // Build an exception specification pointing back at this constructor.
12938   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12939 
12940   LangAS AS = getDefaultCXXMethodAddrSpace();
12941   if (AS != LangAS::Default) {
12942     EPI.TypeQuals.addAddressSpace(AS);
12943   }
12944 
12945   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12946   SpecialMem->setType(QT);
12947 }
12948 
12949 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12950                                                      CXXRecordDecl *ClassDecl) {
12951   // C++ [class.ctor]p5:
12952   //   A default constructor for a class X is a constructor of class X
12953   //   that can be called without an argument. If there is no
12954   //   user-declared constructor for class X, a default constructor is
12955   //   implicitly declared. An implicitly-declared default constructor
12956   //   is an inline public member of its class.
12957   assert(ClassDecl->needsImplicitDefaultConstructor() &&
12958          "Should not build implicit default constructor!");
12959 
12960   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12961   if (DSM.isAlreadyBeingDeclared())
12962     return nullptr;
12963 
12964   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12965                                                      CXXDefaultConstructor,
12966                                                      false);
12967 
12968   // Create the actual constructor declaration.
12969   CanQualType ClassType
12970     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12971   SourceLocation ClassLoc = ClassDecl->getLocation();
12972   DeclarationName Name
12973     = Context.DeclarationNames.getCXXConstructorName(ClassType);
12974   DeclarationNameInfo NameInfo(Name, ClassLoc);
12975   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12976       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12977       /*TInfo=*/nullptr, ExplicitSpecifier(),
12978       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12979       Constexpr ? ConstexprSpecKind::Constexpr
12980                 : ConstexprSpecKind::Unspecified);
12981   DefaultCon->setAccess(AS_public);
12982   DefaultCon->setDefaulted();
12983 
12984   if (getLangOpts().CUDA) {
12985     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
12986                                             DefaultCon,
12987                                             /* ConstRHS */ false,
12988                                             /* Diagnose */ false);
12989   }
12990 
12991   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
12992 
12993   // We don't need to use SpecialMemberIsTrivial here; triviality for default
12994   // constructors is easy to compute.
12995   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
12996 
12997   // Note that we have declared this constructor.
12998   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
12999 
13000   Scope *S = getScopeForContext(ClassDecl);
13001   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13002 
13003   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13004     SetDeclDeleted(DefaultCon, ClassLoc);
13005 
13006   if (S)
13007     PushOnScopeChains(DefaultCon, S, false);
13008   ClassDecl->addDecl(DefaultCon);
13009 
13010   return DefaultCon;
13011 }
13012 
13013 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13014                                             CXXConstructorDecl *Constructor) {
13015   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13016           !Constructor->doesThisDeclarationHaveABody() &&
13017           !Constructor->isDeleted()) &&
13018     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13019   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13020     return;
13021 
13022   CXXRecordDecl *ClassDecl = Constructor->getParent();
13023   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13024 
13025   SynthesizedFunctionScope Scope(*this, Constructor);
13026 
13027   // The exception specification is needed because we are defining the
13028   // function.
13029   ResolveExceptionSpec(CurrentLocation,
13030                        Constructor->getType()->castAs<FunctionProtoType>());
13031   MarkVTableUsed(CurrentLocation, ClassDecl);
13032 
13033   // Add a context note for diagnostics produced after this point.
13034   Scope.addContextNote(CurrentLocation);
13035 
13036   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13037     Constructor->setInvalidDecl();
13038     return;
13039   }
13040 
13041   SourceLocation Loc = Constructor->getEndLoc().isValid()
13042                            ? Constructor->getEndLoc()
13043                            : Constructor->getLocation();
13044   Constructor->setBody(new (Context) CompoundStmt(Loc));
13045   Constructor->markUsed(Context);
13046 
13047   if (ASTMutationListener *L = getASTMutationListener()) {
13048     L->CompletedImplicitDefinition(Constructor);
13049   }
13050 
13051   DiagnoseUninitializedFields(*this, Constructor);
13052 }
13053 
13054 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13055   // Perform any delayed checks on exception specifications.
13056   CheckDelayedMemberExceptionSpecs();
13057 }
13058 
13059 /// Find or create the fake constructor we synthesize to model constructing an
13060 /// object of a derived class via a constructor of a base class.
13061 CXXConstructorDecl *
13062 Sema::findInheritingConstructor(SourceLocation Loc,
13063                                 CXXConstructorDecl *BaseCtor,
13064                                 ConstructorUsingShadowDecl *Shadow) {
13065   CXXRecordDecl *Derived = Shadow->getParent();
13066   SourceLocation UsingLoc = Shadow->getLocation();
13067 
13068   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13069   // For now we use the name of the base class constructor as a member of the
13070   // derived class to indicate a (fake) inherited constructor name.
13071   DeclarationName Name = BaseCtor->getDeclName();
13072 
13073   // Check to see if we already have a fake constructor for this inherited
13074   // constructor call.
13075   for (NamedDecl *Ctor : Derived->lookup(Name))
13076     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13077                                ->getInheritedConstructor()
13078                                .getConstructor(),
13079                            BaseCtor))
13080       return cast<CXXConstructorDecl>(Ctor);
13081 
13082   DeclarationNameInfo NameInfo(Name, UsingLoc);
13083   TypeSourceInfo *TInfo =
13084       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13085   FunctionProtoTypeLoc ProtoLoc =
13086       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13087 
13088   // Check the inherited constructor is valid and find the list of base classes
13089   // from which it was inherited.
13090   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13091 
13092   bool Constexpr =
13093       BaseCtor->isConstexpr() &&
13094       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13095                                         false, BaseCtor, &ICI);
13096 
13097   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13098       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13099       BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13100       /*isImplicitlyDeclared=*/true,
13101       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13102       InheritedConstructor(Shadow, BaseCtor),
13103       BaseCtor->getTrailingRequiresClause());
13104   if (Shadow->isInvalidDecl())
13105     DerivedCtor->setInvalidDecl();
13106 
13107   // Build an unevaluated exception specification for this fake constructor.
13108   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13109   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13110   EPI.ExceptionSpec.Type = EST_Unevaluated;
13111   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13112   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13113                                                FPT->getParamTypes(), EPI));
13114 
13115   // Build the parameter declarations.
13116   SmallVector<ParmVarDecl *, 16> ParamDecls;
13117   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13118     TypeSourceInfo *TInfo =
13119         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13120     ParmVarDecl *PD = ParmVarDecl::Create(
13121         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13122         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13123     PD->setScopeInfo(0, I);
13124     PD->setImplicit();
13125     // Ensure attributes are propagated onto parameters (this matters for
13126     // format, pass_object_size, ...).
13127     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13128     ParamDecls.push_back(PD);
13129     ProtoLoc.setParam(I, PD);
13130   }
13131 
13132   // Set up the new constructor.
13133   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13134   DerivedCtor->setAccess(BaseCtor->getAccess());
13135   DerivedCtor->setParams(ParamDecls);
13136   Derived->addDecl(DerivedCtor);
13137 
13138   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13139     SetDeclDeleted(DerivedCtor, UsingLoc);
13140 
13141   return DerivedCtor;
13142 }
13143 
13144 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13145   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13146                                Ctor->getInheritedConstructor().getShadowDecl());
13147   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13148                             /*Diagnose*/true);
13149 }
13150 
13151 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13152                                        CXXConstructorDecl *Constructor) {
13153   CXXRecordDecl *ClassDecl = Constructor->getParent();
13154   assert(Constructor->getInheritedConstructor() &&
13155          !Constructor->doesThisDeclarationHaveABody() &&
13156          !Constructor->isDeleted());
13157   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13158     return;
13159 
13160   // Initializations are performed "as if by a defaulted default constructor",
13161   // so enter the appropriate scope.
13162   SynthesizedFunctionScope Scope(*this, Constructor);
13163 
13164   // The exception specification is needed because we are defining the
13165   // function.
13166   ResolveExceptionSpec(CurrentLocation,
13167                        Constructor->getType()->castAs<FunctionProtoType>());
13168   MarkVTableUsed(CurrentLocation, ClassDecl);
13169 
13170   // Add a context note for diagnostics produced after this point.
13171   Scope.addContextNote(CurrentLocation);
13172 
13173   ConstructorUsingShadowDecl *Shadow =
13174       Constructor->getInheritedConstructor().getShadowDecl();
13175   CXXConstructorDecl *InheritedCtor =
13176       Constructor->getInheritedConstructor().getConstructor();
13177 
13178   // [class.inhctor.init]p1:
13179   //   initialization proceeds as if a defaulted default constructor is used to
13180   //   initialize the D object and each base class subobject from which the
13181   //   constructor was inherited
13182 
13183   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13184   CXXRecordDecl *RD = Shadow->getParent();
13185   SourceLocation InitLoc = Shadow->getLocation();
13186 
13187   // Build explicit initializers for all base classes from which the
13188   // constructor was inherited.
13189   SmallVector<CXXCtorInitializer*, 8> Inits;
13190   for (bool VBase : {false, true}) {
13191     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13192       if (B.isVirtual() != VBase)
13193         continue;
13194 
13195       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13196       if (!BaseRD)
13197         continue;
13198 
13199       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13200       if (!BaseCtor.first)
13201         continue;
13202 
13203       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13204       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13205           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13206 
13207       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13208       Inits.push_back(new (Context) CXXCtorInitializer(
13209           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13210           SourceLocation()));
13211     }
13212   }
13213 
13214   // We now proceed as if for a defaulted default constructor, with the relevant
13215   // initializers replaced.
13216 
13217   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13218     Constructor->setInvalidDecl();
13219     return;
13220   }
13221 
13222   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13223   Constructor->markUsed(Context);
13224 
13225   if (ASTMutationListener *L = getASTMutationListener()) {
13226     L->CompletedImplicitDefinition(Constructor);
13227   }
13228 
13229   DiagnoseUninitializedFields(*this, Constructor);
13230 }
13231 
13232 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13233   // C++ [class.dtor]p2:
13234   //   If a class has no user-declared destructor, a destructor is
13235   //   declared implicitly. An implicitly-declared destructor is an
13236   //   inline public member of its class.
13237   assert(ClassDecl->needsImplicitDestructor());
13238 
13239   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13240   if (DSM.isAlreadyBeingDeclared())
13241     return nullptr;
13242 
13243   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13244                                                      CXXDestructor,
13245                                                      false);
13246 
13247   // Create the actual destructor declaration.
13248   CanQualType ClassType
13249     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13250   SourceLocation ClassLoc = ClassDecl->getLocation();
13251   DeclarationName Name
13252     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13253   DeclarationNameInfo NameInfo(Name, ClassLoc);
13254   CXXDestructorDecl *Destructor =
13255       CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13256                                 QualType(), nullptr, /*isInline=*/true,
13257                                 /*isImplicitlyDeclared=*/true,
13258                                 Constexpr ? ConstexprSpecKind::Constexpr
13259                                           : ConstexprSpecKind::Unspecified);
13260   Destructor->setAccess(AS_public);
13261   Destructor->setDefaulted();
13262 
13263   if (getLangOpts().CUDA) {
13264     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13265                                             Destructor,
13266                                             /* ConstRHS */ false,
13267                                             /* Diagnose */ false);
13268   }
13269 
13270   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13271 
13272   // We don't need to use SpecialMemberIsTrivial here; triviality for
13273   // destructors is easy to compute.
13274   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13275   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13276                                 ClassDecl->hasTrivialDestructorForCall());
13277 
13278   // Note that we have declared this destructor.
13279   ++getASTContext().NumImplicitDestructorsDeclared;
13280 
13281   Scope *S = getScopeForContext(ClassDecl);
13282   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13283 
13284   // We can't check whether an implicit destructor is deleted before we complete
13285   // the definition of the class, because its validity depends on the alignment
13286   // of the class. We'll check this from ActOnFields once the class is complete.
13287   if (ClassDecl->isCompleteDefinition() &&
13288       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13289     SetDeclDeleted(Destructor, ClassLoc);
13290 
13291   // Introduce this destructor into its scope.
13292   if (S)
13293     PushOnScopeChains(Destructor, S, false);
13294   ClassDecl->addDecl(Destructor);
13295 
13296   return Destructor;
13297 }
13298 
13299 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13300                                     CXXDestructorDecl *Destructor) {
13301   assert((Destructor->isDefaulted() &&
13302           !Destructor->doesThisDeclarationHaveABody() &&
13303           !Destructor->isDeleted()) &&
13304          "DefineImplicitDestructor - call it for implicit default dtor");
13305   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13306     return;
13307 
13308   CXXRecordDecl *ClassDecl = Destructor->getParent();
13309   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13310 
13311   SynthesizedFunctionScope Scope(*this, Destructor);
13312 
13313   // The exception specification is needed because we are defining the
13314   // function.
13315   ResolveExceptionSpec(CurrentLocation,
13316                        Destructor->getType()->castAs<FunctionProtoType>());
13317   MarkVTableUsed(CurrentLocation, ClassDecl);
13318 
13319   // Add a context note for diagnostics produced after this point.
13320   Scope.addContextNote(CurrentLocation);
13321 
13322   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13323                                          Destructor->getParent());
13324 
13325   if (CheckDestructor(Destructor)) {
13326     Destructor->setInvalidDecl();
13327     return;
13328   }
13329 
13330   SourceLocation Loc = Destructor->getEndLoc().isValid()
13331                            ? Destructor->getEndLoc()
13332                            : Destructor->getLocation();
13333   Destructor->setBody(new (Context) CompoundStmt(Loc));
13334   Destructor->markUsed(Context);
13335 
13336   if (ASTMutationListener *L = getASTMutationListener()) {
13337     L->CompletedImplicitDefinition(Destructor);
13338   }
13339 }
13340 
13341 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13342                                           CXXDestructorDecl *Destructor) {
13343   if (Destructor->isInvalidDecl())
13344     return;
13345 
13346   CXXRecordDecl *ClassDecl = Destructor->getParent();
13347   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13348          "implicit complete dtors unneeded outside MS ABI");
13349   assert(ClassDecl->getNumVBases() > 0 &&
13350          "complete dtor only exists for classes with vbases");
13351 
13352   SynthesizedFunctionScope Scope(*this, Destructor);
13353 
13354   // Add a context note for diagnostics produced after this point.
13355   Scope.addContextNote(CurrentLocation);
13356 
13357   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13358 }
13359 
13360 /// Perform any semantic analysis which needs to be delayed until all
13361 /// pending class member declarations have been parsed.
13362 void Sema::ActOnFinishCXXMemberDecls() {
13363   // If the context is an invalid C++ class, just suppress these checks.
13364   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13365     if (Record->isInvalidDecl()) {
13366       DelayedOverridingExceptionSpecChecks.clear();
13367       DelayedEquivalentExceptionSpecChecks.clear();
13368       return;
13369     }
13370     checkForMultipleExportedDefaultConstructors(*this, Record);
13371   }
13372 }
13373 
13374 void Sema::ActOnFinishCXXNonNestedClass() {
13375   referenceDLLExportedClassMethods();
13376 
13377   if (!DelayedDllExportMemberFunctions.empty()) {
13378     SmallVector<CXXMethodDecl*, 4> WorkList;
13379     std::swap(DelayedDllExportMemberFunctions, WorkList);
13380     for (CXXMethodDecl *M : WorkList) {
13381       DefineDefaultedFunction(*this, M, M->getLocation());
13382 
13383       // Pass the method to the consumer to get emitted. This is not necessary
13384       // for explicit instantiation definitions, as they will get emitted
13385       // anyway.
13386       if (M->getParent()->getTemplateSpecializationKind() !=
13387           TSK_ExplicitInstantiationDefinition)
13388         ActOnFinishInlineFunctionDef(M);
13389     }
13390   }
13391 }
13392 
13393 void Sema::referenceDLLExportedClassMethods() {
13394   if (!DelayedDllExportClasses.empty()) {
13395     // Calling ReferenceDllExportedMembers might cause the current function to
13396     // be called again, so use a local copy of DelayedDllExportClasses.
13397     SmallVector<CXXRecordDecl *, 4> WorkList;
13398     std::swap(DelayedDllExportClasses, WorkList);
13399     for (CXXRecordDecl *Class : WorkList)
13400       ReferenceDllExportedMembers(*this, Class);
13401   }
13402 }
13403 
13404 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13405   assert(getLangOpts().CPlusPlus11 &&
13406          "adjusting dtor exception specs was introduced in c++11");
13407 
13408   if (Destructor->isDependentContext())
13409     return;
13410 
13411   // C++11 [class.dtor]p3:
13412   //   A declaration of a destructor that does not have an exception-
13413   //   specification is implicitly considered to have the same exception-
13414   //   specification as an implicit declaration.
13415   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13416   if (DtorType->hasExceptionSpec())
13417     return;
13418 
13419   // Replace the destructor's type, building off the existing one. Fortunately,
13420   // the only thing of interest in the destructor type is its extended info.
13421   // The return and arguments are fixed.
13422   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13423   EPI.ExceptionSpec.Type = EST_Unevaluated;
13424   EPI.ExceptionSpec.SourceDecl = Destructor;
13425   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13426 
13427   // FIXME: If the destructor has a body that could throw, and the newly created
13428   // spec doesn't allow exceptions, we should emit a warning, because this
13429   // change in behavior can break conforming C++03 programs at runtime.
13430   // However, we don't have a body or an exception specification yet, so it
13431   // needs to be done somewhere else.
13432 }
13433 
13434 namespace {
13435 /// An abstract base class for all helper classes used in building the
13436 //  copy/move operators. These classes serve as factory functions and help us
13437 //  avoid using the same Expr* in the AST twice.
13438 class ExprBuilder {
13439   ExprBuilder(const ExprBuilder&) = delete;
13440   ExprBuilder &operator=(const ExprBuilder&) = delete;
13441 
13442 protected:
13443   static Expr *assertNotNull(Expr *E) {
13444     assert(E && "Expression construction must not fail.");
13445     return E;
13446   }
13447 
13448 public:
13449   ExprBuilder() {}
13450   virtual ~ExprBuilder() {}
13451 
13452   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13453 };
13454 
13455 class RefBuilder: public ExprBuilder {
13456   VarDecl *Var;
13457   QualType VarType;
13458 
13459 public:
13460   Expr *build(Sema &S, SourceLocation Loc) const override {
13461     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13462   }
13463 
13464   RefBuilder(VarDecl *Var, QualType VarType)
13465       : Var(Var), VarType(VarType) {}
13466 };
13467 
13468 class ThisBuilder: public ExprBuilder {
13469 public:
13470   Expr *build(Sema &S, SourceLocation Loc) const override {
13471     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13472   }
13473 };
13474 
13475 class CastBuilder: public ExprBuilder {
13476   const ExprBuilder &Builder;
13477   QualType Type;
13478   ExprValueKind Kind;
13479   const CXXCastPath &Path;
13480 
13481 public:
13482   Expr *build(Sema &S, SourceLocation Loc) const override {
13483     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13484                                              CK_UncheckedDerivedToBase, Kind,
13485                                              &Path).get());
13486   }
13487 
13488   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13489               const CXXCastPath &Path)
13490       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13491 };
13492 
13493 class DerefBuilder: public ExprBuilder {
13494   const ExprBuilder &Builder;
13495 
13496 public:
13497   Expr *build(Sema &S, SourceLocation Loc) const override {
13498     return assertNotNull(
13499         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13500   }
13501 
13502   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13503 };
13504 
13505 class MemberBuilder: public ExprBuilder {
13506   const ExprBuilder &Builder;
13507   QualType Type;
13508   CXXScopeSpec SS;
13509   bool IsArrow;
13510   LookupResult &MemberLookup;
13511 
13512 public:
13513   Expr *build(Sema &S, SourceLocation Loc) const override {
13514     return assertNotNull(S.BuildMemberReferenceExpr(
13515         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13516         nullptr, MemberLookup, nullptr, nullptr).get());
13517   }
13518 
13519   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13520                 LookupResult &MemberLookup)
13521       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13522         MemberLookup(MemberLookup) {}
13523 };
13524 
13525 class MoveCastBuilder: public ExprBuilder {
13526   const ExprBuilder &Builder;
13527 
13528 public:
13529   Expr *build(Sema &S, SourceLocation Loc) const override {
13530     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13531   }
13532 
13533   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13534 };
13535 
13536 class LvalueConvBuilder: public ExprBuilder {
13537   const ExprBuilder &Builder;
13538 
13539 public:
13540   Expr *build(Sema &S, SourceLocation Loc) const override {
13541     return assertNotNull(
13542         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13543   }
13544 
13545   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13546 };
13547 
13548 class SubscriptBuilder: public ExprBuilder {
13549   const ExprBuilder &Base;
13550   const ExprBuilder &Index;
13551 
13552 public:
13553   Expr *build(Sema &S, SourceLocation Loc) const override {
13554     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13555         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13556   }
13557 
13558   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13559       : Base(Base), Index(Index) {}
13560 };
13561 
13562 } // end anonymous namespace
13563 
13564 /// When generating a defaulted copy or move assignment operator, if a field
13565 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13566 /// do so. This optimization only applies for arrays of scalars, and for arrays
13567 /// of class type where the selected copy/move-assignment operator is trivial.
13568 static StmtResult
13569 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13570                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13571   // Compute the size of the memory buffer to be copied.
13572   QualType SizeType = S.Context.getSizeType();
13573   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13574                    S.Context.getTypeSizeInChars(T).getQuantity());
13575 
13576   // Take the address of the field references for "from" and "to". We
13577   // directly construct UnaryOperators here because semantic analysis
13578   // does not permit us to take the address of an xvalue.
13579   Expr *From = FromB.build(S, Loc);
13580   From = UnaryOperator::Create(
13581       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13582       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13583   Expr *To = ToB.build(S, Loc);
13584   To = UnaryOperator::Create(
13585       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13586       VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13587 
13588   const Type *E = T->getBaseElementTypeUnsafe();
13589   bool NeedsCollectableMemCpy =
13590       E->isRecordType() &&
13591       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13592 
13593   // Create a reference to the __builtin_objc_memmove_collectable function
13594   StringRef MemCpyName = NeedsCollectableMemCpy ?
13595     "__builtin_objc_memmove_collectable" :
13596     "__builtin_memcpy";
13597   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13598                  Sema::LookupOrdinaryName);
13599   S.LookupName(R, S.TUScope, true);
13600 
13601   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13602   if (!MemCpy)
13603     // Something went horribly wrong earlier, and we will have complained
13604     // about it.
13605     return StmtError();
13606 
13607   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13608                                             VK_RValue, Loc, nullptr);
13609   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13610 
13611   Expr *CallArgs[] = {
13612     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13613   };
13614   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13615                                     Loc, CallArgs, Loc);
13616 
13617   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13618   return Call.getAs<Stmt>();
13619 }
13620 
13621 /// Builds a statement that copies/moves the given entity from \p From to
13622 /// \c To.
13623 ///
13624 /// This routine is used to copy/move the members of a class with an
13625 /// implicitly-declared copy/move assignment operator. When the entities being
13626 /// copied are arrays, this routine builds for loops to copy them.
13627 ///
13628 /// \param S The Sema object used for type-checking.
13629 ///
13630 /// \param Loc The location where the implicit copy/move is being generated.
13631 ///
13632 /// \param T The type of the expressions being copied/moved. Both expressions
13633 /// must have this type.
13634 ///
13635 /// \param To The expression we are copying/moving to.
13636 ///
13637 /// \param From The expression we are copying/moving from.
13638 ///
13639 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13640 /// Otherwise, it's a non-static member subobject.
13641 ///
13642 /// \param Copying Whether we're copying or moving.
13643 ///
13644 /// \param Depth Internal parameter recording the depth of the recursion.
13645 ///
13646 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13647 /// if a memcpy should be used instead.
13648 static StmtResult
13649 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13650                                  const ExprBuilder &To, const ExprBuilder &From,
13651                                  bool CopyingBaseSubobject, bool Copying,
13652                                  unsigned Depth = 0) {
13653   // C++11 [class.copy]p28:
13654   //   Each subobject is assigned in the manner appropriate to its type:
13655   //
13656   //     - if the subobject is of class type, as if by a call to operator= with
13657   //       the subobject as the object expression and the corresponding
13658   //       subobject of x as a single function argument (as if by explicit
13659   //       qualification; that is, ignoring any possible virtual overriding
13660   //       functions in more derived classes);
13661   //
13662   // C++03 [class.copy]p13:
13663   //     - if the subobject is of class type, the copy assignment operator for
13664   //       the class is used (as if by explicit qualification; that is,
13665   //       ignoring any possible virtual overriding functions in more derived
13666   //       classes);
13667   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13668     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13669 
13670     // Look for operator=.
13671     DeclarationName Name
13672       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13673     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13674     S.LookupQualifiedName(OpLookup, ClassDecl, false);
13675 
13676     // Prior to C++11, filter out any result that isn't a copy/move-assignment
13677     // operator.
13678     if (!S.getLangOpts().CPlusPlus11) {
13679       LookupResult::Filter F = OpLookup.makeFilter();
13680       while (F.hasNext()) {
13681         NamedDecl *D = F.next();
13682         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13683           if (Method->isCopyAssignmentOperator() ||
13684               (!Copying && Method->isMoveAssignmentOperator()))
13685             continue;
13686 
13687         F.erase();
13688       }
13689       F.done();
13690     }
13691 
13692     // Suppress the protected check (C++ [class.protected]) for each of the
13693     // assignment operators we found. This strange dance is required when
13694     // we're assigning via a base classes's copy-assignment operator. To
13695     // ensure that we're getting the right base class subobject (without
13696     // ambiguities), we need to cast "this" to that subobject type; to
13697     // ensure that we don't go through the virtual call mechanism, we need
13698     // to qualify the operator= name with the base class (see below). However,
13699     // this means that if the base class has a protected copy assignment
13700     // operator, the protected member access check will fail. So, we
13701     // rewrite "protected" access to "public" access in this case, since we
13702     // know by construction that we're calling from a derived class.
13703     if (CopyingBaseSubobject) {
13704       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13705            L != LEnd; ++L) {
13706         if (L.getAccess() == AS_protected)
13707           L.setAccess(AS_public);
13708       }
13709     }
13710 
13711     // Create the nested-name-specifier that will be used to qualify the
13712     // reference to operator=; this is required to suppress the virtual
13713     // call mechanism.
13714     CXXScopeSpec SS;
13715     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13716     SS.MakeTrivial(S.Context,
13717                    NestedNameSpecifier::Create(S.Context, nullptr, false,
13718                                                CanonicalT),
13719                    Loc);
13720 
13721     // Create the reference to operator=.
13722     ExprResult OpEqualRef
13723       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13724                                    SS, /*TemplateKWLoc=*/SourceLocation(),
13725                                    /*FirstQualifierInScope=*/nullptr,
13726                                    OpLookup,
13727                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
13728                                    /*SuppressQualifierCheck=*/true);
13729     if (OpEqualRef.isInvalid())
13730       return StmtError();
13731 
13732     // Build the call to the assignment operator.
13733 
13734     Expr *FromInst = From.build(S, Loc);
13735     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13736                                                   OpEqualRef.getAs<Expr>(),
13737                                                   Loc, FromInst, Loc);
13738     if (Call.isInvalid())
13739       return StmtError();
13740 
13741     // If we built a call to a trivial 'operator=' while copying an array,
13742     // bail out. We'll replace the whole shebang with a memcpy.
13743     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13744     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13745       return StmtResult((Stmt*)nullptr);
13746 
13747     // Convert to an expression-statement, and clean up any produced
13748     // temporaries.
13749     return S.ActOnExprStmt(Call);
13750   }
13751 
13752   //     - if the subobject is of scalar type, the built-in assignment
13753   //       operator is used.
13754   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13755   if (!ArrayTy) {
13756     ExprResult Assignment = S.CreateBuiltinBinOp(
13757         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13758     if (Assignment.isInvalid())
13759       return StmtError();
13760     return S.ActOnExprStmt(Assignment);
13761   }
13762 
13763   //     - if the subobject is an array, each element is assigned, in the
13764   //       manner appropriate to the element type;
13765 
13766   // Construct a loop over the array bounds, e.g.,
13767   //
13768   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13769   //
13770   // that will copy each of the array elements.
13771   QualType SizeType = S.Context.getSizeType();
13772 
13773   // Create the iteration variable.
13774   IdentifierInfo *IterationVarName = nullptr;
13775   {
13776     SmallString<8> Str;
13777     llvm::raw_svector_ostream OS(Str);
13778     OS << "__i" << Depth;
13779     IterationVarName = &S.Context.Idents.get(OS.str());
13780   }
13781   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13782                                           IterationVarName, SizeType,
13783                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13784                                           SC_None);
13785 
13786   // Initialize the iteration variable to zero.
13787   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13788   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13789 
13790   // Creates a reference to the iteration variable.
13791   RefBuilder IterationVarRef(IterationVar, SizeType);
13792   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13793 
13794   // Create the DeclStmt that holds the iteration variable.
13795   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13796 
13797   // Subscript the "from" and "to" expressions with the iteration variable.
13798   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13799   MoveCastBuilder FromIndexMove(FromIndexCopy);
13800   const ExprBuilder *FromIndex;
13801   if (Copying)
13802     FromIndex = &FromIndexCopy;
13803   else
13804     FromIndex = &FromIndexMove;
13805 
13806   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13807 
13808   // Build the copy/move for an individual element of the array.
13809   StmtResult Copy =
13810     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13811                                      ToIndex, *FromIndex, CopyingBaseSubobject,
13812                                      Copying, Depth + 1);
13813   // Bail out if copying fails or if we determined that we should use memcpy.
13814   if (Copy.isInvalid() || !Copy.get())
13815     return Copy;
13816 
13817   // Create the comparison against the array bound.
13818   llvm::APInt Upper
13819     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13820   Expr *Comparison = BinaryOperator::Create(
13821       S.Context, IterationVarRefRVal.build(S, Loc),
13822       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13823       S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides());
13824 
13825   // Create the pre-increment of the iteration variable. We can determine
13826   // whether the increment will overflow based on the value of the array
13827   // bound.
13828   Expr *Increment = UnaryOperator::Create(
13829       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13830       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
13831 
13832   // Construct the loop that copies all elements of this array.
13833   return S.ActOnForStmt(
13834       Loc, Loc, InitStmt,
13835       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13836       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13837 }
13838 
13839 static StmtResult
13840 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13841                       const ExprBuilder &To, const ExprBuilder &From,
13842                       bool CopyingBaseSubobject, bool Copying) {
13843   // Maybe we should use a memcpy?
13844   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13845       T.isTriviallyCopyableType(S.Context))
13846     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13847 
13848   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13849                                                      CopyingBaseSubobject,
13850                                                      Copying, 0));
13851 
13852   // If we ended up picking a trivial assignment operator for an array of a
13853   // non-trivially-copyable class type, just emit a memcpy.
13854   if (!Result.isInvalid() && !Result.get())
13855     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13856 
13857   return Result;
13858 }
13859 
13860 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13861   // Note: The following rules are largely analoguous to the copy
13862   // constructor rules. Note that virtual bases are not taken into account
13863   // for determining the argument type of the operator. Note also that
13864   // operators taking an object instead of a reference are allowed.
13865   assert(ClassDecl->needsImplicitCopyAssignment());
13866 
13867   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13868   if (DSM.isAlreadyBeingDeclared())
13869     return nullptr;
13870 
13871   QualType ArgType = Context.getTypeDeclType(ClassDecl);
13872   LangAS AS = getDefaultCXXMethodAddrSpace();
13873   if (AS != LangAS::Default)
13874     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13875   QualType RetType = Context.getLValueReferenceType(ArgType);
13876   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13877   if (Const)
13878     ArgType = ArgType.withConst();
13879 
13880   ArgType = Context.getLValueReferenceType(ArgType);
13881 
13882   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13883                                                      CXXCopyAssignment,
13884                                                      Const);
13885 
13886   //   An implicitly-declared copy assignment operator is an inline public
13887   //   member of its class.
13888   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13889   SourceLocation ClassLoc = ClassDecl->getLocation();
13890   DeclarationNameInfo NameInfo(Name, ClassLoc);
13891   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13892       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13893       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13894       /*isInline=*/true,
13895       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
13896       SourceLocation());
13897   CopyAssignment->setAccess(AS_public);
13898   CopyAssignment->setDefaulted();
13899   CopyAssignment->setImplicit();
13900 
13901   if (getLangOpts().CUDA) {
13902     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13903                                             CopyAssignment,
13904                                             /* ConstRHS */ Const,
13905                                             /* Diagnose */ false);
13906   }
13907 
13908   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13909 
13910   // Add the parameter to the operator.
13911   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13912                                                ClassLoc, ClassLoc,
13913                                                /*Id=*/nullptr, ArgType,
13914                                                /*TInfo=*/nullptr, SC_None,
13915                                                nullptr);
13916   CopyAssignment->setParams(FromParam);
13917 
13918   CopyAssignment->setTrivial(
13919     ClassDecl->needsOverloadResolutionForCopyAssignment()
13920       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13921       : ClassDecl->hasTrivialCopyAssignment());
13922 
13923   // Note that we have added this copy-assignment operator.
13924   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13925 
13926   Scope *S = getScopeForContext(ClassDecl);
13927   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13928 
13929   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13930     ClassDecl->setImplicitCopyAssignmentIsDeleted();
13931     SetDeclDeleted(CopyAssignment, ClassLoc);
13932   }
13933 
13934   if (S)
13935     PushOnScopeChains(CopyAssignment, S, false);
13936   ClassDecl->addDecl(CopyAssignment);
13937 
13938   return CopyAssignment;
13939 }
13940 
13941 /// Diagnose an implicit copy operation for a class which is odr-used, but
13942 /// which is deprecated because the class has a user-declared copy constructor,
13943 /// copy assignment operator, or destructor.
13944 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13945   assert(CopyOp->isImplicit());
13946 
13947   CXXRecordDecl *RD = CopyOp->getParent();
13948   CXXMethodDecl *UserDeclaredOperation = nullptr;
13949 
13950   // In Microsoft mode, assignment operations don't affect constructors and
13951   // vice versa.
13952   if (RD->hasUserDeclaredDestructor()) {
13953     UserDeclaredOperation = RD->getDestructor();
13954   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13955              RD->hasUserDeclaredCopyConstructor() &&
13956              !S.getLangOpts().MSVCCompat) {
13957     // Find any user-declared copy constructor.
13958     for (auto *I : RD->ctors()) {
13959       if (I->isCopyConstructor()) {
13960         UserDeclaredOperation = I;
13961         break;
13962       }
13963     }
13964     assert(UserDeclaredOperation);
13965   } else if (isa<CXXConstructorDecl>(CopyOp) &&
13966              RD->hasUserDeclaredCopyAssignment() &&
13967              !S.getLangOpts().MSVCCompat) {
13968     // Find any user-declared move assignment operator.
13969     for (auto *I : RD->methods()) {
13970       if (I->isCopyAssignmentOperator()) {
13971         UserDeclaredOperation = I;
13972         break;
13973       }
13974     }
13975     assert(UserDeclaredOperation);
13976   }
13977 
13978   if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
13979     S.Diag(UserDeclaredOperation->getLocation(),
13980            isa<CXXDestructorDecl>(UserDeclaredOperation)
13981                ? diag::warn_deprecated_copy_dtor_operation
13982                : diag::warn_deprecated_copy_operation)
13983         << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
13984   }
13985 }
13986 
13987 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
13988                                         CXXMethodDecl *CopyAssignOperator) {
13989   assert((CopyAssignOperator->isDefaulted() &&
13990           CopyAssignOperator->isOverloadedOperator() &&
13991           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
13992           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
13993           !CopyAssignOperator->isDeleted()) &&
13994          "DefineImplicitCopyAssignment called for wrong function");
13995   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
13996     return;
13997 
13998   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
13999   if (ClassDecl->isInvalidDecl()) {
14000     CopyAssignOperator->setInvalidDecl();
14001     return;
14002   }
14003 
14004   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14005 
14006   // The exception specification is needed because we are defining the
14007   // function.
14008   ResolveExceptionSpec(CurrentLocation,
14009                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14010 
14011   // Add a context note for diagnostics produced after this point.
14012   Scope.addContextNote(CurrentLocation);
14013 
14014   // C++11 [class.copy]p18:
14015   //   The [definition of an implicitly declared copy assignment operator] is
14016   //   deprecated if the class has a user-declared copy constructor or a
14017   //   user-declared destructor.
14018   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14019     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14020 
14021   // C++0x [class.copy]p30:
14022   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14023   //   for a non-union class X performs memberwise copy assignment of its
14024   //   subobjects. The direct base classes of X are assigned first, in the
14025   //   order of their declaration in the base-specifier-list, and then the
14026   //   immediate non-static data members of X are assigned, in the order in
14027   //   which they were declared in the class definition.
14028 
14029   // The statements that form the synthesized function body.
14030   SmallVector<Stmt*, 8> Statements;
14031 
14032   // The parameter for the "other" object, which we are copying from.
14033   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14034   Qualifiers OtherQuals = Other->getType().getQualifiers();
14035   QualType OtherRefType = Other->getType();
14036   if (const LValueReferenceType *OtherRef
14037                                 = OtherRefType->getAs<LValueReferenceType>()) {
14038     OtherRefType = OtherRef->getPointeeType();
14039     OtherQuals = OtherRefType.getQualifiers();
14040   }
14041 
14042   // Our location for everything implicitly-generated.
14043   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14044                            ? CopyAssignOperator->getEndLoc()
14045                            : CopyAssignOperator->getLocation();
14046 
14047   // Builds a DeclRefExpr for the "other" object.
14048   RefBuilder OtherRef(Other, OtherRefType);
14049 
14050   // Builds the "this" pointer.
14051   ThisBuilder This;
14052 
14053   // Assign base classes.
14054   bool Invalid = false;
14055   for (auto &Base : ClassDecl->bases()) {
14056     // Form the assignment:
14057     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14058     QualType BaseType = Base.getType().getUnqualifiedType();
14059     if (!BaseType->isRecordType()) {
14060       Invalid = true;
14061       continue;
14062     }
14063 
14064     CXXCastPath BasePath;
14065     BasePath.push_back(&Base);
14066 
14067     // Construct the "from" expression, which is an implicit cast to the
14068     // appropriately-qualified base type.
14069     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14070                      VK_LValue, BasePath);
14071 
14072     // Dereference "this".
14073     DerefBuilder DerefThis(This);
14074     CastBuilder To(DerefThis,
14075                    Context.getQualifiedType(
14076                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14077                    VK_LValue, BasePath);
14078 
14079     // Build the copy.
14080     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14081                                             To, From,
14082                                             /*CopyingBaseSubobject=*/true,
14083                                             /*Copying=*/true);
14084     if (Copy.isInvalid()) {
14085       CopyAssignOperator->setInvalidDecl();
14086       return;
14087     }
14088 
14089     // Success! Record the copy.
14090     Statements.push_back(Copy.getAs<Expr>());
14091   }
14092 
14093   // Assign non-static members.
14094   for (auto *Field : ClassDecl->fields()) {
14095     // FIXME: We should form some kind of AST representation for the implied
14096     // memcpy in a union copy operation.
14097     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14098       continue;
14099 
14100     if (Field->isInvalidDecl()) {
14101       Invalid = true;
14102       continue;
14103     }
14104 
14105     // Check for members of reference type; we can't copy those.
14106     if (Field->getType()->isReferenceType()) {
14107       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14108         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14109       Diag(Field->getLocation(), diag::note_declared_at);
14110       Invalid = true;
14111       continue;
14112     }
14113 
14114     // Check for members of const-qualified, non-class type.
14115     QualType BaseType = Context.getBaseElementType(Field->getType());
14116     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14117       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14118         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14119       Diag(Field->getLocation(), diag::note_declared_at);
14120       Invalid = true;
14121       continue;
14122     }
14123 
14124     // Suppress assigning zero-width bitfields.
14125     if (Field->isZeroLengthBitField(Context))
14126       continue;
14127 
14128     QualType FieldType = Field->getType().getNonReferenceType();
14129     if (FieldType->isIncompleteArrayType()) {
14130       assert(ClassDecl->hasFlexibleArrayMember() &&
14131              "Incomplete array type is not valid");
14132       continue;
14133     }
14134 
14135     // Build references to the field in the object we're copying from and to.
14136     CXXScopeSpec SS; // Intentionally empty
14137     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14138                               LookupMemberName);
14139     MemberLookup.addDecl(Field);
14140     MemberLookup.resolveKind();
14141 
14142     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14143 
14144     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14145 
14146     // Build the copy of this field.
14147     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14148                                             To, From,
14149                                             /*CopyingBaseSubobject=*/false,
14150                                             /*Copying=*/true);
14151     if (Copy.isInvalid()) {
14152       CopyAssignOperator->setInvalidDecl();
14153       return;
14154     }
14155 
14156     // Success! Record the copy.
14157     Statements.push_back(Copy.getAs<Stmt>());
14158   }
14159 
14160   if (!Invalid) {
14161     // Add a "return *this;"
14162     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14163 
14164     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14165     if (Return.isInvalid())
14166       Invalid = true;
14167     else
14168       Statements.push_back(Return.getAs<Stmt>());
14169   }
14170 
14171   if (Invalid) {
14172     CopyAssignOperator->setInvalidDecl();
14173     return;
14174   }
14175 
14176   StmtResult Body;
14177   {
14178     CompoundScopeRAII CompoundScope(*this);
14179     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14180                              /*isStmtExpr=*/false);
14181     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14182   }
14183   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14184   CopyAssignOperator->markUsed(Context);
14185 
14186   if (ASTMutationListener *L = getASTMutationListener()) {
14187     L->CompletedImplicitDefinition(CopyAssignOperator);
14188   }
14189 }
14190 
14191 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14192   assert(ClassDecl->needsImplicitMoveAssignment());
14193 
14194   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14195   if (DSM.isAlreadyBeingDeclared())
14196     return nullptr;
14197 
14198   // Note: The following rules are largely analoguous to the move
14199   // constructor rules.
14200 
14201   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14202   LangAS AS = getDefaultCXXMethodAddrSpace();
14203   if (AS != LangAS::Default)
14204     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14205   QualType RetType = Context.getLValueReferenceType(ArgType);
14206   ArgType = Context.getRValueReferenceType(ArgType);
14207 
14208   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14209                                                      CXXMoveAssignment,
14210                                                      false);
14211 
14212   //   An implicitly-declared move assignment operator is an inline public
14213   //   member of its class.
14214   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14215   SourceLocation ClassLoc = ClassDecl->getLocation();
14216   DeclarationNameInfo NameInfo(Name, ClassLoc);
14217   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14218       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14219       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14220       /*isInline=*/true,
14221       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14222       SourceLocation());
14223   MoveAssignment->setAccess(AS_public);
14224   MoveAssignment->setDefaulted();
14225   MoveAssignment->setImplicit();
14226 
14227   if (getLangOpts().CUDA) {
14228     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14229                                             MoveAssignment,
14230                                             /* ConstRHS */ false,
14231                                             /* Diagnose */ false);
14232   }
14233 
14234   // Build an exception specification pointing back at this member.
14235   FunctionProtoType::ExtProtoInfo EPI =
14236       getImplicitMethodEPI(*this, MoveAssignment);
14237   MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14238 
14239   // Add the parameter to the operator.
14240   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14241                                                ClassLoc, ClassLoc,
14242                                                /*Id=*/nullptr, ArgType,
14243                                                /*TInfo=*/nullptr, SC_None,
14244                                                nullptr);
14245   MoveAssignment->setParams(FromParam);
14246 
14247   MoveAssignment->setTrivial(
14248     ClassDecl->needsOverloadResolutionForMoveAssignment()
14249       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14250       : ClassDecl->hasTrivialMoveAssignment());
14251 
14252   // Note that we have added this copy-assignment operator.
14253   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14254 
14255   Scope *S = getScopeForContext(ClassDecl);
14256   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14257 
14258   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14259     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14260     SetDeclDeleted(MoveAssignment, ClassLoc);
14261   }
14262 
14263   if (S)
14264     PushOnScopeChains(MoveAssignment, S, false);
14265   ClassDecl->addDecl(MoveAssignment);
14266 
14267   return MoveAssignment;
14268 }
14269 
14270 /// Check if we're implicitly defining a move assignment operator for a class
14271 /// with virtual bases. Such a move assignment might move-assign the virtual
14272 /// base multiple times.
14273 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14274                                                SourceLocation CurrentLocation) {
14275   assert(!Class->isDependentContext() && "should not define dependent move");
14276 
14277   // Only a virtual base could get implicitly move-assigned multiple times.
14278   // Only a non-trivial move assignment can observe this. We only want to
14279   // diagnose if we implicitly define an assignment operator that assigns
14280   // two base classes, both of which move-assign the same virtual base.
14281   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14282       Class->getNumBases() < 2)
14283     return;
14284 
14285   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14286   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14287   VBaseMap VBases;
14288 
14289   for (auto &BI : Class->bases()) {
14290     Worklist.push_back(&BI);
14291     while (!Worklist.empty()) {
14292       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14293       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14294 
14295       // If the base has no non-trivial move assignment operators,
14296       // we don't care about moves from it.
14297       if (!Base->hasNonTrivialMoveAssignment())
14298         continue;
14299 
14300       // If there's nothing virtual here, skip it.
14301       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14302         continue;
14303 
14304       // If we're not actually going to call a move assignment for this base,
14305       // or the selected move assignment is trivial, skip it.
14306       Sema::SpecialMemberOverloadResult SMOR =
14307         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14308                               /*ConstArg*/false, /*VolatileArg*/false,
14309                               /*RValueThis*/true, /*ConstThis*/false,
14310                               /*VolatileThis*/false);
14311       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14312           !SMOR.getMethod()->isMoveAssignmentOperator())
14313         continue;
14314 
14315       if (BaseSpec->isVirtual()) {
14316         // We're going to move-assign this virtual base, and its move
14317         // assignment operator is not trivial. If this can happen for
14318         // multiple distinct direct bases of Class, diagnose it. (If it
14319         // only happens in one base, we'll diagnose it when synthesizing
14320         // that base class's move assignment operator.)
14321         CXXBaseSpecifier *&Existing =
14322             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14323                 .first->second;
14324         if (Existing && Existing != &BI) {
14325           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14326             << Class << Base;
14327           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14328               << (Base->getCanonicalDecl() ==
14329                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14330               << Base << Existing->getType() << Existing->getSourceRange();
14331           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14332               << (Base->getCanonicalDecl() ==
14333                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14334               << Base << BI.getType() << BaseSpec->getSourceRange();
14335 
14336           // Only diagnose each vbase once.
14337           Existing = nullptr;
14338         }
14339       } else {
14340         // Only walk over bases that have defaulted move assignment operators.
14341         // We assume that any user-provided move assignment operator handles
14342         // the multiple-moves-of-vbase case itself somehow.
14343         if (!SMOR.getMethod()->isDefaulted())
14344           continue;
14345 
14346         // We're going to move the base classes of Base. Add them to the list.
14347         for (auto &BI : Base->bases())
14348           Worklist.push_back(&BI);
14349       }
14350     }
14351   }
14352 }
14353 
14354 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14355                                         CXXMethodDecl *MoveAssignOperator) {
14356   assert((MoveAssignOperator->isDefaulted() &&
14357           MoveAssignOperator->isOverloadedOperator() &&
14358           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14359           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14360           !MoveAssignOperator->isDeleted()) &&
14361          "DefineImplicitMoveAssignment called for wrong function");
14362   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14363     return;
14364 
14365   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14366   if (ClassDecl->isInvalidDecl()) {
14367     MoveAssignOperator->setInvalidDecl();
14368     return;
14369   }
14370 
14371   // C++0x [class.copy]p28:
14372   //   The implicitly-defined or move assignment operator for a non-union class
14373   //   X performs memberwise move assignment of its subobjects. The direct base
14374   //   classes of X are assigned first, in the order of their declaration in the
14375   //   base-specifier-list, and then the immediate non-static data members of X
14376   //   are assigned, in the order in which they were declared in the class
14377   //   definition.
14378 
14379   // Issue a warning if our implicit move assignment operator will move
14380   // from a virtual base more than once.
14381   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14382 
14383   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14384 
14385   // The exception specification is needed because we are defining the
14386   // function.
14387   ResolveExceptionSpec(CurrentLocation,
14388                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14389 
14390   // Add a context note for diagnostics produced after this point.
14391   Scope.addContextNote(CurrentLocation);
14392 
14393   // The statements that form the synthesized function body.
14394   SmallVector<Stmt*, 8> Statements;
14395 
14396   // The parameter for the "other" object, which we are move from.
14397   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14398   QualType OtherRefType =
14399       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14400 
14401   // Our location for everything implicitly-generated.
14402   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14403                            ? MoveAssignOperator->getEndLoc()
14404                            : MoveAssignOperator->getLocation();
14405 
14406   // Builds a reference to the "other" object.
14407   RefBuilder OtherRef(Other, OtherRefType);
14408   // Cast to rvalue.
14409   MoveCastBuilder MoveOther(OtherRef);
14410 
14411   // Builds the "this" pointer.
14412   ThisBuilder This;
14413 
14414   // Assign base classes.
14415   bool Invalid = false;
14416   for (auto &Base : ClassDecl->bases()) {
14417     // C++11 [class.copy]p28:
14418     //   It is unspecified whether subobjects representing virtual base classes
14419     //   are assigned more than once by the implicitly-defined copy assignment
14420     //   operator.
14421     // FIXME: Do not assign to a vbase that will be assigned by some other base
14422     // class. For a move-assignment, this can result in the vbase being moved
14423     // multiple times.
14424 
14425     // Form the assignment:
14426     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14427     QualType BaseType = Base.getType().getUnqualifiedType();
14428     if (!BaseType->isRecordType()) {
14429       Invalid = true;
14430       continue;
14431     }
14432 
14433     CXXCastPath BasePath;
14434     BasePath.push_back(&Base);
14435 
14436     // Construct the "from" expression, which is an implicit cast to the
14437     // appropriately-qualified base type.
14438     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14439 
14440     // Dereference "this".
14441     DerefBuilder DerefThis(This);
14442 
14443     // Implicitly cast "this" to the appropriately-qualified base type.
14444     CastBuilder To(DerefThis,
14445                    Context.getQualifiedType(
14446                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14447                    VK_LValue, BasePath);
14448 
14449     // Build the move.
14450     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14451                                             To, From,
14452                                             /*CopyingBaseSubobject=*/true,
14453                                             /*Copying=*/false);
14454     if (Move.isInvalid()) {
14455       MoveAssignOperator->setInvalidDecl();
14456       return;
14457     }
14458 
14459     // Success! Record the move.
14460     Statements.push_back(Move.getAs<Expr>());
14461   }
14462 
14463   // Assign non-static members.
14464   for (auto *Field : ClassDecl->fields()) {
14465     // FIXME: We should form some kind of AST representation for the implied
14466     // memcpy in a union copy operation.
14467     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14468       continue;
14469 
14470     if (Field->isInvalidDecl()) {
14471       Invalid = true;
14472       continue;
14473     }
14474 
14475     // Check for members of reference type; we can't move those.
14476     if (Field->getType()->isReferenceType()) {
14477       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14478         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14479       Diag(Field->getLocation(), diag::note_declared_at);
14480       Invalid = true;
14481       continue;
14482     }
14483 
14484     // Check for members of const-qualified, non-class type.
14485     QualType BaseType = Context.getBaseElementType(Field->getType());
14486     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14487       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14488         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14489       Diag(Field->getLocation(), diag::note_declared_at);
14490       Invalid = true;
14491       continue;
14492     }
14493 
14494     // Suppress assigning zero-width bitfields.
14495     if (Field->isZeroLengthBitField(Context))
14496       continue;
14497 
14498     QualType FieldType = Field->getType().getNonReferenceType();
14499     if (FieldType->isIncompleteArrayType()) {
14500       assert(ClassDecl->hasFlexibleArrayMember() &&
14501              "Incomplete array type is not valid");
14502       continue;
14503     }
14504 
14505     // Build references to the field in the object we're copying from and to.
14506     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14507                               LookupMemberName);
14508     MemberLookup.addDecl(Field);
14509     MemberLookup.resolveKind();
14510     MemberBuilder From(MoveOther, OtherRefType,
14511                        /*IsArrow=*/false, MemberLookup);
14512     MemberBuilder To(This, getCurrentThisType(),
14513                      /*IsArrow=*/true, MemberLookup);
14514 
14515     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14516         "Member reference with rvalue base must be rvalue except for reference "
14517         "members, which aren't allowed for move assignment.");
14518 
14519     // Build the move of this field.
14520     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14521                                             To, From,
14522                                             /*CopyingBaseSubobject=*/false,
14523                                             /*Copying=*/false);
14524     if (Move.isInvalid()) {
14525       MoveAssignOperator->setInvalidDecl();
14526       return;
14527     }
14528 
14529     // Success! Record the copy.
14530     Statements.push_back(Move.getAs<Stmt>());
14531   }
14532 
14533   if (!Invalid) {
14534     // Add a "return *this;"
14535     ExprResult ThisObj =
14536         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14537 
14538     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14539     if (Return.isInvalid())
14540       Invalid = true;
14541     else
14542       Statements.push_back(Return.getAs<Stmt>());
14543   }
14544 
14545   if (Invalid) {
14546     MoveAssignOperator->setInvalidDecl();
14547     return;
14548   }
14549 
14550   StmtResult Body;
14551   {
14552     CompoundScopeRAII CompoundScope(*this);
14553     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14554                              /*isStmtExpr=*/false);
14555     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14556   }
14557   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14558   MoveAssignOperator->markUsed(Context);
14559 
14560   if (ASTMutationListener *L = getASTMutationListener()) {
14561     L->CompletedImplicitDefinition(MoveAssignOperator);
14562   }
14563 }
14564 
14565 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14566                                                     CXXRecordDecl *ClassDecl) {
14567   // C++ [class.copy]p4:
14568   //   If the class definition does not explicitly declare a copy
14569   //   constructor, one is declared implicitly.
14570   assert(ClassDecl->needsImplicitCopyConstructor());
14571 
14572   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14573   if (DSM.isAlreadyBeingDeclared())
14574     return nullptr;
14575 
14576   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14577   QualType ArgType = ClassType;
14578   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14579   if (Const)
14580     ArgType = ArgType.withConst();
14581 
14582   LangAS AS = getDefaultCXXMethodAddrSpace();
14583   if (AS != LangAS::Default)
14584     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14585 
14586   ArgType = Context.getLValueReferenceType(ArgType);
14587 
14588   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14589                                                      CXXCopyConstructor,
14590                                                      Const);
14591 
14592   DeclarationName Name
14593     = Context.DeclarationNames.getCXXConstructorName(
14594                                            Context.getCanonicalType(ClassType));
14595   SourceLocation ClassLoc = ClassDecl->getLocation();
14596   DeclarationNameInfo NameInfo(Name, ClassLoc);
14597 
14598   //   An implicitly-declared copy constructor is an inline public
14599   //   member of its class.
14600   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14601       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14602       ExplicitSpecifier(),
14603       /*isInline=*/true,
14604       /*isImplicitlyDeclared=*/true,
14605       Constexpr ? ConstexprSpecKind::Constexpr
14606                 : ConstexprSpecKind::Unspecified);
14607   CopyConstructor->setAccess(AS_public);
14608   CopyConstructor->setDefaulted();
14609 
14610   if (getLangOpts().CUDA) {
14611     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14612                                             CopyConstructor,
14613                                             /* ConstRHS */ Const,
14614                                             /* Diagnose */ false);
14615   }
14616 
14617   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14618 
14619   // Add the parameter to the constructor.
14620   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14621                                                ClassLoc, ClassLoc,
14622                                                /*IdentifierInfo=*/nullptr,
14623                                                ArgType, /*TInfo=*/nullptr,
14624                                                SC_None, nullptr);
14625   CopyConstructor->setParams(FromParam);
14626 
14627   CopyConstructor->setTrivial(
14628       ClassDecl->needsOverloadResolutionForCopyConstructor()
14629           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14630           : ClassDecl->hasTrivialCopyConstructor());
14631 
14632   CopyConstructor->setTrivialForCall(
14633       ClassDecl->hasAttr<TrivialABIAttr>() ||
14634       (ClassDecl->needsOverloadResolutionForCopyConstructor()
14635            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14636              TAH_ConsiderTrivialABI)
14637            : ClassDecl->hasTrivialCopyConstructorForCall()));
14638 
14639   // Note that we have declared this constructor.
14640   ++getASTContext().NumImplicitCopyConstructorsDeclared;
14641 
14642   Scope *S = getScopeForContext(ClassDecl);
14643   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14644 
14645   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14646     ClassDecl->setImplicitCopyConstructorIsDeleted();
14647     SetDeclDeleted(CopyConstructor, ClassLoc);
14648   }
14649 
14650   if (S)
14651     PushOnScopeChains(CopyConstructor, S, false);
14652   ClassDecl->addDecl(CopyConstructor);
14653 
14654   return CopyConstructor;
14655 }
14656 
14657 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14658                                          CXXConstructorDecl *CopyConstructor) {
14659   assert((CopyConstructor->isDefaulted() &&
14660           CopyConstructor->isCopyConstructor() &&
14661           !CopyConstructor->doesThisDeclarationHaveABody() &&
14662           !CopyConstructor->isDeleted()) &&
14663          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14664   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14665     return;
14666 
14667   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14668   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14669 
14670   SynthesizedFunctionScope Scope(*this, CopyConstructor);
14671 
14672   // The exception specification is needed because we are defining the
14673   // function.
14674   ResolveExceptionSpec(CurrentLocation,
14675                        CopyConstructor->getType()->castAs<FunctionProtoType>());
14676   MarkVTableUsed(CurrentLocation, ClassDecl);
14677 
14678   // Add a context note for diagnostics produced after this point.
14679   Scope.addContextNote(CurrentLocation);
14680 
14681   // C++11 [class.copy]p7:
14682   //   The [definition of an implicitly declared copy constructor] is
14683   //   deprecated if the class has a user-declared copy assignment operator
14684   //   or a user-declared destructor.
14685   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14686     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14687 
14688   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14689     CopyConstructor->setInvalidDecl();
14690   }  else {
14691     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14692                              ? CopyConstructor->getEndLoc()
14693                              : CopyConstructor->getLocation();
14694     Sema::CompoundScopeRAII CompoundScope(*this);
14695     CopyConstructor->setBody(
14696         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14697     CopyConstructor->markUsed(Context);
14698   }
14699 
14700   if (ASTMutationListener *L = getASTMutationListener()) {
14701     L->CompletedImplicitDefinition(CopyConstructor);
14702   }
14703 }
14704 
14705 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14706                                                     CXXRecordDecl *ClassDecl) {
14707   assert(ClassDecl->needsImplicitMoveConstructor());
14708 
14709   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14710   if (DSM.isAlreadyBeingDeclared())
14711     return nullptr;
14712 
14713   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14714 
14715   QualType ArgType = ClassType;
14716   LangAS AS = getDefaultCXXMethodAddrSpace();
14717   if (AS != LangAS::Default)
14718     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14719   ArgType = Context.getRValueReferenceType(ArgType);
14720 
14721   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14722                                                      CXXMoveConstructor,
14723                                                      false);
14724 
14725   DeclarationName Name
14726     = Context.DeclarationNames.getCXXConstructorName(
14727                                            Context.getCanonicalType(ClassType));
14728   SourceLocation ClassLoc = ClassDecl->getLocation();
14729   DeclarationNameInfo NameInfo(Name, ClassLoc);
14730 
14731   // C++11 [class.copy]p11:
14732   //   An implicitly-declared copy/move constructor is an inline public
14733   //   member of its class.
14734   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14735       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14736       ExplicitSpecifier(),
14737       /*isInline=*/true,
14738       /*isImplicitlyDeclared=*/true,
14739       Constexpr ? ConstexprSpecKind::Constexpr
14740                 : ConstexprSpecKind::Unspecified);
14741   MoveConstructor->setAccess(AS_public);
14742   MoveConstructor->setDefaulted();
14743 
14744   if (getLangOpts().CUDA) {
14745     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14746                                             MoveConstructor,
14747                                             /* ConstRHS */ false,
14748                                             /* Diagnose */ false);
14749   }
14750 
14751   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14752 
14753   // Add the parameter to the constructor.
14754   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14755                                                ClassLoc, ClassLoc,
14756                                                /*IdentifierInfo=*/nullptr,
14757                                                ArgType, /*TInfo=*/nullptr,
14758                                                SC_None, nullptr);
14759   MoveConstructor->setParams(FromParam);
14760 
14761   MoveConstructor->setTrivial(
14762       ClassDecl->needsOverloadResolutionForMoveConstructor()
14763           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14764           : ClassDecl->hasTrivialMoveConstructor());
14765 
14766   MoveConstructor->setTrivialForCall(
14767       ClassDecl->hasAttr<TrivialABIAttr>() ||
14768       (ClassDecl->needsOverloadResolutionForMoveConstructor()
14769            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14770                                     TAH_ConsiderTrivialABI)
14771            : ClassDecl->hasTrivialMoveConstructorForCall()));
14772 
14773   // Note that we have declared this constructor.
14774   ++getASTContext().NumImplicitMoveConstructorsDeclared;
14775 
14776   Scope *S = getScopeForContext(ClassDecl);
14777   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14778 
14779   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14780     ClassDecl->setImplicitMoveConstructorIsDeleted();
14781     SetDeclDeleted(MoveConstructor, ClassLoc);
14782   }
14783 
14784   if (S)
14785     PushOnScopeChains(MoveConstructor, S, false);
14786   ClassDecl->addDecl(MoveConstructor);
14787 
14788   return MoveConstructor;
14789 }
14790 
14791 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14792                                          CXXConstructorDecl *MoveConstructor) {
14793   assert((MoveConstructor->isDefaulted() &&
14794           MoveConstructor->isMoveConstructor() &&
14795           !MoveConstructor->doesThisDeclarationHaveABody() &&
14796           !MoveConstructor->isDeleted()) &&
14797          "DefineImplicitMoveConstructor - call it for implicit move ctor");
14798   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14799     return;
14800 
14801   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14802   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14803 
14804   SynthesizedFunctionScope Scope(*this, MoveConstructor);
14805 
14806   // The exception specification is needed because we are defining the
14807   // function.
14808   ResolveExceptionSpec(CurrentLocation,
14809                        MoveConstructor->getType()->castAs<FunctionProtoType>());
14810   MarkVTableUsed(CurrentLocation, ClassDecl);
14811 
14812   // Add a context note for diagnostics produced after this point.
14813   Scope.addContextNote(CurrentLocation);
14814 
14815   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14816     MoveConstructor->setInvalidDecl();
14817   } else {
14818     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14819                              ? MoveConstructor->getEndLoc()
14820                              : MoveConstructor->getLocation();
14821     Sema::CompoundScopeRAII CompoundScope(*this);
14822     MoveConstructor->setBody(ActOnCompoundStmt(
14823         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14824     MoveConstructor->markUsed(Context);
14825   }
14826 
14827   if (ASTMutationListener *L = getASTMutationListener()) {
14828     L->CompletedImplicitDefinition(MoveConstructor);
14829   }
14830 }
14831 
14832 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14833   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14834 }
14835 
14836 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14837                             SourceLocation CurrentLocation,
14838                             CXXConversionDecl *Conv) {
14839   SynthesizedFunctionScope Scope(*this, Conv);
14840   assert(!Conv->getReturnType()->isUndeducedType());
14841 
14842   QualType ConvRT = Conv->getType()->getAs<FunctionType>()->getReturnType();
14843   CallingConv CC =
14844       ConvRT->getPointeeType()->getAs<FunctionType>()->getCallConv();
14845 
14846   CXXRecordDecl *Lambda = Conv->getParent();
14847   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14848   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
14849 
14850   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14851     CallOp = InstantiateFunctionDeclaration(
14852         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14853     if (!CallOp)
14854       return;
14855 
14856     Invoker = InstantiateFunctionDeclaration(
14857         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14858     if (!Invoker)
14859       return;
14860   }
14861 
14862   if (CallOp->isInvalidDecl())
14863     return;
14864 
14865   // Mark the call operator referenced (and add to pending instantiations
14866   // if necessary).
14867   // For both the conversion and static-invoker template specializations
14868   // we construct their body's in this function, so no need to add them
14869   // to the PendingInstantiations.
14870   MarkFunctionReferenced(CurrentLocation, CallOp);
14871 
14872   // Fill in the __invoke function with a dummy implementation. IR generation
14873   // will fill in the actual details. Update its type in case it contained
14874   // an 'auto'.
14875   Invoker->markUsed(Context);
14876   Invoker->setReferenced();
14877   Invoker->setType(Conv->getReturnType()->getPointeeType());
14878   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14879 
14880   // Construct the body of the conversion function { return __invoke; }.
14881   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14882                                        VK_LValue, Conv->getLocation());
14883   assert(FunctionRef && "Can't refer to __invoke function?");
14884   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14885   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14886                                      Conv->getLocation()));
14887   Conv->markUsed(Context);
14888   Conv->setReferenced();
14889 
14890   if (ASTMutationListener *L = getASTMutationListener()) {
14891     L->CompletedImplicitDefinition(Conv);
14892     L->CompletedImplicitDefinition(Invoker);
14893   }
14894 }
14895 
14896 
14897 
14898 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14899        SourceLocation CurrentLocation,
14900        CXXConversionDecl *Conv)
14901 {
14902   assert(!Conv->getParent()->isGenericLambda());
14903 
14904   SynthesizedFunctionScope Scope(*this, Conv);
14905 
14906   // Copy-initialize the lambda object as needed to capture it.
14907   Expr *This = ActOnCXXThis(CurrentLocation).get();
14908   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14909 
14910   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14911                                                         Conv->getLocation(),
14912                                                         Conv, DerefThis);
14913 
14914   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14915   // behavior.  Note that only the general conversion function does this
14916   // (since it's unusable otherwise); in the case where we inline the
14917   // block literal, it has block literal lifetime semantics.
14918   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14919     BuildBlock = ImplicitCastExpr::Create(
14920         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
14921         BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride());
14922 
14923   if (BuildBlock.isInvalid()) {
14924     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14925     Conv->setInvalidDecl();
14926     return;
14927   }
14928 
14929   // Create the return statement that returns the block from the conversion
14930   // function.
14931   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14932   if (Return.isInvalid()) {
14933     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14934     Conv->setInvalidDecl();
14935     return;
14936   }
14937 
14938   // Set the body of the conversion function.
14939   Stmt *ReturnS = Return.get();
14940   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14941                                      Conv->getLocation()));
14942   Conv->markUsed(Context);
14943 
14944   // We're done; notify the mutation listener, if any.
14945   if (ASTMutationListener *L = getASTMutationListener()) {
14946     L->CompletedImplicitDefinition(Conv);
14947   }
14948 }
14949 
14950 /// Determine whether the given list arguments contains exactly one
14951 /// "real" (non-default) argument.
14952 static bool hasOneRealArgument(MultiExprArg Args) {
14953   switch (Args.size()) {
14954   case 0:
14955     return false;
14956 
14957   default:
14958     if (!Args[1]->isDefaultArgument())
14959       return false;
14960 
14961     LLVM_FALLTHROUGH;
14962   case 1:
14963     return !Args[0]->isDefaultArgument();
14964   }
14965 
14966   return false;
14967 }
14968 
14969 ExprResult
14970 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14971                             NamedDecl *FoundDecl,
14972                             CXXConstructorDecl *Constructor,
14973                             MultiExprArg ExprArgs,
14974                             bool HadMultipleCandidates,
14975                             bool IsListInitialization,
14976                             bool IsStdInitListInitialization,
14977                             bool RequiresZeroInit,
14978                             unsigned ConstructKind,
14979                             SourceRange ParenRange) {
14980   bool Elidable = false;
14981 
14982   // C++0x [class.copy]p34:
14983   //   When certain criteria are met, an implementation is allowed to
14984   //   omit the copy/move construction of a class object, even if the
14985   //   copy/move constructor and/or destructor for the object have
14986   //   side effects. [...]
14987   //     - when a temporary class object that has not been bound to a
14988   //       reference (12.2) would be copied/moved to a class object
14989   //       with the same cv-unqualified type, the copy/move operation
14990   //       can be omitted by constructing the temporary object
14991   //       directly into the target of the omitted copy/move
14992   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
14993       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
14994     Expr *SubExpr = ExprArgs[0];
14995     Elidable = SubExpr->isTemporaryObject(
14996         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
14997   }
14998 
14999   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15000                                FoundDecl, Constructor,
15001                                Elidable, ExprArgs, HadMultipleCandidates,
15002                                IsListInitialization,
15003                                IsStdInitListInitialization, RequiresZeroInit,
15004                                ConstructKind, ParenRange);
15005 }
15006 
15007 ExprResult
15008 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15009                             NamedDecl *FoundDecl,
15010                             CXXConstructorDecl *Constructor,
15011                             bool Elidable,
15012                             MultiExprArg ExprArgs,
15013                             bool HadMultipleCandidates,
15014                             bool IsListInitialization,
15015                             bool IsStdInitListInitialization,
15016                             bool RequiresZeroInit,
15017                             unsigned ConstructKind,
15018                             SourceRange ParenRange) {
15019   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15020     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15021     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15022       return ExprError();
15023   }
15024 
15025   return BuildCXXConstructExpr(
15026       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15027       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15028       RequiresZeroInit, ConstructKind, ParenRange);
15029 }
15030 
15031 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15032 /// including handling of its default argument expressions.
15033 ExprResult
15034 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15035                             CXXConstructorDecl *Constructor,
15036                             bool Elidable,
15037                             MultiExprArg ExprArgs,
15038                             bool HadMultipleCandidates,
15039                             bool IsListInitialization,
15040                             bool IsStdInitListInitialization,
15041                             bool RequiresZeroInit,
15042                             unsigned ConstructKind,
15043                             SourceRange ParenRange) {
15044   assert(declaresSameEntity(
15045              Constructor->getParent(),
15046              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15047          "given constructor for wrong type");
15048   MarkFunctionReferenced(ConstructLoc, Constructor);
15049   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15050     return ExprError();
15051   if (getLangOpts().SYCLIsDevice &&
15052       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15053     return ExprError();
15054 
15055   return CheckForImmediateInvocation(
15056       CXXConstructExpr::Create(
15057           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15058           HadMultipleCandidates, IsListInitialization,
15059           IsStdInitListInitialization, RequiresZeroInit,
15060           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15061           ParenRange),
15062       Constructor);
15063 }
15064 
15065 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15066   assert(Field->hasInClassInitializer());
15067 
15068   // If we already have the in-class initializer nothing needs to be done.
15069   if (Field->getInClassInitializer())
15070     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15071 
15072   // If we might have already tried and failed to instantiate, don't try again.
15073   if (Field->isInvalidDecl())
15074     return ExprError();
15075 
15076   // Maybe we haven't instantiated the in-class initializer. Go check the
15077   // pattern FieldDecl to see if it has one.
15078   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15079 
15080   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15081     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15082     DeclContext::lookup_result Lookup =
15083         ClassPattern->lookup(Field->getDeclName());
15084 
15085     FieldDecl *Pattern = nullptr;
15086     for (auto L : Lookup) {
15087       if (isa<FieldDecl>(L)) {
15088         Pattern = cast<FieldDecl>(L);
15089         break;
15090       }
15091     }
15092     assert(Pattern && "We must have set the Pattern!");
15093 
15094     if (!Pattern->hasInClassInitializer() ||
15095         InstantiateInClassInitializer(Loc, Field, Pattern,
15096                                       getTemplateInstantiationArgs(Field))) {
15097       // Don't diagnose this again.
15098       Field->setInvalidDecl();
15099       return ExprError();
15100     }
15101     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15102   }
15103 
15104   // DR1351:
15105   //   If the brace-or-equal-initializer of a non-static data member
15106   //   invokes a defaulted default constructor of its class or of an
15107   //   enclosing class in a potentially evaluated subexpression, the
15108   //   program is ill-formed.
15109   //
15110   // This resolution is unworkable: the exception specification of the
15111   // default constructor can be needed in an unevaluated context, in
15112   // particular, in the operand of a noexcept-expression, and we can be
15113   // unable to compute an exception specification for an enclosed class.
15114   //
15115   // Any attempt to resolve the exception specification of a defaulted default
15116   // constructor before the initializer is lexically complete will ultimately
15117   // come here at which point we can diagnose it.
15118   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15119   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15120       << OutermostClass << Field;
15121   Diag(Field->getEndLoc(),
15122        diag::note_default_member_initializer_not_yet_parsed);
15123   // Recover by marking the field invalid, unless we're in a SFINAE context.
15124   if (!isSFINAEContext())
15125     Field->setInvalidDecl();
15126   return ExprError();
15127 }
15128 
15129 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15130   if (VD->isInvalidDecl()) return;
15131   // If initializing the variable failed, don't also diagnose problems with
15132   // the desctructor, they're likely related.
15133   if (VD->getInit() && VD->getInit()->containsErrors())
15134     return;
15135 
15136   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15137   if (ClassDecl->isInvalidDecl()) return;
15138   if (ClassDecl->hasIrrelevantDestructor()) return;
15139   if (ClassDecl->isDependentContext()) return;
15140 
15141   if (VD->isNoDestroy(getASTContext()))
15142     return;
15143 
15144   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15145 
15146   // If this is an array, we'll require the destructor during initialization, so
15147   // we can skip over this. We still want to emit exit-time destructor warnings
15148   // though.
15149   if (!VD->getType()->isArrayType()) {
15150     MarkFunctionReferenced(VD->getLocation(), Destructor);
15151     CheckDestructorAccess(VD->getLocation(), Destructor,
15152                           PDiag(diag::err_access_dtor_var)
15153                               << VD->getDeclName() << VD->getType());
15154     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15155   }
15156 
15157   if (Destructor->isTrivial()) return;
15158 
15159   // If the destructor is constexpr, check whether the variable has constant
15160   // destruction now.
15161   if (Destructor->isConstexpr()) {
15162     bool HasConstantInit = false;
15163     if (VD->getInit() && !VD->getInit()->isValueDependent())
15164       HasConstantInit = VD->evaluateValue();
15165     SmallVector<PartialDiagnosticAt, 8> Notes;
15166     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15167         HasConstantInit) {
15168       Diag(VD->getLocation(),
15169            diag::err_constexpr_var_requires_const_destruction) << VD;
15170       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15171         Diag(Notes[I].first, Notes[I].second);
15172     }
15173   }
15174 
15175   if (!VD->hasGlobalStorage()) return;
15176 
15177   // Emit warning for non-trivial dtor in global scope (a real global,
15178   // class-static, function-static).
15179   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15180 
15181   // TODO: this should be re-enabled for static locals by !CXAAtExit
15182   if (!VD->isStaticLocal())
15183     Diag(VD->getLocation(), diag::warn_global_destructor);
15184 }
15185 
15186 /// Given a constructor and the set of arguments provided for the
15187 /// constructor, convert the arguments and add any required default arguments
15188 /// to form a proper call to this constructor.
15189 ///
15190 /// \returns true if an error occurred, false otherwise.
15191 bool
15192 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15193                               MultiExprArg ArgsPtr,
15194                               SourceLocation Loc,
15195                               SmallVectorImpl<Expr*> &ConvertedArgs,
15196                               bool AllowExplicit,
15197                               bool IsListInitialization) {
15198   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15199   unsigned NumArgs = ArgsPtr.size();
15200   Expr **Args = ArgsPtr.data();
15201 
15202   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15203   unsigned NumParams = Proto->getNumParams();
15204 
15205   // If too few arguments are available, we'll fill in the rest with defaults.
15206   if (NumArgs < NumParams)
15207     ConvertedArgs.reserve(NumParams);
15208   else
15209     ConvertedArgs.reserve(NumArgs);
15210 
15211   VariadicCallType CallType =
15212     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15213   SmallVector<Expr *, 8> AllArgs;
15214   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15215                                         Proto, 0,
15216                                         llvm::makeArrayRef(Args, NumArgs),
15217                                         AllArgs,
15218                                         CallType, AllowExplicit,
15219                                         IsListInitialization);
15220   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15221 
15222   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15223 
15224   CheckConstructorCall(Constructor,
15225                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15226                        Proto, Loc);
15227 
15228   return Invalid;
15229 }
15230 
15231 static inline bool
15232 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15233                                        const FunctionDecl *FnDecl) {
15234   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15235   if (isa<NamespaceDecl>(DC)) {
15236     return SemaRef.Diag(FnDecl->getLocation(),
15237                         diag::err_operator_new_delete_declared_in_namespace)
15238       << FnDecl->getDeclName();
15239   }
15240 
15241   if (isa<TranslationUnitDecl>(DC) &&
15242       FnDecl->getStorageClass() == SC_Static) {
15243     return SemaRef.Diag(FnDecl->getLocation(),
15244                         diag::err_operator_new_delete_declared_static)
15245       << FnDecl->getDeclName();
15246   }
15247 
15248   return false;
15249 }
15250 
15251 static QualType
15252 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
15253   QualType QTy = PtrTy->getPointeeType();
15254   QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
15255   return SemaRef.Context.getPointerType(QTy);
15256 }
15257 
15258 static inline bool
15259 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15260                             CanQualType ExpectedResultType,
15261                             CanQualType ExpectedFirstParamType,
15262                             unsigned DependentParamTypeDiag,
15263                             unsigned InvalidParamTypeDiag) {
15264   QualType ResultType =
15265       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15266 
15267   // The operator is valid on any address space for OpenCL.
15268   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15269     if (auto *PtrTy = ResultType->getAs<PointerType>()) {
15270       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15271     }
15272   }
15273 
15274   // Check that the result type is what we expect.
15275   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15276     // Reject even if the type is dependent; an operator delete function is
15277     // required to have a non-dependent result type.
15278     return SemaRef.Diag(
15279                FnDecl->getLocation(),
15280                ResultType->isDependentType()
15281                    ? diag::err_operator_new_delete_dependent_result_type
15282                    : diag::err_operator_new_delete_invalid_result_type)
15283            << FnDecl->getDeclName() << ExpectedResultType;
15284   }
15285 
15286   // A function template must have at least 2 parameters.
15287   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15288     return SemaRef.Diag(FnDecl->getLocation(),
15289                       diag::err_operator_new_delete_template_too_few_parameters)
15290         << FnDecl->getDeclName();
15291 
15292   // The function decl must have at least 1 parameter.
15293   if (FnDecl->getNumParams() == 0)
15294     return SemaRef.Diag(FnDecl->getLocation(),
15295                         diag::err_operator_new_delete_too_few_parameters)
15296       << FnDecl->getDeclName();
15297 
15298   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15299   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15300     // The operator is valid on any address space for OpenCL.
15301     if (auto *PtrTy =
15302             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
15303       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15304     }
15305   }
15306 
15307   // Check that the first parameter type is what we expect.
15308   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15309       ExpectedFirstParamType) {
15310     // The first parameter type is not allowed to be dependent. As a tentative
15311     // DR resolution, we allow a dependent parameter type if it is the right
15312     // type anyway, to allow destroying operator delete in class templates.
15313     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15314                                                    ? DependentParamTypeDiag
15315                                                    : InvalidParamTypeDiag)
15316            << FnDecl->getDeclName() << ExpectedFirstParamType;
15317   }
15318 
15319   return false;
15320 }
15321 
15322 static bool
15323 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15324   // C++ [basic.stc.dynamic.allocation]p1:
15325   //   A program is ill-formed if an allocation function is declared in a
15326   //   namespace scope other than global scope or declared static in global
15327   //   scope.
15328   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15329     return true;
15330 
15331   CanQualType SizeTy =
15332     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15333 
15334   // C++ [basic.stc.dynamic.allocation]p1:
15335   //  The return type shall be void*. The first parameter shall have type
15336   //  std::size_t.
15337   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15338                                   SizeTy,
15339                                   diag::err_operator_new_dependent_param_type,
15340                                   diag::err_operator_new_param_type))
15341     return true;
15342 
15343   // C++ [basic.stc.dynamic.allocation]p1:
15344   //  The first parameter shall not have an associated default argument.
15345   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15346     return SemaRef.Diag(FnDecl->getLocation(),
15347                         diag::err_operator_new_default_arg)
15348       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15349 
15350   return false;
15351 }
15352 
15353 static bool
15354 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15355   // C++ [basic.stc.dynamic.deallocation]p1:
15356   //   A program is ill-formed if deallocation functions are declared in a
15357   //   namespace scope other than global scope or declared static in global
15358   //   scope.
15359   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15360     return true;
15361 
15362   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15363 
15364   // C++ P0722:
15365   //   Within a class C, the first parameter of a destroying operator delete
15366   //   shall be of type C *. The first parameter of any other deallocation
15367   //   function shall be of type void *.
15368   CanQualType ExpectedFirstParamType =
15369       MD && MD->isDestroyingOperatorDelete()
15370           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15371                 SemaRef.Context.getRecordType(MD->getParent())))
15372           : SemaRef.Context.VoidPtrTy;
15373 
15374   // C++ [basic.stc.dynamic.deallocation]p2:
15375   //   Each deallocation function shall return void
15376   if (CheckOperatorNewDeleteTypes(
15377           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15378           diag::err_operator_delete_dependent_param_type,
15379           diag::err_operator_delete_param_type))
15380     return true;
15381 
15382   // C++ P0722:
15383   //   A destroying operator delete shall be a usual deallocation function.
15384   if (MD && !MD->getParent()->isDependentContext() &&
15385       MD->isDestroyingOperatorDelete() &&
15386       !SemaRef.isUsualDeallocationFunction(MD)) {
15387     SemaRef.Diag(MD->getLocation(),
15388                  diag::err_destroying_operator_delete_not_usual);
15389     return true;
15390   }
15391 
15392   return false;
15393 }
15394 
15395 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15396 /// of this overloaded operator is well-formed. If so, returns false;
15397 /// otherwise, emits appropriate diagnostics and returns true.
15398 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15399   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15400          "Expected an overloaded operator declaration");
15401 
15402   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15403 
15404   // C++ [over.oper]p5:
15405   //   The allocation and deallocation functions, operator new,
15406   //   operator new[], operator delete and operator delete[], are
15407   //   described completely in 3.7.3. The attributes and restrictions
15408   //   found in the rest of this subclause do not apply to them unless
15409   //   explicitly stated in 3.7.3.
15410   if (Op == OO_Delete || Op == OO_Array_Delete)
15411     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15412 
15413   if (Op == OO_New || Op == OO_Array_New)
15414     return CheckOperatorNewDeclaration(*this, FnDecl);
15415 
15416   // C++ [over.oper]p6:
15417   //   An operator function shall either be a non-static member
15418   //   function or be a non-member function and have at least one
15419   //   parameter whose type is a class, a reference to a class, an
15420   //   enumeration, or a reference to an enumeration.
15421   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15422     if (MethodDecl->isStatic())
15423       return Diag(FnDecl->getLocation(),
15424                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15425   } else {
15426     bool ClassOrEnumParam = false;
15427     for (auto Param : FnDecl->parameters()) {
15428       QualType ParamType = Param->getType().getNonReferenceType();
15429       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15430           ParamType->isEnumeralType()) {
15431         ClassOrEnumParam = true;
15432         break;
15433       }
15434     }
15435 
15436     if (!ClassOrEnumParam)
15437       return Diag(FnDecl->getLocation(),
15438                   diag::err_operator_overload_needs_class_or_enum)
15439         << FnDecl->getDeclName();
15440   }
15441 
15442   // C++ [over.oper]p8:
15443   //   An operator function cannot have default arguments (8.3.6),
15444   //   except where explicitly stated below.
15445   //
15446   // Only the function-call operator allows default arguments
15447   // (C++ [over.call]p1).
15448   if (Op != OO_Call) {
15449     for (auto Param : FnDecl->parameters()) {
15450       if (Param->hasDefaultArg())
15451         return Diag(Param->getLocation(),
15452                     diag::err_operator_overload_default_arg)
15453           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15454     }
15455   }
15456 
15457   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15458     { false, false, false }
15459 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15460     , { Unary, Binary, MemberOnly }
15461 #include "clang/Basic/OperatorKinds.def"
15462   };
15463 
15464   bool CanBeUnaryOperator = OperatorUses[Op][0];
15465   bool CanBeBinaryOperator = OperatorUses[Op][1];
15466   bool MustBeMemberOperator = OperatorUses[Op][2];
15467 
15468   // C++ [over.oper]p8:
15469   //   [...] Operator functions cannot have more or fewer parameters
15470   //   than the number required for the corresponding operator, as
15471   //   described in the rest of this subclause.
15472   unsigned NumParams = FnDecl->getNumParams()
15473                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15474   if (Op != OO_Call &&
15475       ((NumParams == 1 && !CanBeUnaryOperator) ||
15476        (NumParams == 2 && !CanBeBinaryOperator) ||
15477        (NumParams < 1) || (NumParams > 2))) {
15478     // We have the wrong number of parameters.
15479     unsigned ErrorKind;
15480     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15481       ErrorKind = 2;  // 2 -> unary or binary.
15482     } else if (CanBeUnaryOperator) {
15483       ErrorKind = 0;  // 0 -> unary
15484     } else {
15485       assert(CanBeBinaryOperator &&
15486              "All non-call overloaded operators are unary or binary!");
15487       ErrorKind = 1;  // 1 -> binary
15488     }
15489 
15490     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15491       << FnDecl->getDeclName() << NumParams << ErrorKind;
15492   }
15493 
15494   // Overloaded operators other than operator() cannot be variadic.
15495   if (Op != OO_Call &&
15496       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15497     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15498       << FnDecl->getDeclName();
15499   }
15500 
15501   // Some operators must be non-static member functions.
15502   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15503     return Diag(FnDecl->getLocation(),
15504                 diag::err_operator_overload_must_be_member)
15505       << FnDecl->getDeclName();
15506   }
15507 
15508   // C++ [over.inc]p1:
15509   //   The user-defined function called operator++ implements the
15510   //   prefix and postfix ++ operator. If this function is a member
15511   //   function with no parameters, or a non-member function with one
15512   //   parameter of class or enumeration type, it defines the prefix
15513   //   increment operator ++ for objects of that type. If the function
15514   //   is a member function with one parameter (which shall be of type
15515   //   int) or a non-member function with two parameters (the second
15516   //   of which shall be of type int), it defines the postfix
15517   //   increment operator ++ for objects of that type.
15518   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15519     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15520     QualType ParamType = LastParam->getType();
15521 
15522     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15523         !ParamType->isDependentType())
15524       return Diag(LastParam->getLocation(),
15525                   diag::err_operator_overload_post_incdec_must_be_int)
15526         << LastParam->getType() << (Op == OO_MinusMinus);
15527   }
15528 
15529   return false;
15530 }
15531 
15532 static bool
15533 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15534                                           FunctionTemplateDecl *TpDecl) {
15535   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15536 
15537   // Must have one or two template parameters.
15538   if (TemplateParams->size() == 1) {
15539     NonTypeTemplateParmDecl *PmDecl =
15540         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15541 
15542     // The template parameter must be a char parameter pack.
15543     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15544         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15545       return false;
15546 
15547     // C++20 [over.literal]p5:
15548     //   A string literal operator template is a literal operator template
15549     //   whose template-parameter-list comprises a single non-type
15550     //   template-parameter of class type.
15551     //
15552     // As a DR resolution, we also allow placeholders for deduced class
15553     // template specializations.
15554     if (SemaRef.getLangOpts().CPlusPlus20 &&
15555         !PmDecl->isTemplateParameterPack() &&
15556         (PmDecl->getType()->isRecordType() ||
15557          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
15558       return false;
15559   } else if (TemplateParams->size() == 2) {
15560     TemplateTypeParmDecl *PmType =
15561         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15562     NonTypeTemplateParmDecl *PmArgs =
15563         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15564 
15565     // The second template parameter must be a parameter pack with the
15566     // first template parameter as its type.
15567     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15568         PmArgs->isTemplateParameterPack()) {
15569       const TemplateTypeParmType *TArgs =
15570           PmArgs->getType()->getAs<TemplateTypeParmType>();
15571       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15572           TArgs->getIndex() == PmType->getIndex()) {
15573         if (!SemaRef.inTemplateInstantiation())
15574           SemaRef.Diag(TpDecl->getLocation(),
15575                        diag::ext_string_literal_operator_template);
15576         return false;
15577       }
15578     }
15579   }
15580 
15581   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15582                diag::err_literal_operator_template)
15583       << TpDecl->getTemplateParameters()->getSourceRange();
15584   return true;
15585 }
15586 
15587 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15588 /// of this literal operator function is well-formed. If so, returns
15589 /// false; otherwise, emits appropriate diagnostics and returns true.
15590 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15591   if (isa<CXXMethodDecl>(FnDecl)) {
15592     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15593       << FnDecl->getDeclName();
15594     return true;
15595   }
15596 
15597   if (FnDecl->isExternC()) {
15598     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15599     if (const LinkageSpecDecl *LSD =
15600             FnDecl->getDeclContext()->getExternCContext())
15601       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15602     return true;
15603   }
15604 
15605   // This might be the definition of a literal operator template.
15606   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15607 
15608   // This might be a specialization of a literal operator template.
15609   if (!TpDecl)
15610     TpDecl = FnDecl->getPrimaryTemplate();
15611 
15612   // template <char...> type operator "" name() and
15613   // template <class T, T...> type operator "" name() are the only valid
15614   // template signatures, and the only valid signatures with no parameters.
15615   //
15616   // C++20 also allows template <SomeClass T> type operator "" name().
15617   if (TpDecl) {
15618     if (FnDecl->param_size() != 0) {
15619       Diag(FnDecl->getLocation(),
15620            diag::err_literal_operator_template_with_params);
15621       return true;
15622     }
15623 
15624     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15625       return true;
15626 
15627   } else if (FnDecl->param_size() == 1) {
15628     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15629 
15630     QualType ParamType = Param->getType().getUnqualifiedType();
15631 
15632     // Only unsigned long long int, long double, any character type, and const
15633     // char * are allowed as the only parameters.
15634     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15635         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15636         Context.hasSameType(ParamType, Context.CharTy) ||
15637         Context.hasSameType(ParamType, Context.WideCharTy) ||
15638         Context.hasSameType(ParamType, Context.Char8Ty) ||
15639         Context.hasSameType(ParamType, Context.Char16Ty) ||
15640         Context.hasSameType(ParamType, Context.Char32Ty)) {
15641     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15642       QualType InnerType = Ptr->getPointeeType();
15643 
15644       // Pointer parameter must be a const char *.
15645       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15646                                 Context.CharTy) &&
15647             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15648         Diag(Param->getSourceRange().getBegin(),
15649              diag::err_literal_operator_param)
15650             << ParamType << "'const char *'" << Param->getSourceRange();
15651         return true;
15652       }
15653 
15654     } else if (ParamType->isRealFloatingType()) {
15655       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15656           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15657       return true;
15658 
15659     } else if (ParamType->isIntegerType()) {
15660       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15661           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15662       return true;
15663 
15664     } else {
15665       Diag(Param->getSourceRange().getBegin(),
15666            diag::err_literal_operator_invalid_param)
15667           << ParamType << Param->getSourceRange();
15668       return true;
15669     }
15670 
15671   } else if (FnDecl->param_size() == 2) {
15672     FunctionDecl::param_iterator Param = FnDecl->param_begin();
15673 
15674     // First, verify that the first parameter is correct.
15675 
15676     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15677 
15678     // Two parameter function must have a pointer to const as a
15679     // first parameter; let's strip those qualifiers.
15680     const PointerType *PT = FirstParamType->getAs<PointerType>();
15681 
15682     if (!PT) {
15683       Diag((*Param)->getSourceRange().getBegin(),
15684            diag::err_literal_operator_param)
15685           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15686       return true;
15687     }
15688 
15689     QualType PointeeType = PT->getPointeeType();
15690     // First parameter must be const
15691     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15692       Diag((*Param)->getSourceRange().getBegin(),
15693            diag::err_literal_operator_param)
15694           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15695       return true;
15696     }
15697 
15698     QualType InnerType = PointeeType.getUnqualifiedType();
15699     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15700     // const char32_t* are allowed as the first parameter to a two-parameter
15701     // function
15702     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15703           Context.hasSameType(InnerType, Context.WideCharTy) ||
15704           Context.hasSameType(InnerType, Context.Char8Ty) ||
15705           Context.hasSameType(InnerType, Context.Char16Ty) ||
15706           Context.hasSameType(InnerType, Context.Char32Ty))) {
15707       Diag((*Param)->getSourceRange().getBegin(),
15708            diag::err_literal_operator_param)
15709           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15710       return true;
15711     }
15712 
15713     // Move on to the second and final parameter.
15714     ++Param;
15715 
15716     // The second parameter must be a std::size_t.
15717     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15718     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15719       Diag((*Param)->getSourceRange().getBegin(),
15720            diag::err_literal_operator_param)
15721           << SecondParamType << Context.getSizeType()
15722           << (*Param)->getSourceRange();
15723       return true;
15724     }
15725   } else {
15726     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15727     return true;
15728   }
15729 
15730   // Parameters are good.
15731 
15732   // A parameter-declaration-clause containing a default argument is not
15733   // equivalent to any of the permitted forms.
15734   for (auto Param : FnDecl->parameters()) {
15735     if (Param->hasDefaultArg()) {
15736       Diag(Param->getDefaultArgRange().getBegin(),
15737            diag::err_literal_operator_default_argument)
15738         << Param->getDefaultArgRange();
15739       break;
15740     }
15741   }
15742 
15743   StringRef LiteralName
15744     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15745   if (LiteralName[0] != '_' &&
15746       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15747     // C++11 [usrlit.suffix]p1:
15748     //   Literal suffix identifiers that do not start with an underscore
15749     //   are reserved for future standardization.
15750     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15751       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15752   }
15753 
15754   return false;
15755 }
15756 
15757 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15758 /// linkage specification, including the language and (if present)
15759 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15760 /// language string literal. LBraceLoc, if valid, provides the location of
15761 /// the '{' brace. Otherwise, this linkage specification does not
15762 /// have any braces.
15763 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15764                                            Expr *LangStr,
15765                                            SourceLocation LBraceLoc) {
15766   StringLiteral *Lit = cast<StringLiteral>(LangStr);
15767   if (!Lit->isAscii()) {
15768     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15769       << LangStr->getSourceRange();
15770     return nullptr;
15771   }
15772 
15773   StringRef Lang = Lit->getString();
15774   LinkageSpecDecl::LanguageIDs Language;
15775   if (Lang == "C")
15776     Language = LinkageSpecDecl::lang_c;
15777   else if (Lang == "C++")
15778     Language = LinkageSpecDecl::lang_cxx;
15779   else {
15780     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15781       << LangStr->getSourceRange();
15782     return nullptr;
15783   }
15784 
15785   // FIXME: Add all the various semantics of linkage specifications
15786 
15787   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15788                                                LangStr->getExprLoc(), Language,
15789                                                LBraceLoc.isValid());
15790   CurContext->addDecl(D);
15791   PushDeclContext(S, D);
15792   return D;
15793 }
15794 
15795 /// ActOnFinishLinkageSpecification - Complete the definition of
15796 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15797 /// valid, it's the position of the closing '}' brace in a linkage
15798 /// specification that uses braces.
15799 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15800                                             Decl *LinkageSpec,
15801                                             SourceLocation RBraceLoc) {
15802   if (RBraceLoc.isValid()) {
15803     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15804     LSDecl->setRBraceLoc(RBraceLoc);
15805   }
15806   PopDeclContext();
15807   return LinkageSpec;
15808 }
15809 
15810 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15811                                   const ParsedAttributesView &AttrList,
15812                                   SourceLocation SemiLoc) {
15813   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15814   // Attribute declarations appertain to empty declaration so we handle
15815   // them here.
15816   ProcessDeclAttributeList(S, ED, AttrList);
15817 
15818   CurContext->addDecl(ED);
15819   return ED;
15820 }
15821 
15822 /// Perform semantic analysis for the variable declaration that
15823 /// occurs within a C++ catch clause, returning the newly-created
15824 /// variable.
15825 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15826                                          TypeSourceInfo *TInfo,
15827                                          SourceLocation StartLoc,
15828                                          SourceLocation Loc,
15829                                          IdentifierInfo *Name) {
15830   bool Invalid = false;
15831   QualType ExDeclType = TInfo->getType();
15832 
15833   // Arrays and functions decay.
15834   if (ExDeclType->isArrayType())
15835     ExDeclType = Context.getArrayDecayedType(ExDeclType);
15836   else if (ExDeclType->isFunctionType())
15837     ExDeclType = Context.getPointerType(ExDeclType);
15838 
15839   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15840   // The exception-declaration shall not denote a pointer or reference to an
15841   // incomplete type, other than [cv] void*.
15842   // N2844 forbids rvalue references.
15843   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15844     Diag(Loc, diag::err_catch_rvalue_ref);
15845     Invalid = true;
15846   }
15847 
15848   if (ExDeclType->isVariablyModifiedType()) {
15849     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15850     Invalid = true;
15851   }
15852 
15853   QualType BaseType = ExDeclType;
15854   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15855   unsigned DK = diag::err_catch_incomplete;
15856   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15857     BaseType = Ptr->getPointeeType();
15858     Mode = 1;
15859     DK = diag::err_catch_incomplete_ptr;
15860   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15861     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15862     BaseType = Ref->getPointeeType();
15863     Mode = 2;
15864     DK = diag::err_catch_incomplete_ref;
15865   }
15866   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15867       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15868     Invalid = true;
15869 
15870   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15871     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15872     Invalid = true;
15873   }
15874 
15875   if (!Invalid && !ExDeclType->isDependentType() &&
15876       RequireNonAbstractType(Loc, ExDeclType,
15877                              diag::err_abstract_type_in_decl,
15878                              AbstractVariableType))
15879     Invalid = true;
15880 
15881   // Only the non-fragile NeXT runtime currently supports C++ catches
15882   // of ObjC types, and no runtime supports catching ObjC types by value.
15883   if (!Invalid && getLangOpts().ObjC) {
15884     QualType T = ExDeclType;
15885     if (const ReferenceType *RT = T->getAs<ReferenceType>())
15886       T = RT->getPointeeType();
15887 
15888     if (T->isObjCObjectType()) {
15889       Diag(Loc, diag::err_objc_object_catch);
15890       Invalid = true;
15891     } else if (T->isObjCObjectPointerType()) {
15892       // FIXME: should this be a test for macosx-fragile specifically?
15893       if (getLangOpts().ObjCRuntime.isFragile())
15894         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15895     }
15896   }
15897 
15898   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15899                                     ExDeclType, TInfo, SC_None);
15900   ExDecl->setExceptionVariable(true);
15901 
15902   // In ARC, infer 'retaining' for variables of retainable type.
15903   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15904     Invalid = true;
15905 
15906   if (!Invalid && !ExDeclType->isDependentType()) {
15907     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15908       // Insulate this from anything else we might currently be parsing.
15909       EnterExpressionEvaluationContext scope(
15910           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15911 
15912       // C++ [except.handle]p16:
15913       //   The object declared in an exception-declaration or, if the
15914       //   exception-declaration does not specify a name, a temporary (12.2) is
15915       //   copy-initialized (8.5) from the exception object. [...]
15916       //   The object is destroyed when the handler exits, after the destruction
15917       //   of any automatic objects initialized within the handler.
15918       //
15919       // We just pretend to initialize the object with itself, then make sure
15920       // it can be destroyed later.
15921       QualType initType = Context.getExceptionObjectType(ExDeclType);
15922 
15923       InitializedEntity entity =
15924         InitializedEntity::InitializeVariable(ExDecl);
15925       InitializationKind initKind =
15926         InitializationKind::CreateCopy(Loc, SourceLocation());
15927 
15928       Expr *opaqueValue =
15929         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15930       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15931       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15932       if (result.isInvalid())
15933         Invalid = true;
15934       else {
15935         // If the constructor used was non-trivial, set this as the
15936         // "initializer".
15937         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15938         if (!construct->getConstructor()->isTrivial()) {
15939           Expr *init = MaybeCreateExprWithCleanups(construct);
15940           ExDecl->setInit(init);
15941         }
15942 
15943         // And make sure it's destructable.
15944         FinalizeVarWithDestructor(ExDecl, recordType);
15945       }
15946     }
15947   }
15948 
15949   if (Invalid)
15950     ExDecl->setInvalidDecl();
15951 
15952   return ExDecl;
15953 }
15954 
15955 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15956 /// handler.
15957 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15958   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15959   bool Invalid = D.isInvalidType();
15960 
15961   // Check for unexpanded parameter packs.
15962   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15963                                       UPPC_ExceptionType)) {
15964     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15965                                              D.getIdentifierLoc());
15966     Invalid = true;
15967   }
15968 
15969   IdentifierInfo *II = D.getIdentifier();
15970   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
15971                                              LookupOrdinaryName,
15972                                              ForVisibleRedeclaration)) {
15973     // The scope should be freshly made just for us. There is just no way
15974     // it contains any previous declaration, except for function parameters in
15975     // a function-try-block's catch statement.
15976     assert(!S->isDeclScope(PrevDecl));
15977     if (isDeclInScope(PrevDecl, CurContext, S)) {
15978       Diag(D.getIdentifierLoc(), diag::err_redefinition)
15979         << D.getIdentifier();
15980       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15981       Invalid = true;
15982     } else if (PrevDecl->isTemplateParameter())
15983       // Maybe we will complain about the shadowed template parameter.
15984       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15985   }
15986 
15987   if (D.getCXXScopeSpec().isSet() && !Invalid) {
15988     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
15989       << D.getCXXScopeSpec().getRange();
15990     Invalid = true;
15991   }
15992 
15993   VarDecl *ExDecl = BuildExceptionDeclaration(
15994       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
15995   if (Invalid)
15996     ExDecl->setInvalidDecl();
15997 
15998   // Add the exception declaration into this scope.
15999   if (II)
16000     PushOnScopeChains(ExDecl, S);
16001   else
16002     CurContext->addDecl(ExDecl);
16003 
16004   ProcessDeclAttributes(S, ExDecl, D);
16005   return ExDecl;
16006 }
16007 
16008 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16009                                          Expr *AssertExpr,
16010                                          Expr *AssertMessageExpr,
16011                                          SourceLocation RParenLoc) {
16012   StringLiteral *AssertMessage =
16013       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16014 
16015   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16016     return nullptr;
16017 
16018   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16019                                       AssertMessage, RParenLoc, false);
16020 }
16021 
16022 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16023                                          Expr *AssertExpr,
16024                                          StringLiteral *AssertMessage,
16025                                          SourceLocation RParenLoc,
16026                                          bool Failed) {
16027   assert(AssertExpr != nullptr && "Expected non-null condition");
16028   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16029       !Failed) {
16030     // In a static_assert-declaration, the constant-expression shall be a
16031     // constant expression that can be contextually converted to bool.
16032     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16033     if (Converted.isInvalid())
16034       Failed = true;
16035 
16036     ExprResult FullAssertExpr =
16037         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16038                             /*DiscardedValue*/ false,
16039                             /*IsConstexpr*/ true);
16040     if (FullAssertExpr.isInvalid())
16041       Failed = true;
16042     else
16043       AssertExpr = FullAssertExpr.get();
16044 
16045     llvm::APSInt Cond;
16046     if (!Failed && VerifyIntegerConstantExpression(
16047                        AssertExpr, &Cond,
16048                        diag::err_static_assert_expression_is_not_constant)
16049                        .isInvalid())
16050       Failed = true;
16051 
16052     if (!Failed && !Cond) {
16053       SmallString<256> MsgBuffer;
16054       llvm::raw_svector_ostream Msg(MsgBuffer);
16055       if (AssertMessage)
16056         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16057 
16058       Expr *InnerCond = nullptr;
16059       std::string InnerCondDescription;
16060       std::tie(InnerCond, InnerCondDescription) =
16061         findFailedBooleanCondition(Converted.get());
16062       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16063         // Drill down into concept specialization expressions to see why they
16064         // weren't satisfied.
16065         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16066           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16067         ConstraintSatisfaction Satisfaction;
16068         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16069           DiagnoseUnsatisfiedConstraint(Satisfaction);
16070       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16071                            && !isa<IntegerLiteral>(InnerCond)) {
16072         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16073           << InnerCondDescription << !AssertMessage
16074           << Msg.str() << InnerCond->getSourceRange();
16075       } else {
16076         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16077           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16078       }
16079       Failed = true;
16080     }
16081   } else {
16082     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16083                                                     /*DiscardedValue*/false,
16084                                                     /*IsConstexpr*/true);
16085     if (FullAssertExpr.isInvalid())
16086       Failed = true;
16087     else
16088       AssertExpr = FullAssertExpr.get();
16089   }
16090 
16091   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16092                                         AssertExpr, AssertMessage, RParenLoc,
16093                                         Failed);
16094 
16095   CurContext->addDecl(Decl);
16096   return Decl;
16097 }
16098 
16099 /// Perform semantic analysis of the given friend type declaration.
16100 ///
16101 /// \returns A friend declaration that.
16102 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16103                                       SourceLocation FriendLoc,
16104                                       TypeSourceInfo *TSInfo) {
16105   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16106 
16107   QualType T = TSInfo->getType();
16108   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16109 
16110   // C++03 [class.friend]p2:
16111   //   An elaborated-type-specifier shall be used in a friend declaration
16112   //   for a class.*
16113   //
16114   //   * The class-key of the elaborated-type-specifier is required.
16115   if (!CodeSynthesisContexts.empty()) {
16116     // Do not complain about the form of friend template types during any kind
16117     // of code synthesis. For template instantiation, we will have complained
16118     // when the template was defined.
16119   } else {
16120     if (!T->isElaboratedTypeSpecifier()) {
16121       // If we evaluated the type to a record type, suggest putting
16122       // a tag in front.
16123       if (const RecordType *RT = T->getAs<RecordType>()) {
16124         RecordDecl *RD = RT->getDecl();
16125 
16126         SmallString<16> InsertionText(" ");
16127         InsertionText += RD->getKindName();
16128 
16129         Diag(TypeRange.getBegin(),
16130              getLangOpts().CPlusPlus11 ?
16131                diag::warn_cxx98_compat_unelaborated_friend_type :
16132                diag::ext_unelaborated_friend_type)
16133           << (unsigned) RD->getTagKind()
16134           << T
16135           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16136                                         InsertionText);
16137       } else {
16138         Diag(FriendLoc,
16139              getLangOpts().CPlusPlus11 ?
16140                diag::warn_cxx98_compat_nonclass_type_friend :
16141                diag::ext_nonclass_type_friend)
16142           << T
16143           << TypeRange;
16144       }
16145     } else if (T->getAs<EnumType>()) {
16146       Diag(FriendLoc,
16147            getLangOpts().CPlusPlus11 ?
16148              diag::warn_cxx98_compat_enum_friend :
16149              diag::ext_enum_friend)
16150         << T
16151         << TypeRange;
16152     }
16153 
16154     // C++11 [class.friend]p3:
16155     //   A friend declaration that does not declare a function shall have one
16156     //   of the following forms:
16157     //     friend elaborated-type-specifier ;
16158     //     friend simple-type-specifier ;
16159     //     friend typename-specifier ;
16160     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16161       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16162   }
16163 
16164   //   If the type specifier in a friend declaration designates a (possibly
16165   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16166   //   the friend declaration is ignored.
16167   return FriendDecl::Create(Context, CurContext,
16168                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16169                             FriendLoc);
16170 }
16171 
16172 /// Handle a friend tag declaration where the scope specifier was
16173 /// templated.
16174 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16175                                     unsigned TagSpec, SourceLocation TagLoc,
16176                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16177                                     SourceLocation NameLoc,
16178                                     const ParsedAttributesView &Attr,
16179                                     MultiTemplateParamsArg TempParamLists) {
16180   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16181 
16182   bool IsMemberSpecialization = false;
16183   bool Invalid = false;
16184 
16185   if (TemplateParameterList *TemplateParams =
16186           MatchTemplateParametersToScopeSpecifier(
16187               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16188               IsMemberSpecialization, Invalid)) {
16189     if (TemplateParams->size() > 0) {
16190       // This is a declaration of a class template.
16191       if (Invalid)
16192         return nullptr;
16193 
16194       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16195                                 NameLoc, Attr, TemplateParams, AS_public,
16196                                 /*ModulePrivateLoc=*/SourceLocation(),
16197                                 FriendLoc, TempParamLists.size() - 1,
16198                                 TempParamLists.data()).get();
16199     } else {
16200       // The "template<>" header is extraneous.
16201       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16202         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16203       IsMemberSpecialization = true;
16204     }
16205   }
16206 
16207   if (Invalid) return nullptr;
16208 
16209   bool isAllExplicitSpecializations = true;
16210   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16211     if (TempParamLists[I]->size()) {
16212       isAllExplicitSpecializations = false;
16213       break;
16214     }
16215   }
16216 
16217   // FIXME: don't ignore attributes.
16218 
16219   // If it's explicit specializations all the way down, just forget
16220   // about the template header and build an appropriate non-templated
16221   // friend.  TODO: for source fidelity, remember the headers.
16222   if (isAllExplicitSpecializations) {
16223     if (SS.isEmpty()) {
16224       bool Owned = false;
16225       bool IsDependent = false;
16226       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16227                       Attr, AS_public,
16228                       /*ModulePrivateLoc=*/SourceLocation(),
16229                       MultiTemplateParamsArg(), Owned, IsDependent,
16230                       /*ScopedEnumKWLoc=*/SourceLocation(),
16231                       /*ScopedEnumUsesClassTag=*/false,
16232                       /*UnderlyingType=*/TypeResult(),
16233                       /*IsTypeSpecifier=*/false,
16234                       /*IsTemplateParamOrArg=*/false);
16235     }
16236 
16237     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16238     ElaboratedTypeKeyword Keyword
16239       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16240     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16241                                    *Name, NameLoc);
16242     if (T.isNull())
16243       return nullptr;
16244 
16245     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16246     if (isa<DependentNameType>(T)) {
16247       DependentNameTypeLoc TL =
16248           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16249       TL.setElaboratedKeywordLoc(TagLoc);
16250       TL.setQualifierLoc(QualifierLoc);
16251       TL.setNameLoc(NameLoc);
16252     } else {
16253       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16254       TL.setElaboratedKeywordLoc(TagLoc);
16255       TL.setQualifierLoc(QualifierLoc);
16256       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16257     }
16258 
16259     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16260                                             TSI, FriendLoc, TempParamLists);
16261     Friend->setAccess(AS_public);
16262     CurContext->addDecl(Friend);
16263     return Friend;
16264   }
16265 
16266   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16267 
16268 
16269 
16270   // Handle the case of a templated-scope friend class.  e.g.
16271   //   template <class T> class A<T>::B;
16272   // FIXME: we don't support these right now.
16273   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16274     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16275   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16276   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16277   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16278   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16279   TL.setElaboratedKeywordLoc(TagLoc);
16280   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16281   TL.setNameLoc(NameLoc);
16282 
16283   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16284                                           TSI, FriendLoc, TempParamLists);
16285   Friend->setAccess(AS_public);
16286   Friend->setUnsupportedFriend(true);
16287   CurContext->addDecl(Friend);
16288   return Friend;
16289 }
16290 
16291 /// Handle a friend type declaration.  This works in tandem with
16292 /// ActOnTag.
16293 ///
16294 /// Notes on friend class templates:
16295 ///
16296 /// We generally treat friend class declarations as if they were
16297 /// declaring a class.  So, for example, the elaborated type specifier
16298 /// in a friend declaration is required to obey the restrictions of a
16299 /// class-head (i.e. no typedefs in the scope chain), template
16300 /// parameters are required to match up with simple template-ids, &c.
16301 /// However, unlike when declaring a template specialization, it's
16302 /// okay to refer to a template specialization without an empty
16303 /// template parameter declaration, e.g.
16304 ///   friend class A<T>::B<unsigned>;
16305 /// We permit this as a special case; if there are any template
16306 /// parameters present at all, require proper matching, i.e.
16307 ///   template <> template \<class T> friend class A<int>::B;
16308 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16309                                 MultiTemplateParamsArg TempParams) {
16310   SourceLocation Loc = DS.getBeginLoc();
16311 
16312   assert(DS.isFriendSpecified());
16313   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16314 
16315   // C++ [class.friend]p3:
16316   // A friend declaration that does not declare a function shall have one of
16317   // the following forms:
16318   //     friend elaborated-type-specifier ;
16319   //     friend simple-type-specifier ;
16320   //     friend typename-specifier ;
16321   //
16322   // Any declaration with a type qualifier does not have that form. (It's
16323   // legal to specify a qualified type as a friend, you just can't write the
16324   // keywords.)
16325   if (DS.getTypeQualifiers()) {
16326     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16327       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16328     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16329       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16330     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16331       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16332     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16333       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16334     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16335       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16336   }
16337 
16338   // Try to convert the decl specifier to a type.  This works for
16339   // friend templates because ActOnTag never produces a ClassTemplateDecl
16340   // for a TUK_Friend.
16341   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16342   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16343   QualType T = TSI->getType();
16344   if (TheDeclarator.isInvalidType())
16345     return nullptr;
16346 
16347   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16348     return nullptr;
16349 
16350   // This is definitely an error in C++98.  It's probably meant to
16351   // be forbidden in C++0x, too, but the specification is just
16352   // poorly written.
16353   //
16354   // The problem is with declarations like the following:
16355   //   template <T> friend A<T>::foo;
16356   // where deciding whether a class C is a friend or not now hinges
16357   // on whether there exists an instantiation of A that causes
16358   // 'foo' to equal C.  There are restrictions on class-heads
16359   // (which we declare (by fiat) elaborated friend declarations to
16360   // be) that makes this tractable.
16361   //
16362   // FIXME: handle "template <> friend class A<T>;", which
16363   // is possibly well-formed?  Who even knows?
16364   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16365     Diag(Loc, diag::err_tagless_friend_type_template)
16366       << DS.getSourceRange();
16367     return nullptr;
16368   }
16369 
16370   // C++98 [class.friend]p1: A friend of a class is a function
16371   //   or class that is not a member of the class . . .
16372   // This is fixed in DR77, which just barely didn't make the C++03
16373   // deadline.  It's also a very silly restriction that seriously
16374   // affects inner classes and which nobody else seems to implement;
16375   // thus we never diagnose it, not even in -pedantic.
16376   //
16377   // But note that we could warn about it: it's always useless to
16378   // friend one of your own members (it's not, however, worthless to
16379   // friend a member of an arbitrary specialization of your template).
16380 
16381   Decl *D;
16382   if (!TempParams.empty())
16383     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16384                                    TempParams,
16385                                    TSI,
16386                                    DS.getFriendSpecLoc());
16387   else
16388     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16389 
16390   if (!D)
16391     return nullptr;
16392 
16393   D->setAccess(AS_public);
16394   CurContext->addDecl(D);
16395 
16396   return D;
16397 }
16398 
16399 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16400                                         MultiTemplateParamsArg TemplateParams) {
16401   const DeclSpec &DS = D.getDeclSpec();
16402 
16403   assert(DS.isFriendSpecified());
16404   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16405 
16406   SourceLocation Loc = D.getIdentifierLoc();
16407   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16408 
16409   // C++ [class.friend]p1
16410   //   A friend of a class is a function or class....
16411   // Note that this sees through typedefs, which is intended.
16412   // It *doesn't* see through dependent types, which is correct
16413   // according to [temp.arg.type]p3:
16414   //   If a declaration acquires a function type through a
16415   //   type dependent on a template-parameter and this causes
16416   //   a declaration that does not use the syntactic form of a
16417   //   function declarator to have a function type, the program
16418   //   is ill-formed.
16419   if (!TInfo->getType()->isFunctionType()) {
16420     Diag(Loc, diag::err_unexpected_friend);
16421 
16422     // It might be worthwhile to try to recover by creating an
16423     // appropriate declaration.
16424     return nullptr;
16425   }
16426 
16427   // C++ [namespace.memdef]p3
16428   //  - If a friend declaration in a non-local class first declares a
16429   //    class or function, the friend class or function is a member
16430   //    of the innermost enclosing namespace.
16431   //  - The name of the friend is not found by simple name lookup
16432   //    until a matching declaration is provided in that namespace
16433   //    scope (either before or after the class declaration granting
16434   //    friendship).
16435   //  - If a friend function is called, its name may be found by the
16436   //    name lookup that considers functions from namespaces and
16437   //    classes associated with the types of the function arguments.
16438   //  - When looking for a prior declaration of a class or a function
16439   //    declared as a friend, scopes outside the innermost enclosing
16440   //    namespace scope are not considered.
16441 
16442   CXXScopeSpec &SS = D.getCXXScopeSpec();
16443   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16444   assert(NameInfo.getName());
16445 
16446   // Check for unexpanded parameter packs.
16447   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16448       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16449       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16450     return nullptr;
16451 
16452   // The context we found the declaration in, or in which we should
16453   // create the declaration.
16454   DeclContext *DC;
16455   Scope *DCScope = S;
16456   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16457                         ForExternalRedeclaration);
16458 
16459   // There are five cases here.
16460   //   - There's no scope specifier and we're in a local class. Only look
16461   //     for functions declared in the immediately-enclosing block scope.
16462   // We recover from invalid scope qualifiers as if they just weren't there.
16463   FunctionDecl *FunctionContainingLocalClass = nullptr;
16464   if ((SS.isInvalid() || !SS.isSet()) &&
16465       (FunctionContainingLocalClass =
16466            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16467     // C++11 [class.friend]p11:
16468     //   If a friend declaration appears in a local class and the name
16469     //   specified is an unqualified name, a prior declaration is
16470     //   looked up without considering scopes that are outside the
16471     //   innermost enclosing non-class scope. For a friend function
16472     //   declaration, if there is no prior declaration, the program is
16473     //   ill-formed.
16474 
16475     // Find the innermost enclosing non-class scope. This is the block
16476     // scope containing the local class definition (or for a nested class,
16477     // the outer local class).
16478     DCScope = S->getFnParent();
16479 
16480     // Look up the function name in the scope.
16481     Previous.clear(LookupLocalFriendName);
16482     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16483 
16484     if (!Previous.empty()) {
16485       // All possible previous declarations must have the same context:
16486       // either they were declared at block scope or they are members of
16487       // one of the enclosing local classes.
16488       DC = Previous.getRepresentativeDecl()->getDeclContext();
16489     } else {
16490       // This is ill-formed, but provide the context that we would have
16491       // declared the function in, if we were permitted to, for error recovery.
16492       DC = FunctionContainingLocalClass;
16493     }
16494     adjustContextForLocalExternDecl(DC);
16495 
16496     // C++ [class.friend]p6:
16497     //   A function can be defined in a friend declaration of a class if and
16498     //   only if the class is a non-local class (9.8), the function name is
16499     //   unqualified, and the function has namespace scope.
16500     if (D.isFunctionDefinition()) {
16501       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16502     }
16503 
16504   //   - There's no scope specifier, in which case we just go to the
16505   //     appropriate scope and look for a function or function template
16506   //     there as appropriate.
16507   } else if (SS.isInvalid() || !SS.isSet()) {
16508     // C++11 [namespace.memdef]p3:
16509     //   If the name in a friend declaration is neither qualified nor
16510     //   a template-id and the declaration is a function or an
16511     //   elaborated-type-specifier, the lookup to determine whether
16512     //   the entity has been previously declared shall not consider
16513     //   any scopes outside the innermost enclosing namespace.
16514     bool isTemplateId =
16515         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16516 
16517     // Find the appropriate context according to the above.
16518     DC = CurContext;
16519 
16520     // Skip class contexts.  If someone can cite chapter and verse
16521     // for this behavior, that would be nice --- it's what GCC and
16522     // EDG do, and it seems like a reasonable intent, but the spec
16523     // really only says that checks for unqualified existing
16524     // declarations should stop at the nearest enclosing namespace,
16525     // not that they should only consider the nearest enclosing
16526     // namespace.
16527     while (DC->isRecord())
16528       DC = DC->getParent();
16529 
16530     DeclContext *LookupDC = DC;
16531     while (LookupDC->isTransparentContext())
16532       LookupDC = LookupDC->getParent();
16533 
16534     while (true) {
16535       LookupQualifiedName(Previous, LookupDC);
16536 
16537       if (!Previous.empty()) {
16538         DC = LookupDC;
16539         break;
16540       }
16541 
16542       if (isTemplateId) {
16543         if (isa<TranslationUnitDecl>(LookupDC)) break;
16544       } else {
16545         if (LookupDC->isFileContext()) break;
16546       }
16547       LookupDC = LookupDC->getParent();
16548     }
16549 
16550     DCScope = getScopeForDeclContext(S, DC);
16551 
16552   //   - There's a non-dependent scope specifier, in which case we
16553   //     compute it and do a previous lookup there for a function
16554   //     or function template.
16555   } else if (!SS.getScopeRep()->isDependent()) {
16556     DC = computeDeclContext(SS);
16557     if (!DC) return nullptr;
16558 
16559     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16560 
16561     LookupQualifiedName(Previous, DC);
16562 
16563     // C++ [class.friend]p1: A friend of a class is a function or
16564     //   class that is not a member of the class . . .
16565     if (DC->Equals(CurContext))
16566       Diag(DS.getFriendSpecLoc(),
16567            getLangOpts().CPlusPlus11 ?
16568              diag::warn_cxx98_compat_friend_is_member :
16569              diag::err_friend_is_member);
16570 
16571     if (D.isFunctionDefinition()) {
16572       // C++ [class.friend]p6:
16573       //   A function can be defined in a friend declaration of a class if and
16574       //   only if the class is a non-local class (9.8), the function name is
16575       //   unqualified, and the function has namespace scope.
16576       //
16577       // FIXME: We should only do this if the scope specifier names the
16578       // innermost enclosing namespace; otherwise the fixit changes the
16579       // meaning of the code.
16580       SemaDiagnosticBuilder DB
16581         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16582 
16583       DB << SS.getScopeRep();
16584       if (DC->isFileContext())
16585         DB << FixItHint::CreateRemoval(SS.getRange());
16586       SS.clear();
16587     }
16588 
16589   //   - There's a scope specifier that does not match any template
16590   //     parameter lists, in which case we use some arbitrary context,
16591   //     create a method or method template, and wait for instantiation.
16592   //   - There's a scope specifier that does match some template
16593   //     parameter lists, which we don't handle right now.
16594   } else {
16595     if (D.isFunctionDefinition()) {
16596       // C++ [class.friend]p6:
16597       //   A function can be defined in a friend declaration of a class if and
16598       //   only if the class is a non-local class (9.8), the function name is
16599       //   unqualified, and the function has namespace scope.
16600       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16601         << SS.getScopeRep();
16602     }
16603 
16604     DC = CurContext;
16605     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16606   }
16607 
16608   if (!DC->isRecord()) {
16609     int DiagArg = -1;
16610     switch (D.getName().getKind()) {
16611     case UnqualifiedIdKind::IK_ConstructorTemplateId:
16612     case UnqualifiedIdKind::IK_ConstructorName:
16613       DiagArg = 0;
16614       break;
16615     case UnqualifiedIdKind::IK_DestructorName:
16616       DiagArg = 1;
16617       break;
16618     case UnqualifiedIdKind::IK_ConversionFunctionId:
16619       DiagArg = 2;
16620       break;
16621     case UnqualifiedIdKind::IK_DeductionGuideName:
16622       DiagArg = 3;
16623       break;
16624     case UnqualifiedIdKind::IK_Identifier:
16625     case UnqualifiedIdKind::IK_ImplicitSelfParam:
16626     case UnqualifiedIdKind::IK_LiteralOperatorId:
16627     case UnqualifiedIdKind::IK_OperatorFunctionId:
16628     case UnqualifiedIdKind::IK_TemplateId:
16629       break;
16630     }
16631     // This implies that it has to be an operator or function.
16632     if (DiagArg >= 0) {
16633       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16634       return nullptr;
16635     }
16636   }
16637 
16638   // FIXME: This is an egregious hack to cope with cases where the scope stack
16639   // does not contain the declaration context, i.e., in an out-of-line
16640   // definition of a class.
16641   Scope FakeDCScope(S, Scope::DeclScope, Diags);
16642   if (!DCScope) {
16643     FakeDCScope.setEntity(DC);
16644     DCScope = &FakeDCScope;
16645   }
16646 
16647   bool AddToScope = true;
16648   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16649                                           TemplateParams, AddToScope);
16650   if (!ND) return nullptr;
16651 
16652   assert(ND->getLexicalDeclContext() == CurContext);
16653 
16654   // If we performed typo correction, we might have added a scope specifier
16655   // and changed the decl context.
16656   DC = ND->getDeclContext();
16657 
16658   // Add the function declaration to the appropriate lookup tables,
16659   // adjusting the redeclarations list as necessary.  We don't
16660   // want to do this yet if the friending class is dependent.
16661   //
16662   // Also update the scope-based lookup if the target context's
16663   // lookup context is in lexical scope.
16664   if (!CurContext->isDependentContext()) {
16665     DC = DC->getRedeclContext();
16666     DC->makeDeclVisibleInContext(ND);
16667     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16668       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16669   }
16670 
16671   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16672                                        D.getIdentifierLoc(), ND,
16673                                        DS.getFriendSpecLoc());
16674   FrD->setAccess(AS_public);
16675   CurContext->addDecl(FrD);
16676 
16677   if (ND->isInvalidDecl()) {
16678     FrD->setInvalidDecl();
16679   } else {
16680     if (DC->isRecord()) CheckFriendAccess(ND);
16681 
16682     FunctionDecl *FD;
16683     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16684       FD = FTD->getTemplatedDecl();
16685     else
16686       FD = cast<FunctionDecl>(ND);
16687 
16688     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16689     // default argument expression, that declaration shall be a definition
16690     // and shall be the only declaration of the function or function
16691     // template in the translation unit.
16692     if (functionDeclHasDefaultArgument(FD)) {
16693       // We can't look at FD->getPreviousDecl() because it may not have been set
16694       // if we're in a dependent context. If the function is known to be a
16695       // redeclaration, we will have narrowed Previous down to the right decl.
16696       if (D.isRedeclaration()) {
16697         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16698         Diag(Previous.getRepresentativeDecl()->getLocation(),
16699              diag::note_previous_declaration);
16700       } else if (!D.isFunctionDefinition())
16701         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16702     }
16703 
16704     // Mark templated-scope function declarations as unsupported.
16705     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16706       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16707         << SS.getScopeRep() << SS.getRange()
16708         << cast<CXXRecordDecl>(CurContext);
16709       FrD->setUnsupportedFriend(true);
16710     }
16711   }
16712 
16713   return ND;
16714 }
16715 
16716 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16717   AdjustDeclIfTemplate(Dcl);
16718 
16719   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16720   if (!Fn) {
16721     Diag(DelLoc, diag::err_deleted_non_function);
16722     return;
16723   }
16724 
16725   // Deleted function does not have a body.
16726   Fn->setWillHaveBody(false);
16727 
16728   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16729     // Don't consider the implicit declaration we generate for explicit
16730     // specializations. FIXME: Do not generate these implicit declarations.
16731     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16732          Prev->getPreviousDecl()) &&
16733         !Prev->isDefined()) {
16734       Diag(DelLoc, diag::err_deleted_decl_not_first);
16735       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16736            Prev->isImplicit() ? diag::note_previous_implicit_declaration
16737                               : diag::note_previous_declaration);
16738       // We can't recover from this; the declaration might have already
16739       // been used.
16740       Fn->setInvalidDecl();
16741       return;
16742     }
16743 
16744     // To maintain the invariant that functions are only deleted on their first
16745     // declaration, mark the implicitly-instantiated declaration of the
16746     // explicitly-specialized function as deleted instead of marking the
16747     // instantiated redeclaration.
16748     Fn = Fn->getCanonicalDecl();
16749   }
16750 
16751   // dllimport/dllexport cannot be deleted.
16752   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16753     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16754     Fn->setInvalidDecl();
16755   }
16756 
16757   // C++11 [basic.start.main]p3:
16758   //   A program that defines main as deleted [...] is ill-formed.
16759   if (Fn->isMain())
16760     Diag(DelLoc, diag::err_deleted_main);
16761 
16762   // C++11 [dcl.fct.def.delete]p4:
16763   //  A deleted function is implicitly inline.
16764   Fn->setImplicitlyInline();
16765   Fn->setDeletedAsWritten();
16766 }
16767 
16768 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16769   if (!Dcl || Dcl->isInvalidDecl())
16770     return;
16771 
16772   auto *FD = dyn_cast<FunctionDecl>(Dcl);
16773   if (!FD) {
16774     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16775       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16776         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16777         return;
16778       }
16779     }
16780 
16781     Diag(DefaultLoc, diag::err_default_special_members)
16782         << getLangOpts().CPlusPlus20;
16783     return;
16784   }
16785 
16786   // Reject if this can't possibly be a defaultable function.
16787   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16788   if (!DefKind &&
16789       // A dependent function that doesn't locally look defaultable can
16790       // still instantiate to a defaultable function if it's a constructor
16791       // or assignment operator.
16792       (!FD->isDependentContext() ||
16793        (!isa<CXXConstructorDecl>(FD) &&
16794         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16795     Diag(DefaultLoc, diag::err_default_special_members)
16796         << getLangOpts().CPlusPlus20;
16797     return;
16798   }
16799 
16800   if (DefKind.isComparison() &&
16801       !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16802     Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16803         << (int)DefKind.asComparison();
16804     return;
16805   }
16806 
16807   // Issue compatibility warning. We already warned if the operator is
16808   // 'operator<=>' when parsing the '<=>' token.
16809   if (DefKind.isComparison() &&
16810       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16811     Diag(DefaultLoc, getLangOpts().CPlusPlus20
16812                          ? diag::warn_cxx17_compat_defaulted_comparison
16813                          : diag::ext_defaulted_comparison);
16814   }
16815 
16816   FD->setDefaulted();
16817   FD->setExplicitlyDefaulted();
16818 
16819   // Defer checking functions that are defaulted in a dependent context.
16820   if (FD->isDependentContext())
16821     return;
16822 
16823   // Unset that we will have a body for this function. We might not,
16824   // if it turns out to be trivial, and we don't need this marking now
16825   // that we've marked it as defaulted.
16826   FD->setWillHaveBody(false);
16827 
16828   // If this definition appears within the record, do the checking when
16829   // the record is complete. This is always the case for a defaulted
16830   // comparison.
16831   if (DefKind.isComparison())
16832     return;
16833   auto *MD = cast<CXXMethodDecl>(FD);
16834 
16835   const FunctionDecl *Primary = FD;
16836   if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16837     // Ask the template instantiation pattern that actually had the
16838     // '= default' on it.
16839     Primary = Pattern;
16840 
16841   // If the method was defaulted on its first declaration, we will have
16842   // already performed the checking in CheckCompletedCXXClass. Such a
16843   // declaration doesn't trigger an implicit definition.
16844   if (Primary->getCanonicalDecl()->isDefaulted())
16845     return;
16846 
16847   // FIXME: Once we support defining comparisons out of class, check for a
16848   // defaulted comparison here.
16849   if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16850     MD->setInvalidDecl();
16851   else
16852     DefineDefaultedFunction(*this, MD, DefaultLoc);
16853 }
16854 
16855 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16856   for (Stmt *SubStmt : S->children()) {
16857     if (!SubStmt)
16858       continue;
16859     if (isa<ReturnStmt>(SubStmt))
16860       Self.Diag(SubStmt->getBeginLoc(),
16861                 diag::err_return_in_constructor_handler);
16862     if (!isa<Expr>(SubStmt))
16863       SearchForReturnInStmt(Self, SubStmt);
16864   }
16865 }
16866 
16867 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16868   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16869     CXXCatchStmt *Handler = TryBlock->getHandler(I);
16870     SearchForReturnInStmt(*this, Handler);
16871   }
16872 }
16873 
16874 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16875                                              const CXXMethodDecl *Old) {
16876   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16877   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16878 
16879   if (OldFT->hasExtParameterInfos()) {
16880     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16881       // A parameter of the overriding method should be annotated with noescape
16882       // if the corresponding parameter of the overridden method is annotated.
16883       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16884           !NewFT->getExtParameterInfo(I).isNoEscape()) {
16885         Diag(New->getParamDecl(I)->getLocation(),
16886              diag::warn_overriding_method_missing_noescape);
16887         Diag(Old->getParamDecl(I)->getLocation(),
16888              diag::note_overridden_marked_noescape);
16889       }
16890   }
16891 
16892   // Virtual overrides must have the same code_seg.
16893   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16894   const auto *NewCSA = New->getAttr<CodeSegAttr>();
16895   if ((NewCSA || OldCSA) &&
16896       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16897     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16898     Diag(Old->getLocation(), diag::note_previous_declaration);
16899     return true;
16900   }
16901 
16902   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16903 
16904   // If the calling conventions match, everything is fine
16905   if (NewCC == OldCC)
16906     return false;
16907 
16908   // If the calling conventions mismatch because the new function is static,
16909   // suppress the calling convention mismatch error; the error about static
16910   // function override (err_static_overrides_virtual from
16911   // Sema::CheckFunctionDeclaration) is more clear.
16912   if (New->getStorageClass() == SC_Static)
16913     return false;
16914 
16915   Diag(New->getLocation(),
16916        diag::err_conflicting_overriding_cc_attributes)
16917     << New->getDeclName() << New->getType() << Old->getType();
16918   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16919   return true;
16920 }
16921 
16922 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16923                                              const CXXMethodDecl *Old) {
16924   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16925   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16926 
16927   if (Context.hasSameType(NewTy, OldTy) ||
16928       NewTy->isDependentType() || OldTy->isDependentType())
16929     return false;
16930 
16931   // Check if the return types are covariant
16932   QualType NewClassTy, OldClassTy;
16933 
16934   /// Both types must be pointers or references to classes.
16935   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16936     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16937       NewClassTy = NewPT->getPointeeType();
16938       OldClassTy = OldPT->getPointeeType();
16939     }
16940   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16941     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16942       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16943         NewClassTy = NewRT->getPointeeType();
16944         OldClassTy = OldRT->getPointeeType();
16945       }
16946     }
16947   }
16948 
16949   // The return types aren't either both pointers or references to a class type.
16950   if (NewClassTy.isNull()) {
16951     Diag(New->getLocation(),
16952          diag::err_different_return_type_for_overriding_virtual_function)
16953         << New->getDeclName() << NewTy << OldTy
16954         << New->getReturnTypeSourceRange();
16955     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16956         << Old->getReturnTypeSourceRange();
16957 
16958     return true;
16959   }
16960 
16961   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16962     // C++14 [class.virtual]p8:
16963     //   If the class type in the covariant return type of D::f differs from
16964     //   that of B::f, the class type in the return type of D::f shall be
16965     //   complete at the point of declaration of D::f or shall be the class
16966     //   type D.
16967     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16968       if (!RT->isBeingDefined() &&
16969           RequireCompleteType(New->getLocation(), NewClassTy,
16970                               diag::err_covariant_return_incomplete,
16971                               New->getDeclName()))
16972         return true;
16973     }
16974 
16975     // Check if the new class derives from the old class.
16976     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
16977       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
16978           << New->getDeclName() << NewTy << OldTy
16979           << New->getReturnTypeSourceRange();
16980       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16981           << Old->getReturnTypeSourceRange();
16982       return true;
16983     }
16984 
16985     // Check if we the conversion from derived to base is valid.
16986     if (CheckDerivedToBaseConversion(
16987             NewClassTy, OldClassTy,
16988             diag::err_covariant_return_inaccessible_base,
16989             diag::err_covariant_return_ambiguous_derived_to_base_conv,
16990             New->getLocation(), New->getReturnTypeSourceRange(),
16991             New->getDeclName(), nullptr)) {
16992       // FIXME: this note won't trigger for delayed access control
16993       // diagnostics, and it's impossible to get an undelayed error
16994       // here from access control during the original parse because
16995       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
16996       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16997           << Old->getReturnTypeSourceRange();
16998       return true;
16999     }
17000   }
17001 
17002   // The qualifiers of the return types must be the same.
17003   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17004     Diag(New->getLocation(),
17005          diag::err_covariant_return_type_different_qualifications)
17006         << New->getDeclName() << NewTy << OldTy
17007         << New->getReturnTypeSourceRange();
17008     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17009         << Old->getReturnTypeSourceRange();
17010     return true;
17011   }
17012 
17013 
17014   // The new class type must have the same or less qualifiers as the old type.
17015   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17016     Diag(New->getLocation(),
17017          diag::err_covariant_return_type_class_type_more_qualified)
17018         << New->getDeclName() << NewTy << OldTy
17019         << New->getReturnTypeSourceRange();
17020     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17021         << Old->getReturnTypeSourceRange();
17022     return true;
17023   }
17024 
17025   return false;
17026 }
17027 
17028 /// Mark the given method pure.
17029 ///
17030 /// \param Method the method to be marked pure.
17031 ///
17032 /// \param InitRange the source range that covers the "0" initializer.
17033 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17034   SourceLocation EndLoc = InitRange.getEnd();
17035   if (EndLoc.isValid())
17036     Method->setRangeEnd(EndLoc);
17037 
17038   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17039     Method->setPure();
17040     return false;
17041   }
17042 
17043   if (!Method->isInvalidDecl())
17044     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17045       << Method->getDeclName() << InitRange;
17046   return true;
17047 }
17048 
17049 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17050   if (D->getFriendObjectKind())
17051     Diag(D->getLocation(), diag::err_pure_friend);
17052   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17053     CheckPureMethod(M, ZeroLoc);
17054   else
17055     Diag(D->getLocation(), diag::err_illegal_initializer);
17056 }
17057 
17058 /// Determine whether the given declaration is a global variable or
17059 /// static data member.
17060 static bool isNonlocalVariable(const Decl *D) {
17061   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17062     return Var->hasGlobalStorage();
17063 
17064   return false;
17065 }
17066 
17067 /// Invoked when we are about to parse an initializer for the declaration
17068 /// 'Dcl'.
17069 ///
17070 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17071 /// static data member of class X, names should be looked up in the scope of
17072 /// class X. If the declaration had a scope specifier, a scope will have
17073 /// been created and passed in for this purpose. Otherwise, S will be null.
17074 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17075   // If there is no declaration, there was an error parsing it.
17076   if (!D || D->isInvalidDecl())
17077     return;
17078 
17079   // We will always have a nested name specifier here, but this declaration
17080   // might not be out of line if the specifier names the current namespace:
17081   //   extern int n;
17082   //   int ::n = 0;
17083   if (S && D->isOutOfLine())
17084     EnterDeclaratorContext(S, D->getDeclContext());
17085 
17086   // If we are parsing the initializer for a static data member, push a
17087   // new expression evaluation context that is associated with this static
17088   // data member.
17089   if (isNonlocalVariable(D))
17090     PushExpressionEvaluationContext(
17091         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17092 }
17093 
17094 /// Invoked after we are finished parsing an initializer for the declaration D.
17095 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17096   // If there is no declaration, there was an error parsing it.
17097   if (!D || D->isInvalidDecl())
17098     return;
17099 
17100   if (isNonlocalVariable(D))
17101     PopExpressionEvaluationContext();
17102 
17103   if (S && D->isOutOfLine())
17104     ExitDeclaratorContext(S);
17105 }
17106 
17107 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17108 /// C++ if/switch/while/for statement.
17109 /// e.g: "if (int x = f()) {...}"
17110 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17111   // C++ 6.4p2:
17112   // The declarator shall not specify a function or an array.
17113   // The type-specifier-seq shall not contain typedef and shall not declare a
17114   // new class or enumeration.
17115   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17116          "Parser allowed 'typedef' as storage class of condition decl.");
17117 
17118   Decl *Dcl = ActOnDeclarator(S, D);
17119   if (!Dcl)
17120     return true;
17121 
17122   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17123     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17124       << D.getSourceRange();
17125     return true;
17126   }
17127 
17128   return Dcl;
17129 }
17130 
17131 void Sema::LoadExternalVTableUses() {
17132   if (!ExternalSource)
17133     return;
17134 
17135   SmallVector<ExternalVTableUse, 4> VTables;
17136   ExternalSource->ReadUsedVTables(VTables);
17137   SmallVector<VTableUse, 4> NewUses;
17138   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17139     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17140       = VTablesUsed.find(VTables[I].Record);
17141     // Even if a definition wasn't required before, it may be required now.
17142     if (Pos != VTablesUsed.end()) {
17143       if (!Pos->second && VTables[I].DefinitionRequired)
17144         Pos->second = true;
17145       continue;
17146     }
17147 
17148     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17149     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17150   }
17151 
17152   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17153 }
17154 
17155 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17156                           bool DefinitionRequired) {
17157   // Ignore any vtable uses in unevaluated operands or for classes that do
17158   // not have a vtable.
17159   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17160       CurContext->isDependentContext() || isUnevaluatedContext())
17161     return;
17162   // Do not mark as used if compiling for the device outside of the target
17163   // region.
17164   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17165       !isInOpenMPDeclareTargetContext() &&
17166       !isInOpenMPTargetExecutionDirective()) {
17167     if (!DefinitionRequired)
17168       MarkVirtualMembersReferenced(Loc, Class);
17169     return;
17170   }
17171 
17172   // Try to insert this class into the map.
17173   LoadExternalVTableUses();
17174   Class = Class->getCanonicalDecl();
17175   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17176     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17177   if (!Pos.second) {
17178     // If we already had an entry, check to see if we are promoting this vtable
17179     // to require a definition. If so, we need to reappend to the VTableUses
17180     // list, since we may have already processed the first entry.
17181     if (DefinitionRequired && !Pos.first->second) {
17182       Pos.first->second = true;
17183     } else {
17184       // Otherwise, we can early exit.
17185       return;
17186     }
17187   } else {
17188     // The Microsoft ABI requires that we perform the destructor body
17189     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17190     // the deleting destructor is emitted with the vtable, not with the
17191     // destructor definition as in the Itanium ABI.
17192     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17193       CXXDestructorDecl *DD = Class->getDestructor();
17194       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17195         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17196           // If this is an out-of-line declaration, marking it referenced will
17197           // not do anything. Manually call CheckDestructor to look up operator
17198           // delete().
17199           ContextRAII SavedContext(*this, DD);
17200           CheckDestructor(DD);
17201         } else {
17202           MarkFunctionReferenced(Loc, Class->getDestructor());
17203         }
17204       }
17205     }
17206   }
17207 
17208   // Local classes need to have their virtual members marked
17209   // immediately. For all other classes, we mark their virtual members
17210   // at the end of the translation unit.
17211   if (Class->isLocalClass())
17212     MarkVirtualMembersReferenced(Loc, Class);
17213   else
17214     VTableUses.push_back(std::make_pair(Class, Loc));
17215 }
17216 
17217 bool Sema::DefineUsedVTables() {
17218   LoadExternalVTableUses();
17219   if (VTableUses.empty())
17220     return false;
17221 
17222   // Note: The VTableUses vector could grow as a result of marking
17223   // the members of a class as "used", so we check the size each
17224   // time through the loop and prefer indices (which are stable) to
17225   // iterators (which are not).
17226   bool DefinedAnything = false;
17227   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17228     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17229     if (!Class)
17230       continue;
17231     TemplateSpecializationKind ClassTSK =
17232         Class->getTemplateSpecializationKind();
17233 
17234     SourceLocation Loc = VTableUses[I].second;
17235 
17236     bool DefineVTable = true;
17237 
17238     // If this class has a key function, but that key function is
17239     // defined in another translation unit, we don't need to emit the
17240     // vtable even though we're using it.
17241     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17242     if (KeyFunction && !KeyFunction->hasBody()) {
17243       // The key function is in another translation unit.
17244       DefineVTable = false;
17245       TemplateSpecializationKind TSK =
17246           KeyFunction->getTemplateSpecializationKind();
17247       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17248              TSK != TSK_ImplicitInstantiation &&
17249              "Instantiations don't have key functions");
17250       (void)TSK;
17251     } else if (!KeyFunction) {
17252       // If we have a class with no key function that is the subject
17253       // of an explicit instantiation declaration, suppress the
17254       // vtable; it will live with the explicit instantiation
17255       // definition.
17256       bool IsExplicitInstantiationDeclaration =
17257           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17258       for (auto R : Class->redecls()) {
17259         TemplateSpecializationKind TSK
17260           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17261         if (TSK == TSK_ExplicitInstantiationDeclaration)
17262           IsExplicitInstantiationDeclaration = true;
17263         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17264           IsExplicitInstantiationDeclaration = false;
17265           break;
17266         }
17267       }
17268 
17269       if (IsExplicitInstantiationDeclaration)
17270         DefineVTable = false;
17271     }
17272 
17273     // The exception specifications for all virtual members may be needed even
17274     // if we are not providing an authoritative form of the vtable in this TU.
17275     // We may choose to emit it available_externally anyway.
17276     if (!DefineVTable) {
17277       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17278       continue;
17279     }
17280 
17281     // Mark all of the virtual members of this class as referenced, so
17282     // that we can build a vtable. Then, tell the AST consumer that a
17283     // vtable for this class is required.
17284     DefinedAnything = true;
17285     MarkVirtualMembersReferenced(Loc, Class);
17286     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17287     if (VTablesUsed[Canonical])
17288       Consumer.HandleVTable(Class);
17289 
17290     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17291     // no key function or the key function is inlined. Don't warn in C++ ABIs
17292     // that lack key functions, since the user won't be able to make one.
17293     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17294         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17295       const FunctionDecl *KeyFunctionDef = nullptr;
17296       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17297                            KeyFunctionDef->isInlined())) {
17298         Diag(Class->getLocation(),
17299              ClassTSK == TSK_ExplicitInstantiationDefinition
17300                  ? diag::warn_weak_template_vtable
17301                  : diag::warn_weak_vtable)
17302             << Class;
17303       }
17304     }
17305   }
17306   VTableUses.clear();
17307 
17308   return DefinedAnything;
17309 }
17310 
17311 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17312                                                  const CXXRecordDecl *RD) {
17313   for (const auto *I : RD->methods())
17314     if (I->isVirtual() && !I->isPure())
17315       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17316 }
17317 
17318 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17319                                         const CXXRecordDecl *RD,
17320                                         bool ConstexprOnly) {
17321   // Mark all functions which will appear in RD's vtable as used.
17322   CXXFinalOverriderMap FinalOverriders;
17323   RD->getFinalOverriders(FinalOverriders);
17324   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17325                                             E = FinalOverriders.end();
17326        I != E; ++I) {
17327     for (OverridingMethods::const_iterator OI = I->second.begin(),
17328                                            OE = I->second.end();
17329          OI != OE; ++OI) {
17330       assert(OI->second.size() > 0 && "no final overrider");
17331       CXXMethodDecl *Overrider = OI->second.front().Method;
17332 
17333       // C++ [basic.def.odr]p2:
17334       //   [...] A virtual member function is used if it is not pure. [...]
17335       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17336         MarkFunctionReferenced(Loc, Overrider);
17337     }
17338   }
17339 
17340   // Only classes that have virtual bases need a VTT.
17341   if (RD->getNumVBases() == 0)
17342     return;
17343 
17344   for (const auto &I : RD->bases()) {
17345     const auto *Base =
17346         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17347     if (Base->getNumVBases() == 0)
17348       continue;
17349     MarkVirtualMembersReferenced(Loc, Base);
17350   }
17351 }
17352 
17353 /// SetIvarInitializers - This routine builds initialization ASTs for the
17354 /// Objective-C implementation whose ivars need be initialized.
17355 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17356   if (!getLangOpts().CPlusPlus)
17357     return;
17358   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17359     SmallVector<ObjCIvarDecl*, 8> ivars;
17360     CollectIvarsToConstructOrDestruct(OID, ivars);
17361     if (ivars.empty())
17362       return;
17363     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17364     for (unsigned i = 0; i < ivars.size(); i++) {
17365       FieldDecl *Field = ivars[i];
17366       if (Field->isInvalidDecl())
17367         continue;
17368 
17369       CXXCtorInitializer *Member;
17370       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17371       InitializationKind InitKind =
17372         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17373 
17374       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17375       ExprResult MemberInit =
17376         InitSeq.Perform(*this, InitEntity, InitKind, None);
17377       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17378       // Note, MemberInit could actually come back empty if no initialization
17379       // is required (e.g., because it would call a trivial default constructor)
17380       if (!MemberInit.get() || MemberInit.isInvalid())
17381         continue;
17382 
17383       Member =
17384         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17385                                          SourceLocation(),
17386                                          MemberInit.getAs<Expr>(),
17387                                          SourceLocation());
17388       AllToInit.push_back(Member);
17389 
17390       // Be sure that the destructor is accessible and is marked as referenced.
17391       if (const RecordType *RecordTy =
17392               Context.getBaseElementType(Field->getType())
17393                   ->getAs<RecordType>()) {
17394         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17395         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17396           MarkFunctionReferenced(Field->getLocation(), Destructor);
17397           CheckDestructorAccess(Field->getLocation(), Destructor,
17398                             PDiag(diag::err_access_dtor_ivar)
17399                               << Context.getBaseElementType(Field->getType()));
17400         }
17401       }
17402     }
17403     ObjCImplementation->setIvarInitializers(Context,
17404                                             AllToInit.data(), AllToInit.size());
17405   }
17406 }
17407 
17408 static
17409 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17410                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17411                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17412                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17413                            Sema &S) {
17414   if (Ctor->isInvalidDecl())
17415     return;
17416 
17417   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17418 
17419   // Target may not be determinable yet, for instance if this is a dependent
17420   // call in an uninstantiated template.
17421   if (Target) {
17422     const FunctionDecl *FNTarget = nullptr;
17423     (void)Target->hasBody(FNTarget);
17424     Target = const_cast<CXXConstructorDecl*>(
17425       cast_or_null<CXXConstructorDecl>(FNTarget));
17426   }
17427 
17428   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17429                      // Avoid dereferencing a null pointer here.
17430                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17431 
17432   if (!Current.insert(Canonical).second)
17433     return;
17434 
17435   // We know that beyond here, we aren't chaining into a cycle.
17436   if (!Target || !Target->isDelegatingConstructor() ||
17437       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17438     Valid.insert(Current.begin(), Current.end());
17439     Current.clear();
17440   // We've hit a cycle.
17441   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17442              Current.count(TCanonical)) {
17443     // If we haven't diagnosed this cycle yet, do so now.
17444     if (!Invalid.count(TCanonical)) {
17445       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17446              diag::warn_delegating_ctor_cycle)
17447         << Ctor;
17448 
17449       // Don't add a note for a function delegating directly to itself.
17450       if (TCanonical != Canonical)
17451         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17452 
17453       CXXConstructorDecl *C = Target;
17454       while (C->getCanonicalDecl() != Canonical) {
17455         const FunctionDecl *FNTarget = nullptr;
17456         (void)C->getTargetConstructor()->hasBody(FNTarget);
17457         assert(FNTarget && "Ctor cycle through bodiless function");
17458 
17459         C = const_cast<CXXConstructorDecl*>(
17460           cast<CXXConstructorDecl>(FNTarget));
17461         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17462       }
17463     }
17464 
17465     Invalid.insert(Current.begin(), Current.end());
17466     Current.clear();
17467   } else {
17468     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17469   }
17470 }
17471 
17472 
17473 void Sema::CheckDelegatingCtorCycles() {
17474   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17475 
17476   for (DelegatingCtorDeclsType::iterator
17477          I = DelegatingCtorDecls.begin(ExternalSource),
17478          E = DelegatingCtorDecls.end();
17479        I != E; ++I)
17480     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17481 
17482   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17483     (*CI)->setInvalidDecl();
17484 }
17485 
17486 namespace {
17487   /// AST visitor that finds references to the 'this' expression.
17488   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17489     Sema &S;
17490 
17491   public:
17492     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17493 
17494     bool VisitCXXThisExpr(CXXThisExpr *E) {
17495       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17496         << E->isImplicit();
17497       return false;
17498     }
17499   };
17500 }
17501 
17502 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17503   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17504   if (!TSInfo)
17505     return false;
17506 
17507   TypeLoc TL = TSInfo->getTypeLoc();
17508   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17509   if (!ProtoTL)
17510     return false;
17511 
17512   // C++11 [expr.prim.general]p3:
17513   //   [The expression this] shall not appear before the optional
17514   //   cv-qualifier-seq and it shall not appear within the declaration of a
17515   //   static member function (although its type and value category are defined
17516   //   within a static member function as they are within a non-static member
17517   //   function). [ Note: this is because declaration matching does not occur
17518   //  until the complete declarator is known. - end note ]
17519   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17520   FindCXXThisExpr Finder(*this);
17521 
17522   // If the return type came after the cv-qualifier-seq, check it now.
17523   if (Proto->hasTrailingReturn() &&
17524       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17525     return true;
17526 
17527   // Check the exception specification.
17528   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17529     return true;
17530 
17531   // Check the trailing requires clause
17532   if (Expr *E = Method->getTrailingRequiresClause())
17533     if (!Finder.TraverseStmt(E))
17534       return true;
17535 
17536   return checkThisInStaticMemberFunctionAttributes(Method);
17537 }
17538 
17539 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17540   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17541   if (!TSInfo)
17542     return false;
17543 
17544   TypeLoc TL = TSInfo->getTypeLoc();
17545   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17546   if (!ProtoTL)
17547     return false;
17548 
17549   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17550   FindCXXThisExpr Finder(*this);
17551 
17552   switch (Proto->getExceptionSpecType()) {
17553   case EST_Unparsed:
17554   case EST_Uninstantiated:
17555   case EST_Unevaluated:
17556   case EST_BasicNoexcept:
17557   case EST_NoThrow:
17558   case EST_DynamicNone:
17559   case EST_MSAny:
17560   case EST_None:
17561     break;
17562 
17563   case EST_DependentNoexcept:
17564   case EST_NoexceptFalse:
17565   case EST_NoexceptTrue:
17566     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17567       return true;
17568     LLVM_FALLTHROUGH;
17569 
17570   case EST_Dynamic:
17571     for (const auto &E : Proto->exceptions()) {
17572       if (!Finder.TraverseType(E))
17573         return true;
17574     }
17575     break;
17576   }
17577 
17578   return false;
17579 }
17580 
17581 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17582   FindCXXThisExpr Finder(*this);
17583 
17584   // Check attributes.
17585   for (const auto *A : Method->attrs()) {
17586     // FIXME: This should be emitted by tblgen.
17587     Expr *Arg = nullptr;
17588     ArrayRef<Expr *> Args;
17589     if (const auto *G = dyn_cast<GuardedByAttr>(A))
17590       Arg = G->getArg();
17591     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17592       Arg = G->getArg();
17593     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17594       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17595     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17596       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17597     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17598       Arg = ETLF->getSuccessValue();
17599       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17600     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17601       Arg = STLF->getSuccessValue();
17602       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17603     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17604       Arg = LR->getArg();
17605     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17606       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17607     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17608       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17609     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17610       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17611     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17612       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17613     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17614       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17615 
17616     if (Arg && !Finder.TraverseStmt(Arg))
17617       return true;
17618 
17619     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17620       if (!Finder.TraverseStmt(Args[I]))
17621         return true;
17622     }
17623   }
17624 
17625   return false;
17626 }
17627 
17628 void Sema::checkExceptionSpecification(
17629     bool IsTopLevel, ExceptionSpecificationType EST,
17630     ArrayRef<ParsedType> DynamicExceptions,
17631     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17632     SmallVectorImpl<QualType> &Exceptions,
17633     FunctionProtoType::ExceptionSpecInfo &ESI) {
17634   Exceptions.clear();
17635   ESI.Type = EST;
17636   if (EST == EST_Dynamic) {
17637     Exceptions.reserve(DynamicExceptions.size());
17638     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17639       // FIXME: Preserve type source info.
17640       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17641 
17642       if (IsTopLevel) {
17643         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17644         collectUnexpandedParameterPacks(ET, Unexpanded);
17645         if (!Unexpanded.empty()) {
17646           DiagnoseUnexpandedParameterPacks(
17647               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17648               Unexpanded);
17649           continue;
17650         }
17651       }
17652 
17653       // Check that the type is valid for an exception spec, and
17654       // drop it if not.
17655       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17656         Exceptions.push_back(ET);
17657     }
17658     ESI.Exceptions = Exceptions;
17659     return;
17660   }
17661 
17662   if (isComputedNoexcept(EST)) {
17663     assert((NoexceptExpr->isTypeDependent() ||
17664             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17665             Context.BoolTy) &&
17666            "Parser should have made sure that the expression is boolean");
17667     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17668       ESI.Type = EST_BasicNoexcept;
17669       return;
17670     }
17671 
17672     ESI.NoexceptExpr = NoexceptExpr;
17673     return;
17674   }
17675 }
17676 
17677 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17678              ExceptionSpecificationType EST,
17679              SourceRange SpecificationRange,
17680              ArrayRef<ParsedType> DynamicExceptions,
17681              ArrayRef<SourceRange> DynamicExceptionRanges,
17682              Expr *NoexceptExpr) {
17683   if (!MethodD)
17684     return;
17685 
17686   // Dig out the method we're referring to.
17687   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17688     MethodD = FunTmpl->getTemplatedDecl();
17689 
17690   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17691   if (!Method)
17692     return;
17693 
17694   // Check the exception specification.
17695   llvm::SmallVector<QualType, 4> Exceptions;
17696   FunctionProtoType::ExceptionSpecInfo ESI;
17697   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17698                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
17699                               ESI);
17700 
17701   // Update the exception specification on the function type.
17702   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17703 
17704   if (Method->isStatic())
17705     checkThisInStaticMemberFunctionExceptionSpec(Method);
17706 
17707   if (Method->isVirtual()) {
17708     // Check overrides, which we previously had to delay.
17709     for (const CXXMethodDecl *O : Method->overridden_methods())
17710       CheckOverridingFunctionExceptionSpec(Method, O);
17711   }
17712 }
17713 
17714 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17715 ///
17716 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17717                                        SourceLocation DeclStart, Declarator &D,
17718                                        Expr *BitWidth,
17719                                        InClassInitStyle InitStyle,
17720                                        AccessSpecifier AS,
17721                                        const ParsedAttr &MSPropertyAttr) {
17722   IdentifierInfo *II = D.getIdentifier();
17723   if (!II) {
17724     Diag(DeclStart, diag::err_anonymous_property);
17725     return nullptr;
17726   }
17727   SourceLocation Loc = D.getIdentifierLoc();
17728 
17729   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17730   QualType T = TInfo->getType();
17731   if (getLangOpts().CPlusPlus) {
17732     CheckExtraCXXDefaultArguments(D);
17733 
17734     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17735                                         UPPC_DataMemberType)) {
17736       D.setInvalidType();
17737       T = Context.IntTy;
17738       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17739     }
17740   }
17741 
17742   DiagnoseFunctionSpecifiers(D.getDeclSpec());
17743 
17744   if (D.getDeclSpec().isInlineSpecified())
17745     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17746         << getLangOpts().CPlusPlus17;
17747   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17748     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17749          diag::err_invalid_thread)
17750       << DeclSpec::getSpecifierName(TSCS);
17751 
17752   // Check to see if this name was declared as a member previously
17753   NamedDecl *PrevDecl = nullptr;
17754   LookupResult Previous(*this, II, Loc, LookupMemberName,
17755                         ForVisibleRedeclaration);
17756   LookupName(Previous, S);
17757   switch (Previous.getResultKind()) {
17758   case LookupResult::Found:
17759   case LookupResult::FoundUnresolvedValue:
17760     PrevDecl = Previous.getAsSingle<NamedDecl>();
17761     break;
17762 
17763   case LookupResult::FoundOverloaded:
17764     PrevDecl = Previous.getRepresentativeDecl();
17765     break;
17766 
17767   case LookupResult::NotFound:
17768   case LookupResult::NotFoundInCurrentInstantiation:
17769   case LookupResult::Ambiguous:
17770     break;
17771   }
17772 
17773   if (PrevDecl && PrevDecl->isTemplateParameter()) {
17774     // Maybe we will complain about the shadowed template parameter.
17775     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17776     // Just pretend that we didn't see the previous declaration.
17777     PrevDecl = nullptr;
17778   }
17779 
17780   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17781     PrevDecl = nullptr;
17782 
17783   SourceLocation TSSL = D.getBeginLoc();
17784   MSPropertyDecl *NewPD =
17785       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17786                              MSPropertyAttr.getPropertyDataGetter(),
17787                              MSPropertyAttr.getPropertyDataSetter());
17788   ProcessDeclAttributes(TUScope, NewPD, D);
17789   NewPD->setAccess(AS);
17790 
17791   if (NewPD->isInvalidDecl())
17792     Record->setInvalidDecl();
17793 
17794   if (D.getDeclSpec().isModulePrivateSpecified())
17795     NewPD->setModulePrivate();
17796 
17797   if (NewPD->isInvalidDecl() && PrevDecl) {
17798     // Don't introduce NewFD into scope; there's already something
17799     // with the same name in the same scope.
17800   } else if (II) {
17801     PushOnScopeChains(NewPD, S);
17802   } else
17803     Record->addDecl(NewPD);
17804 
17805   return NewPD;
17806 }
17807 
17808 void Sema::ActOnStartFunctionDeclarationDeclarator(
17809     Declarator &Declarator, unsigned TemplateParameterDepth) {
17810   auto &Info = InventedParameterInfos.emplace_back();
17811   TemplateParameterList *ExplicitParams = nullptr;
17812   ArrayRef<TemplateParameterList *> ExplicitLists =
17813       Declarator.getTemplateParameterLists();
17814   if (!ExplicitLists.empty()) {
17815     bool IsMemberSpecialization, IsInvalid;
17816     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17817         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17818         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17819         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17820         /*SuppressDiagnostic=*/true);
17821   }
17822   if (ExplicitParams) {
17823     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17824     for (NamedDecl *Param : *ExplicitParams)
17825       Info.TemplateParams.push_back(Param);
17826     Info.NumExplicitTemplateParams = ExplicitParams->size();
17827   } else {
17828     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17829     Info.NumExplicitTemplateParams = 0;
17830   }
17831 }
17832 
17833 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17834   auto &FSI = InventedParameterInfos.back();
17835   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17836     if (FSI.NumExplicitTemplateParams != 0) {
17837       TemplateParameterList *ExplicitParams =
17838           Declarator.getTemplateParameterLists().back();
17839       Declarator.setInventedTemplateParameterList(
17840           TemplateParameterList::Create(
17841               Context, ExplicitParams->getTemplateLoc(),
17842               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17843               ExplicitParams->getRAngleLoc(),
17844               ExplicitParams->getRequiresClause()));
17845     } else {
17846       Declarator.setInventedTemplateParameterList(
17847           TemplateParameterList::Create(
17848               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17849               SourceLocation(), /*RequiresClause=*/nullptr));
17850     }
17851   }
17852   InventedParameterInfos.pop_back();
17853 }
17854