1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/AttributeCommonInfo.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/CXXFieldCollector.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Initialization.h"
36 #include "clang/Sema/Lookup.h"
37 #include "clang/Sema/ParsedTemplate.h"
38 #include "clang/Sema/Scope.h"
39 #include "clang/Sema/ScopeInfo.h"
40 #include "clang/Sema/SemaInternal.h"
41 #include "clang/Sema/Template.h"
42 #include "llvm/ADT/ScopeExit.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include <map>
47 #include <set>
48 
49 using namespace clang;
50 
51 //===----------------------------------------------------------------------===//
52 // CheckDefaultArgumentVisitor
53 //===----------------------------------------------------------------------===//
54 
55 namespace {
56 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
57 /// the default argument of a parameter to determine whether it
58 /// contains any ill-formed subexpressions. For example, this will
59 /// diagnose the use of local variables or parameters within the
60 /// default argument expression.
61 class CheckDefaultArgumentVisitor
62     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
63   Sema &S;
64   const Expr *DefaultArg;
65 
66 public:
67   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
68       : S(S), DefaultArg(DefaultArg) {}
69 
70   bool VisitExpr(const Expr *Node);
71   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
72   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
73   bool VisitLambdaExpr(const LambdaExpr *Lambda);
74   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
75 };
76 
77 /// VisitExpr - Visit all of the children of this expression.
78 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
79   bool IsInvalid = false;
80   for (const Stmt *SubStmt : Node->children())
81     IsInvalid |= Visit(SubStmt);
82   return IsInvalid;
83 }
84 
85 /// VisitDeclRefExpr - Visit a reference to a declaration, to
86 /// determine whether this declaration can be used in the default
87 /// argument expression.
88 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
89   const NamedDecl *Decl = DRE->getDecl();
90   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
91     // C++ [dcl.fct.default]p9:
92     //   [...] parameters of a function shall not be used in default
93     //   argument expressions, even if they are not evaluated. [...]
94     //
95     // C++17 [dcl.fct.default]p9 (by CWG 2082):
96     //   [...] A parameter shall not appear as a potentially-evaluated
97     //   expression in a default argument. [...]
98     //
99     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
100       return S.Diag(DRE->getBeginLoc(),
101                     diag::err_param_default_argument_references_param)
102              << Param->getDeclName() << DefaultArg->getSourceRange();
103   } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
104     // C++ [dcl.fct.default]p7:
105     //   Local variables shall not be used in default argument
106     //   expressions.
107     //
108     // C++17 [dcl.fct.default]p7 (by CWG 2082):
109     //   A local variable shall not appear as a potentially-evaluated
110     //   expression in a default argument.
111     //
112     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
113     //   Note: A local variable cannot be odr-used (6.3) in a default argument.
114     //
115     if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
116       return S.Diag(DRE->getBeginLoc(),
117                     diag::err_param_default_argument_references_local)
118              << VDecl->getDeclName() << DefaultArg->getSourceRange();
119   }
120 
121   return false;
122 }
123 
124 /// VisitCXXThisExpr - Visit a C++ "this" expression.
125 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
126   // C++ [dcl.fct.default]p8:
127   //   The keyword this shall not be used in a default argument of a
128   //   member function.
129   return S.Diag(ThisE->getBeginLoc(),
130                 diag::err_param_default_argument_references_this)
131          << ThisE->getSourceRange();
132 }
133 
134 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
135     const PseudoObjectExpr *POE) {
136   bool Invalid = false;
137   for (const Expr *E : POE->semantics()) {
138     // Look through bindings.
139     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
140       E = OVE->getSourceExpr();
141       assert(E && "pseudo-object binding without source expression?");
142     }
143 
144     Invalid |= Visit(E);
145   }
146   return Invalid;
147 }
148 
149 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
150   // C++11 [expr.lambda.prim]p13:
151   //   A lambda-expression appearing in a default argument shall not
152   //   implicitly or explicitly capture any entity.
153   if (Lambda->capture_begin() == Lambda->capture_end())
154     return false;
155 
156   return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
157 }
158 } // namespace
159 
160 void
161 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
162                                                  const CXXMethodDecl *Method) {
163   // If we have an MSAny spec already, don't bother.
164   if (!Method || ComputedEST == EST_MSAny)
165     return;
166 
167   const FunctionProtoType *Proto
168     = Method->getType()->getAs<FunctionProtoType>();
169   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
170   if (!Proto)
171     return;
172 
173   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
174 
175   // If we have a throw-all spec at this point, ignore the function.
176   if (ComputedEST == EST_None)
177     return;
178 
179   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
180     EST = EST_BasicNoexcept;
181 
182   switch (EST) {
183   case EST_Unparsed:
184   case EST_Uninstantiated:
185   case EST_Unevaluated:
186     llvm_unreachable("should not see unresolved exception specs here");
187 
188   // If this function can throw any exceptions, make a note of that.
189   case EST_MSAny:
190   case EST_None:
191     // FIXME: Whichever we see last of MSAny and None determines our result.
192     // We should make a consistent, order-independent choice here.
193     ClearExceptions();
194     ComputedEST = EST;
195     return;
196   case EST_NoexceptFalse:
197     ClearExceptions();
198     ComputedEST = EST_None;
199     return;
200   // FIXME: If the call to this decl is using any of its default arguments, we
201   // need to search them for potentially-throwing calls.
202   // If this function has a basic noexcept, it doesn't affect the outcome.
203   case EST_BasicNoexcept:
204   case EST_NoexceptTrue:
205   case EST_NoThrow:
206     return;
207   // If we're still at noexcept(true) and there's a throw() callee,
208   // change to that specification.
209   case EST_DynamicNone:
210     if (ComputedEST == EST_BasicNoexcept)
211       ComputedEST = EST_DynamicNone;
212     return;
213   case EST_DependentNoexcept:
214     llvm_unreachable(
215         "should not generate implicit declarations for dependent cases");
216   case EST_Dynamic:
217     break;
218   }
219   assert(EST == EST_Dynamic && "EST case not considered earlier.");
220   assert(ComputedEST != EST_None &&
221          "Shouldn't collect exceptions when throw-all is guaranteed.");
222   ComputedEST = EST_Dynamic;
223   // Record the exceptions in this function's exception specification.
224   for (const auto &E : Proto->exceptions())
225     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
226       Exceptions.push_back(E);
227 }
228 
229 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
230   if (!S || ComputedEST == EST_MSAny)
231     return;
232 
233   // FIXME:
234   //
235   // C++0x [except.spec]p14:
236   //   [An] implicit exception-specification specifies the type-id T if and
237   // only if T is allowed by the exception-specification of a function directly
238   // invoked by f's implicit definition; f shall allow all exceptions if any
239   // function it directly invokes allows all exceptions, and f shall allow no
240   // exceptions if every function it directly invokes allows no exceptions.
241   //
242   // Note in particular that if an implicit exception-specification is generated
243   // for a function containing a throw-expression, that specification can still
244   // be noexcept(true).
245   //
246   // Note also that 'directly invoked' is not defined in the standard, and there
247   // is no indication that we should only consider potentially-evaluated calls.
248   //
249   // Ultimately we should implement the intent of the standard: the exception
250   // specification should be the set of exceptions which can be thrown by the
251   // implicit definition. For now, we assume that any non-nothrow expression can
252   // throw any exception.
253 
254   if (Self->canThrow(S))
255     ComputedEST = EST_None;
256 }
257 
258 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
259                                              SourceLocation EqualLoc) {
260   if (RequireCompleteType(Param->getLocation(), Param->getType(),
261                           diag::err_typecheck_decl_incomplete_type))
262     return true;
263 
264   // C++ [dcl.fct.default]p5
265   //   A default argument expression is implicitly converted (clause
266   //   4) to the parameter type. The default argument expression has
267   //   the same semantic constraints as the initializer expression in
268   //   a declaration of a variable of the parameter type, using the
269   //   copy-initialization semantics (8.5).
270   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
271                                                                     Param);
272   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
273                                                            EqualLoc);
274   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276   if (Result.isInvalid())
277     return true;
278   Arg = Result.getAs<Expr>();
279 
280   CheckCompletedExpr(Arg, EqualLoc);
281   Arg = MaybeCreateExprWithCleanups(Arg);
282 
283   return Arg;
284 }
285 
286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
287                                    SourceLocation EqualLoc) {
288   // Add the default argument to the parameter
289   Param->setDefaultArg(Arg);
290 
291   // We have already instantiated this parameter; provide each of the
292   // instantiations with the uninstantiated default argument.
293   UnparsedDefaultArgInstantiationsMap::iterator InstPos
294     = UnparsedDefaultArgInstantiations.find(Param);
295   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
297       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
298 
299     // We're done tracking this parameter's instantiations.
300     UnparsedDefaultArgInstantiations.erase(InstPos);
301   }
302 }
303 
304 /// ActOnParamDefaultArgument - Check whether the default argument
305 /// provided for a function parameter is well-formed. If so, attach it
306 /// to the parameter declaration.
307 void
308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
309                                 Expr *DefaultArg) {
310   if (!param || !DefaultArg)
311     return;
312 
313   ParmVarDecl *Param = cast<ParmVarDecl>(param);
314   UnparsedDefaultArgLocs.erase(Param);
315 
316   auto Fail = [&] {
317     Param->setInvalidDecl();
318     Param->setDefaultArg(new (Context) OpaqueValueExpr(
319         EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
320   };
321 
322   // Default arguments are only permitted in C++
323   if (!getLangOpts().CPlusPlus) {
324     Diag(EqualLoc, diag::err_param_default_argument)
325       << DefaultArg->getSourceRange();
326     return Fail();
327   }
328 
329   // Check for unexpanded parameter packs.
330   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
331     return Fail();
332   }
333 
334   // C++11 [dcl.fct.default]p3
335   //   A default argument expression [...] shall not be specified for a
336   //   parameter pack.
337   if (Param->isParameterPack()) {
338     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339         << DefaultArg->getSourceRange();
340     // Recover by discarding the default argument.
341     Param->setDefaultArg(nullptr);
342     return;
343   }
344 
345   ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346   if (Result.isInvalid())
347     return Fail();
348 
349   DefaultArg = Result.getAs<Expr>();
350 
351   // Check that the default argument is well-formed
352   CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353   if (DefaultArgChecker.Visit(DefaultArg))
354     return Fail();
355 
356   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
357 }
358 
359 /// ActOnParamUnparsedDefaultArgument - We've seen a default
360 /// argument for a function parameter, but we can't parse it yet
361 /// because we're inside a class definition. Note that this default
362 /// argument will be parsed later.
363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
364                                              SourceLocation EqualLoc,
365                                              SourceLocation ArgLoc) {
366   if (!param)
367     return;
368 
369   ParmVarDecl *Param = cast<ParmVarDecl>(param);
370   Param->setUnparsedDefaultArg();
371   UnparsedDefaultArgLocs[Param] = ArgLoc;
372 }
373 
374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375 /// the default argument for the parameter param failed.
376 void Sema::ActOnParamDefaultArgumentError(Decl *param,
377                                           SourceLocation EqualLoc) {
378   if (!param)
379     return;
380 
381   ParmVarDecl *Param = cast<ParmVarDecl>(param);
382   Param->setInvalidDecl();
383   UnparsedDefaultArgLocs.erase(Param);
384   Param->setDefaultArg(new (Context) OpaqueValueExpr(
385       EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
386 }
387 
388 /// CheckExtraCXXDefaultArguments - Check for any extra default
389 /// arguments in the declarator, which is not a function declaration
390 /// or definition and therefore is not permitted to have default
391 /// arguments. This routine should be invoked for every declarator
392 /// that is not a function declaration or definition.
393 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
394   // C++ [dcl.fct.default]p3
395   //   A default argument expression shall be specified only in the
396   //   parameter-declaration-clause of a function declaration or in a
397   //   template-parameter (14.1). It shall not be specified for a
398   //   parameter pack. If it is specified in a
399   //   parameter-declaration-clause, it shall not occur within a
400   //   declarator or abstract-declarator of a parameter-declaration.
401   bool MightBeFunction = D.isFunctionDeclarationContext();
402   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
403     DeclaratorChunk &chunk = D.getTypeObject(i);
404     if (chunk.Kind == DeclaratorChunk::Function) {
405       if (MightBeFunction) {
406         // This is a function declaration. It can have default arguments, but
407         // keep looking in case its return type is a function type with default
408         // arguments.
409         MightBeFunction = false;
410         continue;
411       }
412       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
413            ++argIdx) {
414         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
415         if (Param->hasUnparsedDefaultArg()) {
416           std::unique_ptr<CachedTokens> Toks =
417               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
418           SourceRange SR;
419           if (Toks->size() > 1)
420             SR = SourceRange((*Toks)[1].getLocation(),
421                              Toks->back().getLocation());
422           else
423             SR = UnparsedDefaultArgLocs[Param];
424           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
425             << SR;
426         } else if (Param->getDefaultArg()) {
427           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
428             << Param->getDefaultArg()->getSourceRange();
429           Param->setDefaultArg(nullptr);
430         }
431       }
432     } else if (chunk.Kind != DeclaratorChunk::Paren) {
433       MightBeFunction = false;
434     }
435   }
436 }
437 
438 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
439   return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
440     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
441   });
442 }
443 
444 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
445 /// function, once we already know that they have the same
446 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
447 /// error, false otherwise.
448 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
449                                 Scope *S) {
450   bool Invalid = false;
451 
452   // The declaration context corresponding to the scope is the semantic
453   // parent, unless this is a local function declaration, in which case
454   // it is that surrounding function.
455   DeclContext *ScopeDC = New->isLocalExternDecl()
456                              ? New->getLexicalDeclContext()
457                              : New->getDeclContext();
458 
459   // Find the previous declaration for the purpose of default arguments.
460   FunctionDecl *PrevForDefaultArgs = Old;
461   for (/**/; PrevForDefaultArgs;
462        // Don't bother looking back past the latest decl if this is a local
463        // extern declaration; nothing else could work.
464        PrevForDefaultArgs = New->isLocalExternDecl()
465                                 ? nullptr
466                                 : PrevForDefaultArgs->getPreviousDecl()) {
467     // Ignore hidden declarations.
468     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
469       continue;
470 
471     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
472         !New->isCXXClassMember()) {
473       // Ignore default arguments of old decl if they are not in
474       // the same scope and this is not an out-of-line definition of
475       // a member function.
476       continue;
477     }
478 
479     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
480       // If only one of these is a local function declaration, then they are
481       // declared in different scopes, even though isDeclInScope may think
482       // they're in the same scope. (If both are local, the scope check is
483       // sufficient, and if neither is local, then they are in the same scope.)
484       continue;
485     }
486 
487     // We found the right previous declaration.
488     break;
489   }
490 
491   // C++ [dcl.fct.default]p4:
492   //   For non-template functions, default arguments can be added in
493   //   later declarations of a function in the same
494   //   scope. Declarations in different scopes have completely
495   //   distinct sets of default arguments. That is, declarations in
496   //   inner scopes do not acquire default arguments from
497   //   declarations in outer scopes, and vice versa. In a given
498   //   function declaration, all parameters subsequent to a
499   //   parameter with a default argument shall have default
500   //   arguments supplied in this or previous declarations. A
501   //   default argument shall not be redefined by a later
502   //   declaration (not even to the same value).
503   //
504   // C++ [dcl.fct.default]p6:
505   //   Except for member functions of class templates, the default arguments
506   //   in a member function definition that appears outside of the class
507   //   definition are added to the set of default arguments provided by the
508   //   member function declaration in the class definition.
509   for (unsigned p = 0, NumParams = PrevForDefaultArgs
510                                        ? PrevForDefaultArgs->getNumParams()
511                                        : 0;
512        p < NumParams; ++p) {
513     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
514     ParmVarDecl *NewParam = New->getParamDecl(p);
515 
516     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
517     bool NewParamHasDfl = NewParam->hasDefaultArg();
518 
519     if (OldParamHasDfl && NewParamHasDfl) {
520       unsigned DiagDefaultParamID =
521         diag::err_param_default_argument_redefinition;
522 
523       // MSVC accepts that default parameters be redefined for member functions
524       // of template class. The new default parameter's value is ignored.
525       Invalid = true;
526       if (getLangOpts().MicrosoftExt) {
527         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
528         if (MD && MD->getParent()->getDescribedClassTemplate()) {
529           // Merge the old default argument into the new parameter.
530           NewParam->setHasInheritedDefaultArg();
531           if (OldParam->hasUninstantiatedDefaultArg())
532             NewParam->setUninstantiatedDefaultArg(
533                                       OldParam->getUninstantiatedDefaultArg());
534           else
535             NewParam->setDefaultArg(OldParam->getInit());
536           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
537           Invalid = false;
538         }
539       }
540 
541       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
542       // hint here. Alternatively, we could walk the type-source information
543       // for NewParam to find the last source location in the type... but it
544       // isn't worth the effort right now. This is the kind of test case that
545       // is hard to get right:
546       //   int f(int);
547       //   void g(int (*fp)(int) = f);
548       //   void g(int (*fp)(int) = &f);
549       Diag(NewParam->getLocation(), DiagDefaultParamID)
550         << NewParam->getDefaultArgRange();
551 
552       // Look for the function declaration where the default argument was
553       // actually written, which may be a declaration prior to Old.
554       for (auto Older = PrevForDefaultArgs;
555            OldParam->hasInheritedDefaultArg(); /**/) {
556         Older = Older->getPreviousDecl();
557         OldParam = Older->getParamDecl(p);
558       }
559 
560       Diag(OldParam->getLocation(), diag::note_previous_definition)
561         << OldParam->getDefaultArgRange();
562     } else if (OldParamHasDfl) {
563       // Merge the old default argument into the new parameter unless the new
564       // function is a friend declaration in a template class. In the latter
565       // case the default arguments will be inherited when the friend
566       // declaration will be instantiated.
567       if (New->getFriendObjectKind() == Decl::FOK_None ||
568           !New->getLexicalDeclContext()->isDependentContext()) {
569         // It's important to use getInit() here;  getDefaultArg()
570         // strips off any top-level ExprWithCleanups.
571         NewParam->setHasInheritedDefaultArg();
572         if (OldParam->hasUnparsedDefaultArg())
573           NewParam->setUnparsedDefaultArg();
574         else if (OldParam->hasUninstantiatedDefaultArg())
575           NewParam->setUninstantiatedDefaultArg(
576                                        OldParam->getUninstantiatedDefaultArg());
577         else
578           NewParam->setDefaultArg(OldParam->getInit());
579       }
580     } else if (NewParamHasDfl) {
581       if (New->getDescribedFunctionTemplate()) {
582         // Paragraph 4, quoted above, only applies to non-template functions.
583         Diag(NewParam->getLocation(),
584              diag::err_param_default_argument_template_redecl)
585           << NewParam->getDefaultArgRange();
586         Diag(PrevForDefaultArgs->getLocation(),
587              diag::note_template_prev_declaration)
588             << false;
589       } else if (New->getTemplateSpecializationKind()
590                    != TSK_ImplicitInstantiation &&
591                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
592         // C++ [temp.expr.spec]p21:
593         //   Default function arguments shall not be specified in a declaration
594         //   or a definition for one of the following explicit specializations:
595         //     - the explicit specialization of a function template;
596         //     - the explicit specialization of a member function template;
597         //     - the explicit specialization of a member function of a class
598         //       template where the class template specialization to which the
599         //       member function specialization belongs is implicitly
600         //       instantiated.
601         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
602           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
603           << New->getDeclName()
604           << NewParam->getDefaultArgRange();
605       } else if (New->getDeclContext()->isDependentContext()) {
606         // C++ [dcl.fct.default]p6 (DR217):
607         //   Default arguments for a member function of a class template shall
608         //   be specified on the initial declaration of the member function
609         //   within the class template.
610         //
611         // Reading the tea leaves a bit in DR217 and its reference to DR205
612         // leads me to the conclusion that one cannot add default function
613         // arguments for an out-of-line definition of a member function of a
614         // dependent type.
615         int WhichKind = 2;
616         if (CXXRecordDecl *Record
617               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
618           if (Record->getDescribedClassTemplate())
619             WhichKind = 0;
620           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
621             WhichKind = 1;
622           else
623             WhichKind = 2;
624         }
625 
626         Diag(NewParam->getLocation(),
627              diag::err_param_default_argument_member_template_redecl)
628           << WhichKind
629           << NewParam->getDefaultArgRange();
630       }
631     }
632   }
633 
634   // DR1344: If a default argument is added outside a class definition and that
635   // default argument makes the function a special member function, the program
636   // is ill-formed. This can only happen for constructors.
637   if (isa<CXXConstructorDecl>(New) &&
638       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
639     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
640                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
641     if (NewSM != OldSM) {
642       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
643       assert(NewParam->hasDefaultArg());
644       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
645         << NewParam->getDefaultArgRange() << NewSM;
646       Diag(Old->getLocation(), diag::note_previous_declaration);
647     }
648   }
649 
650   const FunctionDecl *Def;
651   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
652   // template has a constexpr specifier then all its declarations shall
653   // contain the constexpr specifier.
654   if (New->getConstexprKind() != Old->getConstexprKind()) {
655     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
656         << New << static_cast<int>(New->getConstexprKind())
657         << static_cast<int>(Old->getConstexprKind());
658     Diag(Old->getLocation(), diag::note_previous_declaration);
659     Invalid = true;
660   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
661              Old->isDefined(Def) &&
662              // If a friend function is inlined but does not have 'inline'
663              // specifier, it is a definition. Do not report attribute conflict
664              // in this case, redefinition will be diagnosed later.
665              (New->isInlineSpecified() ||
666               New->getFriendObjectKind() == Decl::FOK_None)) {
667     // C++11 [dcl.fcn.spec]p4:
668     //   If the definition of a function appears in a translation unit before its
669     //   first declaration as inline, the program is ill-formed.
670     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
671     Diag(Def->getLocation(), diag::note_previous_definition);
672     Invalid = true;
673   }
674 
675   // C++17 [temp.deduct.guide]p3:
676   //   Two deduction guide declarations in the same translation unit
677   //   for the same class template shall not have equivalent
678   //   parameter-declaration-clauses.
679   if (isa<CXXDeductionGuideDecl>(New) &&
680       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
681     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
682     Diag(Old->getLocation(), diag::note_previous_declaration);
683   }
684 
685   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
686   // argument expression, that declaration shall be a definition and shall be
687   // the only declaration of the function or function template in the
688   // translation unit.
689   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
690       functionDeclHasDefaultArgument(Old)) {
691     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
692     Diag(Old->getLocation(), diag::note_previous_declaration);
693     Invalid = true;
694   }
695 
696   // C++11 [temp.friend]p4 (DR329):
697   //   When a function is defined in a friend function declaration in a class
698   //   template, the function is instantiated when the function is odr-used.
699   //   The same restrictions on multiple declarations and definitions that
700   //   apply to non-template function declarations and definitions also apply
701   //   to these implicit definitions.
702   const FunctionDecl *OldDefinition = nullptr;
703   if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
704       Old->isDefined(OldDefinition, true))
705     CheckForFunctionRedefinition(New, OldDefinition);
706 
707   return Invalid;
708 }
709 
710 NamedDecl *
711 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
712                                    MultiTemplateParamsArg TemplateParamLists) {
713   assert(D.isDecompositionDeclarator());
714   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
715 
716   // The syntax only allows a decomposition declarator as a simple-declaration,
717   // a for-range-declaration, or a condition in Clang, but we parse it in more
718   // cases than that.
719   if (!D.mayHaveDecompositionDeclarator()) {
720     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
721       << Decomp.getSourceRange();
722     return nullptr;
723   }
724 
725   if (!TemplateParamLists.empty()) {
726     // FIXME: There's no rule against this, but there are also no rules that
727     // would actually make it usable, so we reject it for now.
728     Diag(TemplateParamLists.front()->getTemplateLoc(),
729          diag::err_decomp_decl_template);
730     return nullptr;
731   }
732 
733   Diag(Decomp.getLSquareLoc(),
734        !getLangOpts().CPlusPlus17
735            ? diag::ext_decomp_decl
736            : D.getContext() == DeclaratorContext::Condition
737                  ? diag::ext_decomp_decl_cond
738                  : diag::warn_cxx14_compat_decomp_decl)
739       << Decomp.getSourceRange();
740 
741   // The semantic context is always just the current context.
742   DeclContext *const DC = CurContext;
743 
744   // C++17 [dcl.dcl]/8:
745   //   The decl-specifier-seq shall contain only the type-specifier auto
746   //   and cv-qualifiers.
747   // C++2a [dcl.dcl]/8:
748   //   If decl-specifier-seq contains any decl-specifier other than static,
749   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
750   auto &DS = D.getDeclSpec();
751   {
752     SmallVector<StringRef, 8> BadSpecifiers;
753     SmallVector<SourceLocation, 8> BadSpecifierLocs;
754     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
755     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
756     if (auto SCS = DS.getStorageClassSpec()) {
757       if (SCS == DeclSpec::SCS_static) {
758         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
759         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
760       } else {
761         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
762         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
763       }
764     }
765     if (auto TSCS = DS.getThreadStorageClassSpec()) {
766       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
767       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
768     }
769     if (DS.hasConstexprSpecifier()) {
770       BadSpecifiers.push_back(
771           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
772       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
773     }
774     if (DS.isInlineSpecified()) {
775       BadSpecifiers.push_back("inline");
776       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
777     }
778     if (!BadSpecifiers.empty()) {
779       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
780       Err << (int)BadSpecifiers.size()
781           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
782       // Don't add FixItHints to remove the specifiers; we do still respect
783       // them when building the underlying variable.
784       for (auto Loc : BadSpecifierLocs)
785         Err << SourceRange(Loc, Loc);
786     } else if (!CPlusPlus20Specifiers.empty()) {
787       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
788                          getLangOpts().CPlusPlus20
789                              ? diag::warn_cxx17_compat_decomp_decl_spec
790                              : diag::ext_decomp_decl_spec);
791       Warn << (int)CPlusPlus20Specifiers.size()
792            << llvm::join(CPlusPlus20Specifiers.begin(),
793                          CPlusPlus20Specifiers.end(), " ");
794       for (auto Loc : CPlusPlus20SpecifierLocs)
795         Warn << SourceRange(Loc, Loc);
796     }
797     // We can't recover from it being declared as a typedef.
798     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
799       return nullptr;
800   }
801 
802   // C++2a [dcl.struct.bind]p1:
803   //   A cv that includes volatile is deprecated
804   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
805       getLangOpts().CPlusPlus20)
806     Diag(DS.getVolatileSpecLoc(),
807          diag::warn_deprecated_volatile_structured_binding);
808 
809   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
810   QualType R = TInfo->getType();
811 
812   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
813                                       UPPC_DeclarationType))
814     D.setInvalidType();
815 
816   // The syntax only allows a single ref-qualifier prior to the decomposition
817   // declarator. No other declarator chunks are permitted. Also check the type
818   // specifier here.
819   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
820       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
821       (D.getNumTypeObjects() == 1 &&
822        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
823     Diag(Decomp.getLSquareLoc(),
824          (D.hasGroupingParens() ||
825           (D.getNumTypeObjects() &&
826            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
827              ? diag::err_decomp_decl_parens
828              : diag::err_decomp_decl_type)
829         << R;
830 
831     // In most cases, there's no actual problem with an explicitly-specified
832     // type, but a function type won't work here, and ActOnVariableDeclarator
833     // shouldn't be called for such a type.
834     if (R->isFunctionType())
835       D.setInvalidType();
836   }
837 
838   // Build the BindingDecls.
839   SmallVector<BindingDecl*, 8> Bindings;
840 
841   // Build the BindingDecls.
842   for (auto &B : D.getDecompositionDeclarator().bindings()) {
843     // Check for name conflicts.
844     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
845     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
846                           ForVisibleRedeclaration);
847     LookupName(Previous, S,
848                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
849 
850     // It's not permitted to shadow a template parameter name.
851     if (Previous.isSingleResult() &&
852         Previous.getFoundDecl()->isTemplateParameter()) {
853       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
854                                       Previous.getFoundDecl());
855       Previous.clear();
856     }
857 
858     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
859 
860     // Find the shadowed declaration before filtering for scope.
861     NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
862                                   ? getShadowedDeclaration(BD, Previous)
863                                   : nullptr;
864 
865     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
866                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
867     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
868                          /*AllowInlineNamespace*/false);
869 
870     if (!Previous.empty()) {
871       auto *Old = Previous.getRepresentativeDecl();
872       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
873       Diag(Old->getLocation(), diag::note_previous_definition);
874     } else if (ShadowedDecl && !D.isRedeclaration()) {
875       CheckShadow(BD, ShadowedDecl, Previous);
876     }
877     PushOnScopeChains(BD, S, true);
878     Bindings.push_back(BD);
879     ParsingInitForAutoVars.insert(BD);
880   }
881 
882   // There are no prior lookup results for the variable itself, because it
883   // is unnamed.
884   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
885                                Decomp.getLSquareLoc());
886   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
887                         ForVisibleRedeclaration);
888 
889   // Build the variable that holds the non-decomposed object.
890   bool AddToScope = true;
891   NamedDecl *New =
892       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
893                               MultiTemplateParamsArg(), AddToScope, Bindings);
894   if (AddToScope) {
895     S->AddDecl(New);
896     CurContext->addHiddenDecl(New);
897   }
898 
899   if (isInOpenMPDeclareTargetContext())
900     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
901 
902   return New;
903 }
904 
905 static bool checkSimpleDecomposition(
906     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
907     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
908     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
909   if ((int64_t)Bindings.size() != NumElems) {
910     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
911         << DecompType << (unsigned)Bindings.size()
912         << (unsigned)NumElems.getLimitedValue(UINT_MAX)
913         << toString(NumElems, 10) << (NumElems < Bindings.size());
914     return true;
915   }
916 
917   unsigned I = 0;
918   for (auto *B : Bindings) {
919     SourceLocation Loc = B->getLocation();
920     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
921     if (E.isInvalid())
922       return true;
923     E = GetInit(Loc, E.get(), I++);
924     if (E.isInvalid())
925       return true;
926     B->setBinding(ElemType, E.get());
927   }
928 
929   return false;
930 }
931 
932 static bool checkArrayLikeDecomposition(Sema &S,
933                                         ArrayRef<BindingDecl *> Bindings,
934                                         ValueDecl *Src, QualType DecompType,
935                                         const llvm::APSInt &NumElems,
936                                         QualType ElemType) {
937   return checkSimpleDecomposition(
938       S, Bindings, Src, DecompType, NumElems, ElemType,
939       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
940         ExprResult E = S.ActOnIntegerConstant(Loc, I);
941         if (E.isInvalid())
942           return ExprError();
943         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
944       });
945 }
946 
947 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
948                                     ValueDecl *Src, QualType DecompType,
949                                     const ConstantArrayType *CAT) {
950   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
951                                      llvm::APSInt(CAT->getSize()),
952                                      CAT->getElementType());
953 }
954 
955 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
956                                      ValueDecl *Src, QualType DecompType,
957                                      const VectorType *VT) {
958   return checkArrayLikeDecomposition(
959       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
960       S.Context.getQualifiedType(VT->getElementType(),
961                                  DecompType.getQualifiers()));
962 }
963 
964 static bool checkComplexDecomposition(Sema &S,
965                                       ArrayRef<BindingDecl *> Bindings,
966                                       ValueDecl *Src, QualType DecompType,
967                                       const ComplexType *CT) {
968   return checkSimpleDecomposition(
969       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
970       S.Context.getQualifiedType(CT->getElementType(),
971                                  DecompType.getQualifiers()),
972       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
973         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
974       });
975 }
976 
977 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
978                                      TemplateArgumentListInfo &Args,
979                                      const TemplateParameterList *Params) {
980   SmallString<128> SS;
981   llvm::raw_svector_ostream OS(SS);
982   bool First = true;
983   unsigned I = 0;
984   for (auto &Arg : Args.arguments()) {
985     if (!First)
986       OS << ", ";
987     Arg.getArgument().print(PrintingPolicy, OS,
988                             TemplateParameterList::shouldIncludeTypeForArgument(
989                                 PrintingPolicy, Params, I));
990     First = false;
991     I++;
992   }
993   return std::string(OS.str());
994 }
995 
996 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
997                                      SourceLocation Loc, StringRef Trait,
998                                      TemplateArgumentListInfo &Args,
999                                      unsigned DiagID) {
1000   auto DiagnoseMissing = [&] {
1001     if (DiagID)
1002       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1003                                                Args, /*Params*/ nullptr);
1004     return true;
1005   };
1006 
1007   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1008   NamespaceDecl *Std = S.getStdNamespace();
1009   if (!Std)
1010     return DiagnoseMissing();
1011 
1012   // Look up the trait itself, within namespace std. We can diagnose various
1013   // problems with this lookup even if we've been asked to not diagnose a
1014   // missing specialization, because this can only fail if the user has been
1015   // declaring their own names in namespace std or we don't support the
1016   // standard library implementation in use.
1017   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1018                       Loc, Sema::LookupOrdinaryName);
1019   if (!S.LookupQualifiedName(Result, Std))
1020     return DiagnoseMissing();
1021   if (Result.isAmbiguous())
1022     return true;
1023 
1024   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1025   if (!TraitTD) {
1026     Result.suppressDiagnostics();
1027     NamedDecl *Found = *Result.begin();
1028     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1029     S.Diag(Found->getLocation(), diag::note_declared_at);
1030     return true;
1031   }
1032 
1033   // Build the template-id.
1034   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1035   if (TraitTy.isNull())
1036     return true;
1037   if (!S.isCompleteType(Loc, TraitTy)) {
1038     if (DiagID)
1039       S.RequireCompleteType(
1040           Loc, TraitTy, DiagID,
1041           printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1042                             TraitTD->getTemplateParameters()));
1043     return true;
1044   }
1045 
1046   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1047   assert(RD && "specialization of class template is not a class?");
1048 
1049   // Look up the member of the trait type.
1050   S.LookupQualifiedName(TraitMemberLookup, RD);
1051   return TraitMemberLookup.isAmbiguous();
1052 }
1053 
1054 static TemplateArgumentLoc
1055 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1056                                    uint64_t I) {
1057   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1058   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1059 }
1060 
1061 static TemplateArgumentLoc
1062 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1063   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1064 }
1065 
1066 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1067 
1068 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1069                                llvm::APSInt &Size) {
1070   EnterExpressionEvaluationContext ContextRAII(
1071       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1072 
1073   DeclarationName Value = S.PP.getIdentifierInfo("value");
1074   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1075 
1076   // Form template argument list for tuple_size<T>.
1077   TemplateArgumentListInfo Args(Loc, Loc);
1078   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1079 
1080   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1081   // it's not tuple-like.
1082   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1083       R.empty())
1084     return IsTupleLike::NotTupleLike;
1085 
1086   // If we get this far, we've committed to the tuple interpretation, but
1087   // we can still fail if there actually isn't a usable ::value.
1088 
1089   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1090     LookupResult &R;
1091     TemplateArgumentListInfo &Args;
1092     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1093         : R(R), Args(Args) {}
1094     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1095                                                SourceLocation Loc) override {
1096       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1097              << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1098                                   /*Params*/ nullptr);
1099     }
1100   } Diagnoser(R, Args);
1101 
1102   ExprResult E =
1103       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1104   if (E.isInvalid())
1105     return IsTupleLike::Error;
1106 
1107   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1108   if (E.isInvalid())
1109     return IsTupleLike::Error;
1110 
1111   return IsTupleLike::TupleLike;
1112 }
1113 
1114 /// \return std::tuple_element<I, T>::type.
1115 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1116                                         unsigned I, QualType T) {
1117   // Form template argument list for tuple_element<I, T>.
1118   TemplateArgumentListInfo Args(Loc, Loc);
1119   Args.addArgument(
1120       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1121   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1122 
1123   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1124   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1125   if (lookupStdTypeTraitMember(
1126           S, R, Loc, "tuple_element", Args,
1127           diag::err_decomp_decl_std_tuple_element_not_specialized))
1128     return QualType();
1129 
1130   auto *TD = R.getAsSingle<TypeDecl>();
1131   if (!TD) {
1132     R.suppressDiagnostics();
1133     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1134         << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1135                              /*Params*/ nullptr);
1136     if (!R.empty())
1137       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1138     return QualType();
1139   }
1140 
1141   return S.Context.getTypeDeclType(TD);
1142 }
1143 
1144 namespace {
1145 struct InitializingBinding {
1146   Sema &S;
1147   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1148     Sema::CodeSynthesisContext Ctx;
1149     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1150     Ctx.PointOfInstantiation = BD->getLocation();
1151     Ctx.Entity = BD;
1152     S.pushCodeSynthesisContext(Ctx);
1153   }
1154   ~InitializingBinding() {
1155     S.popCodeSynthesisContext();
1156   }
1157 };
1158 }
1159 
1160 static bool checkTupleLikeDecomposition(Sema &S,
1161                                         ArrayRef<BindingDecl *> Bindings,
1162                                         VarDecl *Src, QualType DecompType,
1163                                         const llvm::APSInt &TupleSize) {
1164   if ((int64_t)Bindings.size() != TupleSize) {
1165     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1166         << DecompType << (unsigned)Bindings.size()
1167         << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1168         << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1169     return true;
1170   }
1171 
1172   if (Bindings.empty())
1173     return false;
1174 
1175   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1176 
1177   // [dcl.decomp]p3:
1178   //   The unqualified-id get is looked up in the scope of E by class member
1179   //   access lookup ...
1180   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1181   bool UseMemberGet = false;
1182   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1183     if (auto *RD = DecompType->getAsCXXRecordDecl())
1184       S.LookupQualifiedName(MemberGet, RD);
1185     if (MemberGet.isAmbiguous())
1186       return true;
1187     //   ... and if that finds at least one declaration that is a function
1188     //   template whose first template parameter is a non-type parameter ...
1189     for (NamedDecl *D : MemberGet) {
1190       if (FunctionTemplateDecl *FTD =
1191               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1192         TemplateParameterList *TPL = FTD->getTemplateParameters();
1193         if (TPL->size() != 0 &&
1194             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1195           //   ... the initializer is e.get<i>().
1196           UseMemberGet = true;
1197           break;
1198         }
1199       }
1200     }
1201   }
1202 
1203   unsigned I = 0;
1204   for (auto *B : Bindings) {
1205     InitializingBinding InitContext(S, B);
1206     SourceLocation Loc = B->getLocation();
1207 
1208     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1209     if (E.isInvalid())
1210       return true;
1211 
1212     //   e is an lvalue if the type of the entity is an lvalue reference and
1213     //   an xvalue otherwise
1214     if (!Src->getType()->isLValueReferenceType())
1215       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1216                                    E.get(), nullptr, VK_XValue,
1217                                    FPOptionsOverride());
1218 
1219     TemplateArgumentListInfo Args(Loc, Loc);
1220     Args.addArgument(
1221         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1222 
1223     if (UseMemberGet) {
1224       //   if [lookup of member get] finds at least one declaration, the
1225       //   initializer is e.get<i-1>().
1226       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1227                                      CXXScopeSpec(), SourceLocation(), nullptr,
1228                                      MemberGet, &Args, nullptr);
1229       if (E.isInvalid())
1230         return true;
1231 
1232       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1233     } else {
1234       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1235       //   in the associated namespaces.
1236       Expr *Get = UnresolvedLookupExpr::Create(
1237           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1238           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1239           UnresolvedSetIterator(), UnresolvedSetIterator());
1240 
1241       Expr *Arg = E.get();
1242       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1243     }
1244     if (E.isInvalid())
1245       return true;
1246     Expr *Init = E.get();
1247 
1248     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1249     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1250     if (T.isNull())
1251       return true;
1252 
1253     //   each vi is a variable of type "reference to T" initialized with the
1254     //   initializer, where the reference is an lvalue reference if the
1255     //   initializer is an lvalue and an rvalue reference otherwise
1256     QualType RefType =
1257         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1258     if (RefType.isNull())
1259       return true;
1260     auto *RefVD = VarDecl::Create(
1261         S.Context, Src->getDeclContext(), Loc, Loc,
1262         B->getDeclName().getAsIdentifierInfo(), RefType,
1263         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1264     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1265     RefVD->setTSCSpec(Src->getTSCSpec());
1266     RefVD->setImplicit();
1267     if (Src->isInlineSpecified())
1268       RefVD->setInlineSpecified();
1269     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1270 
1271     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1272     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1273     InitializationSequence Seq(S, Entity, Kind, Init);
1274     E = Seq.Perform(S, Entity, Kind, Init);
1275     if (E.isInvalid())
1276       return true;
1277     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1278     if (E.isInvalid())
1279       return true;
1280     RefVD->setInit(E.get());
1281     S.CheckCompleteVariableDeclaration(RefVD);
1282 
1283     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1284                                    DeclarationNameInfo(B->getDeclName(), Loc),
1285                                    RefVD);
1286     if (E.isInvalid())
1287       return true;
1288 
1289     B->setBinding(T, E.get());
1290     I++;
1291   }
1292 
1293   return false;
1294 }
1295 
1296 /// Find the base class to decompose in a built-in decomposition of a class type.
1297 /// This base class search is, unfortunately, not quite like any other that we
1298 /// perform anywhere else in C++.
1299 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1300                                                 const CXXRecordDecl *RD,
1301                                                 CXXCastPath &BasePath) {
1302   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1303                           CXXBasePath &Path) {
1304     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1305   };
1306 
1307   const CXXRecordDecl *ClassWithFields = nullptr;
1308   AccessSpecifier AS = AS_public;
1309   if (RD->hasDirectFields())
1310     // [dcl.decomp]p4:
1311     //   Otherwise, all of E's non-static data members shall be public direct
1312     //   members of E ...
1313     ClassWithFields = RD;
1314   else {
1315     //   ... or of ...
1316     CXXBasePaths Paths;
1317     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1318     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1319       // If no classes have fields, just decompose RD itself. (This will work
1320       // if and only if zero bindings were provided.)
1321       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1322     }
1323 
1324     CXXBasePath *BestPath = nullptr;
1325     for (auto &P : Paths) {
1326       if (!BestPath)
1327         BestPath = &P;
1328       else if (!S.Context.hasSameType(P.back().Base->getType(),
1329                                       BestPath->back().Base->getType())) {
1330         //   ... the same ...
1331         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1332           << false << RD << BestPath->back().Base->getType()
1333           << P.back().Base->getType();
1334         return DeclAccessPair();
1335       } else if (P.Access < BestPath->Access) {
1336         BestPath = &P;
1337       }
1338     }
1339 
1340     //   ... unambiguous ...
1341     QualType BaseType = BestPath->back().Base->getType();
1342     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1343       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1344         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1345       return DeclAccessPair();
1346     }
1347 
1348     //   ... [accessible, implied by other rules] base class of E.
1349     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1350                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1351     AS = BestPath->Access;
1352 
1353     ClassWithFields = BaseType->getAsCXXRecordDecl();
1354     S.BuildBasePathArray(Paths, BasePath);
1355   }
1356 
1357   // The above search did not check whether the selected class itself has base
1358   // classes with fields, so check that now.
1359   CXXBasePaths Paths;
1360   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1361     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1362       << (ClassWithFields == RD) << RD << ClassWithFields
1363       << Paths.front().back().Base->getType();
1364     return DeclAccessPair();
1365   }
1366 
1367   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1368 }
1369 
1370 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1371                                      ValueDecl *Src, QualType DecompType,
1372                                      const CXXRecordDecl *OrigRD) {
1373   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1374                             diag::err_incomplete_type))
1375     return true;
1376 
1377   CXXCastPath BasePath;
1378   DeclAccessPair BasePair =
1379       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1380   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1381   if (!RD)
1382     return true;
1383   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1384                                                  DecompType.getQualifiers());
1385 
1386   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1387     unsigned NumFields = llvm::count_if(
1388         RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1389     assert(Bindings.size() != NumFields);
1390     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1391         << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1392         << (NumFields < Bindings.size());
1393     return true;
1394   };
1395 
1396   //   all of E's non-static data members shall be [...] well-formed
1397   //   when named as e.name in the context of the structured binding,
1398   //   E shall not have an anonymous union member, ...
1399   unsigned I = 0;
1400   for (auto *FD : RD->fields()) {
1401     if (FD->isUnnamedBitfield())
1402       continue;
1403 
1404     // All the non-static data members are required to be nameable, so they
1405     // must all have names.
1406     if (!FD->getDeclName()) {
1407       if (RD->isLambda()) {
1408         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1409         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1410         return true;
1411       }
1412 
1413       if (FD->isAnonymousStructOrUnion()) {
1414         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1415           << DecompType << FD->getType()->isUnionType();
1416         S.Diag(FD->getLocation(), diag::note_declared_at);
1417         return true;
1418       }
1419 
1420       // FIXME: Are there any other ways we could have an anonymous member?
1421     }
1422 
1423     // We have a real field to bind.
1424     if (I >= Bindings.size())
1425       return DiagnoseBadNumberOfBindings();
1426     auto *B = Bindings[I++];
1427     SourceLocation Loc = B->getLocation();
1428 
1429     // The field must be accessible in the context of the structured binding.
1430     // We already checked that the base class is accessible.
1431     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1432     // const_cast here.
1433     S.CheckStructuredBindingMemberAccess(
1434         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1435         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1436                                      BasePair.getAccess(), FD->getAccess())));
1437 
1438     // Initialize the binding to Src.FD.
1439     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1440     if (E.isInvalid())
1441       return true;
1442     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1443                             VK_LValue, &BasePath);
1444     if (E.isInvalid())
1445       return true;
1446     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1447                                   CXXScopeSpec(), FD,
1448                                   DeclAccessPair::make(FD, FD->getAccess()),
1449                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1450     if (E.isInvalid())
1451       return true;
1452 
1453     // If the type of the member is T, the referenced type is cv T, where cv is
1454     // the cv-qualification of the decomposition expression.
1455     //
1456     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1457     // 'const' to the type of the field.
1458     Qualifiers Q = DecompType.getQualifiers();
1459     if (FD->isMutable())
1460       Q.removeConst();
1461     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1462   }
1463 
1464   if (I != Bindings.size())
1465     return DiagnoseBadNumberOfBindings();
1466 
1467   return false;
1468 }
1469 
1470 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1471   QualType DecompType = DD->getType();
1472 
1473   // If the type of the decomposition is dependent, then so is the type of
1474   // each binding.
1475   if (DecompType->isDependentType()) {
1476     for (auto *B : DD->bindings())
1477       B->setType(Context.DependentTy);
1478     return;
1479   }
1480 
1481   DecompType = DecompType.getNonReferenceType();
1482   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1483 
1484   // C++1z [dcl.decomp]/2:
1485   //   If E is an array type [...]
1486   // As an extension, we also support decomposition of built-in complex and
1487   // vector types.
1488   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1489     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1490       DD->setInvalidDecl();
1491     return;
1492   }
1493   if (auto *VT = DecompType->getAs<VectorType>()) {
1494     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1495       DD->setInvalidDecl();
1496     return;
1497   }
1498   if (auto *CT = DecompType->getAs<ComplexType>()) {
1499     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1500       DD->setInvalidDecl();
1501     return;
1502   }
1503 
1504   // C++1z [dcl.decomp]/3:
1505   //   if the expression std::tuple_size<E>::value is a well-formed integral
1506   //   constant expression, [...]
1507   llvm::APSInt TupleSize(32);
1508   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1509   case IsTupleLike::Error:
1510     DD->setInvalidDecl();
1511     return;
1512 
1513   case IsTupleLike::TupleLike:
1514     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1515       DD->setInvalidDecl();
1516     return;
1517 
1518   case IsTupleLike::NotTupleLike:
1519     break;
1520   }
1521 
1522   // C++1z [dcl.dcl]/8:
1523   //   [E shall be of array or non-union class type]
1524   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1525   if (!RD || RD->isUnion()) {
1526     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1527         << DD << !RD << DecompType;
1528     DD->setInvalidDecl();
1529     return;
1530   }
1531 
1532   // C++1z [dcl.decomp]/4:
1533   //   all of E's non-static data members shall be [...] direct members of
1534   //   E or of the same unambiguous public base class of E, ...
1535   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1536     DD->setInvalidDecl();
1537 }
1538 
1539 /// Merge the exception specifications of two variable declarations.
1540 ///
1541 /// This is called when there's a redeclaration of a VarDecl. The function
1542 /// checks if the redeclaration might have an exception specification and
1543 /// validates compatibility and merges the specs if necessary.
1544 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1545   // Shortcut if exceptions are disabled.
1546   if (!getLangOpts().CXXExceptions)
1547     return;
1548 
1549   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1550          "Should only be called if types are otherwise the same.");
1551 
1552   QualType NewType = New->getType();
1553   QualType OldType = Old->getType();
1554 
1555   // We're only interested in pointers and references to functions, as well
1556   // as pointers to member functions.
1557   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1558     NewType = R->getPointeeType();
1559     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1560   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1561     NewType = P->getPointeeType();
1562     OldType = OldType->castAs<PointerType>()->getPointeeType();
1563   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1564     NewType = M->getPointeeType();
1565     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1566   }
1567 
1568   if (!NewType->isFunctionProtoType())
1569     return;
1570 
1571   // There's lots of special cases for functions. For function pointers, system
1572   // libraries are hopefully not as broken so that we don't need these
1573   // workarounds.
1574   if (CheckEquivalentExceptionSpec(
1575         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1576         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1577     New->setInvalidDecl();
1578   }
1579 }
1580 
1581 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1582 /// function declaration are well-formed according to C++
1583 /// [dcl.fct.default].
1584 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1585   unsigned NumParams = FD->getNumParams();
1586   unsigned ParamIdx = 0;
1587 
1588   // This checking doesn't make sense for explicit specializations; their
1589   // default arguments are determined by the declaration we're specializing,
1590   // not by FD.
1591   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1592     return;
1593   if (auto *FTD = FD->getDescribedFunctionTemplate())
1594     if (FTD->isMemberSpecialization())
1595       return;
1596 
1597   // Find first parameter with a default argument
1598   for (; ParamIdx < NumParams; ++ParamIdx) {
1599     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1600     if (Param->hasDefaultArg())
1601       break;
1602   }
1603 
1604   // C++20 [dcl.fct.default]p4:
1605   //   In a given function declaration, each parameter subsequent to a parameter
1606   //   with a default argument shall have a default argument supplied in this or
1607   //   a previous declaration, unless the parameter was expanded from a
1608   //   parameter pack, or shall be a function parameter pack.
1609   for (; ParamIdx < NumParams; ++ParamIdx) {
1610     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1611     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1612         !(CurrentInstantiationScope &&
1613           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1614       if (Param->isInvalidDecl())
1615         /* We already complained about this parameter. */;
1616       else if (Param->getIdentifier())
1617         Diag(Param->getLocation(),
1618              diag::err_param_default_argument_missing_name)
1619           << Param->getIdentifier();
1620       else
1621         Diag(Param->getLocation(),
1622              diag::err_param_default_argument_missing);
1623     }
1624   }
1625 }
1626 
1627 /// Check that the given type is a literal type. Issue a diagnostic if not,
1628 /// if Kind is Diagnose.
1629 /// \return \c true if a problem has been found (and optionally diagnosed).
1630 template <typename... Ts>
1631 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1632                              SourceLocation Loc, QualType T, unsigned DiagID,
1633                              Ts &&...DiagArgs) {
1634   if (T->isDependentType())
1635     return false;
1636 
1637   switch (Kind) {
1638   case Sema::CheckConstexprKind::Diagnose:
1639     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1640                                       std::forward<Ts>(DiagArgs)...);
1641 
1642   case Sema::CheckConstexprKind::CheckValid:
1643     return !T->isLiteralType(SemaRef.Context);
1644   }
1645 
1646   llvm_unreachable("unknown CheckConstexprKind");
1647 }
1648 
1649 /// Determine whether a destructor cannot be constexpr due to
1650 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1651                                                const CXXDestructorDecl *DD,
1652                                                Sema::CheckConstexprKind Kind) {
1653   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1654     const CXXRecordDecl *RD =
1655         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1656     if (!RD || RD->hasConstexprDestructor())
1657       return true;
1658 
1659     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1660       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1661           << static_cast<int>(DD->getConstexprKind()) << !FD
1662           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1663       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1664           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1665     }
1666     return false;
1667   };
1668 
1669   const CXXRecordDecl *RD = DD->getParent();
1670   for (const CXXBaseSpecifier &B : RD->bases())
1671     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1672       return false;
1673   for (const FieldDecl *FD : RD->fields())
1674     if (!Check(FD->getLocation(), FD->getType(), FD))
1675       return false;
1676   return true;
1677 }
1678 
1679 /// Check whether a function's parameter types are all literal types. If so,
1680 /// return true. If not, produce a suitable diagnostic and return false.
1681 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1682                                          const FunctionDecl *FD,
1683                                          Sema::CheckConstexprKind Kind) {
1684   unsigned ArgIndex = 0;
1685   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1686   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1687                                               e = FT->param_type_end();
1688        i != e; ++i, ++ArgIndex) {
1689     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1690     SourceLocation ParamLoc = PD->getLocation();
1691     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1692                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1693                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1694                          FD->isConsteval()))
1695       return false;
1696   }
1697   return true;
1698 }
1699 
1700 /// Check whether a function's return type is a literal type. If so, return
1701 /// true. If not, produce a suitable diagnostic and return false.
1702 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1703                                      Sema::CheckConstexprKind Kind) {
1704   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1705                        diag::err_constexpr_non_literal_return,
1706                        FD->isConsteval()))
1707     return false;
1708   return true;
1709 }
1710 
1711 /// Get diagnostic %select index for tag kind for
1712 /// record diagnostic message.
1713 /// WARNING: Indexes apply to particular diagnostics only!
1714 ///
1715 /// \returns diagnostic %select index.
1716 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1717   switch (Tag) {
1718   case TTK_Struct: return 0;
1719   case TTK_Interface: return 1;
1720   case TTK_Class:  return 2;
1721   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1722   }
1723 }
1724 
1725 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1726                                        Stmt *Body,
1727                                        Sema::CheckConstexprKind Kind);
1728 
1729 // Check whether a function declaration satisfies the requirements of a
1730 // constexpr function definition or a constexpr constructor definition. If so,
1731 // return true. If not, produce appropriate diagnostics (unless asked not to by
1732 // Kind) and return false.
1733 //
1734 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1735 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1736                                             CheckConstexprKind Kind) {
1737   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1738   if (MD && MD->isInstance()) {
1739     // C++11 [dcl.constexpr]p4:
1740     //  The definition of a constexpr constructor shall satisfy the following
1741     //  constraints:
1742     //  - the class shall not have any virtual base classes;
1743     //
1744     // FIXME: This only applies to constructors and destructors, not arbitrary
1745     // member functions.
1746     const CXXRecordDecl *RD = MD->getParent();
1747     if (RD->getNumVBases()) {
1748       if (Kind == CheckConstexprKind::CheckValid)
1749         return false;
1750 
1751       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1752         << isa<CXXConstructorDecl>(NewFD)
1753         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1754       for (const auto &I : RD->vbases())
1755         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1756             << I.getSourceRange();
1757       return false;
1758     }
1759   }
1760 
1761   if (!isa<CXXConstructorDecl>(NewFD)) {
1762     // C++11 [dcl.constexpr]p3:
1763     //  The definition of a constexpr function shall satisfy the following
1764     //  constraints:
1765     // - it shall not be virtual; (removed in C++20)
1766     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1767     if (Method && Method->isVirtual()) {
1768       if (getLangOpts().CPlusPlus20) {
1769         if (Kind == CheckConstexprKind::Diagnose)
1770           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1771       } else {
1772         if (Kind == CheckConstexprKind::CheckValid)
1773           return false;
1774 
1775         Method = Method->getCanonicalDecl();
1776         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1777 
1778         // If it's not obvious why this function is virtual, find an overridden
1779         // function which uses the 'virtual' keyword.
1780         const CXXMethodDecl *WrittenVirtual = Method;
1781         while (!WrittenVirtual->isVirtualAsWritten())
1782           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1783         if (WrittenVirtual != Method)
1784           Diag(WrittenVirtual->getLocation(),
1785                diag::note_overridden_virtual_function);
1786         return false;
1787       }
1788     }
1789 
1790     // - its return type shall be a literal type;
1791     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1792       return false;
1793   }
1794 
1795   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1796     // A destructor can be constexpr only if the defaulted destructor could be;
1797     // we don't need to check the members and bases if we already know they all
1798     // have constexpr destructors.
1799     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1800       if (Kind == CheckConstexprKind::CheckValid)
1801         return false;
1802       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1803         return false;
1804     }
1805   }
1806 
1807   // - each of its parameter types shall be a literal type;
1808   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1809     return false;
1810 
1811   Stmt *Body = NewFD->getBody();
1812   assert(Body &&
1813          "CheckConstexprFunctionDefinition called on function with no body");
1814   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1815 }
1816 
1817 /// Check the given declaration statement is legal within a constexpr function
1818 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1819 ///
1820 /// \return true if the body is OK (maybe only as an extension), false if we
1821 ///         have diagnosed a problem.
1822 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1823                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1824                                    Sema::CheckConstexprKind Kind) {
1825   // C++11 [dcl.constexpr]p3 and p4:
1826   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1827   //  contain only
1828   for (const auto *DclIt : DS->decls()) {
1829     switch (DclIt->getKind()) {
1830     case Decl::StaticAssert:
1831     case Decl::Using:
1832     case Decl::UsingShadow:
1833     case Decl::UsingDirective:
1834     case Decl::UnresolvedUsingTypename:
1835     case Decl::UnresolvedUsingValue:
1836     case Decl::UsingEnum:
1837       //   - static_assert-declarations
1838       //   - using-declarations,
1839       //   - using-directives,
1840       //   - using-enum-declaration
1841       continue;
1842 
1843     case Decl::Typedef:
1844     case Decl::TypeAlias: {
1845       //   - typedef declarations and alias-declarations that do not define
1846       //     classes or enumerations,
1847       const auto *TN = cast<TypedefNameDecl>(DclIt);
1848       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1849         // Don't allow variably-modified types in constexpr functions.
1850         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1851           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1852           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1853             << TL.getSourceRange() << TL.getType()
1854             << isa<CXXConstructorDecl>(Dcl);
1855         }
1856         return false;
1857       }
1858       continue;
1859     }
1860 
1861     case Decl::Enum:
1862     case Decl::CXXRecord:
1863       // C++1y allows types to be defined, not just declared.
1864       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1865         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866           SemaRef.Diag(DS->getBeginLoc(),
1867                        SemaRef.getLangOpts().CPlusPlus14
1868                            ? diag::warn_cxx11_compat_constexpr_type_definition
1869                            : diag::ext_constexpr_type_definition)
1870               << isa<CXXConstructorDecl>(Dcl);
1871         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1872           return false;
1873         }
1874       }
1875       continue;
1876 
1877     case Decl::EnumConstant:
1878     case Decl::IndirectField:
1879     case Decl::ParmVar:
1880       // These can only appear with other declarations which are banned in
1881       // C++11 and permitted in C++1y, so ignore them.
1882       continue;
1883 
1884     case Decl::Var:
1885     case Decl::Decomposition: {
1886       // C++1y [dcl.constexpr]p3 allows anything except:
1887       //   a definition of a variable of non-literal type or of static or
1888       //   thread storage duration or [before C++2a] for which no
1889       //   initialization is performed.
1890       const auto *VD = cast<VarDecl>(DclIt);
1891       if (VD->isThisDeclarationADefinition()) {
1892         if (VD->isStaticLocal()) {
1893           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1894             SemaRef.Diag(VD->getLocation(),
1895                          diag::err_constexpr_local_var_static)
1896               << isa<CXXConstructorDecl>(Dcl)
1897               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1898           }
1899           return false;
1900         }
1901         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1902                              diag::err_constexpr_local_var_non_literal_type,
1903                              isa<CXXConstructorDecl>(Dcl)))
1904           return false;
1905         if (!VD->getType()->isDependentType() &&
1906             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1907           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1908             SemaRef.Diag(
1909                 VD->getLocation(),
1910                 SemaRef.getLangOpts().CPlusPlus20
1911                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1912                     : diag::ext_constexpr_local_var_no_init)
1913                 << isa<CXXConstructorDecl>(Dcl);
1914           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1915             return false;
1916           }
1917           continue;
1918         }
1919       }
1920       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1921         SemaRef.Diag(VD->getLocation(),
1922                      SemaRef.getLangOpts().CPlusPlus14
1923                       ? diag::warn_cxx11_compat_constexpr_local_var
1924                       : diag::ext_constexpr_local_var)
1925           << isa<CXXConstructorDecl>(Dcl);
1926       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1927         return false;
1928       }
1929       continue;
1930     }
1931 
1932     case Decl::NamespaceAlias:
1933     case Decl::Function:
1934       // These are disallowed in C++11 and permitted in C++1y. Allow them
1935       // everywhere as an extension.
1936       if (!Cxx1yLoc.isValid())
1937         Cxx1yLoc = DS->getBeginLoc();
1938       continue;
1939 
1940     default:
1941       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1942         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1943             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1944       }
1945       return false;
1946     }
1947   }
1948 
1949   return true;
1950 }
1951 
1952 /// Check that the given field is initialized within a constexpr constructor.
1953 ///
1954 /// \param Dcl The constexpr constructor being checked.
1955 /// \param Field The field being checked. This may be a member of an anonymous
1956 ///        struct or union nested within the class being checked.
1957 /// \param Inits All declarations, including anonymous struct/union members and
1958 ///        indirect members, for which any initialization was provided.
1959 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1960 ///        multiple notes for different members to the same error.
1961 /// \param Kind Whether we're diagnosing a constructor as written or determining
1962 ///        whether the formal requirements are satisfied.
1963 /// \return \c false if we're checking for validity and the constructor does
1964 ///         not satisfy the requirements on a constexpr constructor.
1965 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1966                                           const FunctionDecl *Dcl,
1967                                           FieldDecl *Field,
1968                                           llvm::SmallSet<Decl*, 16> &Inits,
1969                                           bool &Diagnosed,
1970                                           Sema::CheckConstexprKind Kind) {
1971   // In C++20 onwards, there's nothing to check for validity.
1972   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1973       SemaRef.getLangOpts().CPlusPlus20)
1974     return true;
1975 
1976   if (Field->isInvalidDecl())
1977     return true;
1978 
1979   if (Field->isUnnamedBitfield())
1980     return true;
1981 
1982   // Anonymous unions with no variant members and empty anonymous structs do not
1983   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1984   // indirect fields don't need initializing.
1985   if (Field->isAnonymousStructOrUnion() &&
1986       (Field->getType()->isUnionType()
1987            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1988            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1989     return true;
1990 
1991   if (!Inits.count(Field)) {
1992     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1993       if (!Diagnosed) {
1994         SemaRef.Diag(Dcl->getLocation(),
1995                      SemaRef.getLangOpts().CPlusPlus20
1996                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1997                          : diag::ext_constexpr_ctor_missing_init);
1998         Diagnosed = true;
1999       }
2000       SemaRef.Diag(Field->getLocation(),
2001                    diag::note_constexpr_ctor_missing_init);
2002     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2003       return false;
2004     }
2005   } else if (Field->isAnonymousStructOrUnion()) {
2006     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2007     for (auto *I : RD->fields())
2008       // If an anonymous union contains an anonymous struct of which any member
2009       // is initialized, all members must be initialized.
2010       if (!RD->isUnion() || Inits.count(I))
2011         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2012                                            Kind))
2013           return false;
2014   }
2015   return true;
2016 }
2017 
2018 /// Check the provided statement is allowed in a constexpr function
2019 /// definition.
2020 static bool
2021 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2022                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2023                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2024                            Sema::CheckConstexprKind Kind) {
2025   // - its function-body shall be [...] a compound-statement that contains only
2026   switch (S->getStmtClass()) {
2027   case Stmt::NullStmtClass:
2028     //   - null statements,
2029     return true;
2030 
2031   case Stmt::DeclStmtClass:
2032     //   - static_assert-declarations
2033     //   - using-declarations,
2034     //   - using-directives,
2035     //   - typedef declarations and alias-declarations that do not define
2036     //     classes or enumerations,
2037     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2038       return false;
2039     return true;
2040 
2041   case Stmt::ReturnStmtClass:
2042     //   - and exactly one return statement;
2043     if (isa<CXXConstructorDecl>(Dcl)) {
2044       // C++1y allows return statements in constexpr constructors.
2045       if (!Cxx1yLoc.isValid())
2046         Cxx1yLoc = S->getBeginLoc();
2047       return true;
2048     }
2049 
2050     ReturnStmts.push_back(S->getBeginLoc());
2051     return true;
2052 
2053   case Stmt::AttributedStmtClass:
2054     // Attributes on a statement don't affect its formal kind and hence don't
2055     // affect its validity in a constexpr function.
2056     return CheckConstexprFunctionStmt(SemaRef, Dcl,
2057                                       cast<AttributedStmt>(S)->getSubStmt(),
2058                                       ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind);
2059 
2060   case Stmt::CompoundStmtClass: {
2061     // C++1y allows compound-statements.
2062     if (!Cxx1yLoc.isValid())
2063       Cxx1yLoc = S->getBeginLoc();
2064 
2065     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2066     for (auto *BodyIt : CompStmt->body()) {
2067       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2068                                       Cxx1yLoc, Cxx2aLoc, Kind))
2069         return false;
2070     }
2071     return true;
2072   }
2073 
2074   case Stmt::IfStmtClass: {
2075     // C++1y allows if-statements.
2076     if (!Cxx1yLoc.isValid())
2077       Cxx1yLoc = S->getBeginLoc();
2078 
2079     IfStmt *If = cast<IfStmt>(S);
2080     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2081                                     Cxx1yLoc, Cxx2aLoc, Kind))
2082       return false;
2083     if (If->getElse() &&
2084         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2085                                     Cxx1yLoc, Cxx2aLoc, Kind))
2086       return false;
2087     return true;
2088   }
2089 
2090   case Stmt::WhileStmtClass:
2091   case Stmt::DoStmtClass:
2092   case Stmt::ForStmtClass:
2093   case Stmt::CXXForRangeStmtClass:
2094   case Stmt::ContinueStmtClass:
2095     // C++1y allows all of these. We don't allow them as extensions in C++11,
2096     // because they don't make sense without variable mutation.
2097     if (!SemaRef.getLangOpts().CPlusPlus14)
2098       break;
2099     if (!Cxx1yLoc.isValid())
2100       Cxx1yLoc = S->getBeginLoc();
2101     for (Stmt *SubStmt : S->children())
2102       if (SubStmt &&
2103           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2104                                       Cxx1yLoc, Cxx2aLoc, Kind))
2105         return false;
2106     return true;
2107 
2108   case Stmt::SwitchStmtClass:
2109   case Stmt::CaseStmtClass:
2110   case Stmt::DefaultStmtClass:
2111   case Stmt::BreakStmtClass:
2112     // C++1y allows switch-statements, and since they don't need variable
2113     // mutation, we can reasonably allow them in C++11 as an extension.
2114     if (!Cxx1yLoc.isValid())
2115       Cxx1yLoc = S->getBeginLoc();
2116     for (Stmt *SubStmt : S->children())
2117       if (SubStmt &&
2118           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2119                                       Cxx1yLoc, Cxx2aLoc, Kind))
2120         return false;
2121     return true;
2122 
2123   case Stmt::GCCAsmStmtClass:
2124   case Stmt::MSAsmStmtClass:
2125     // C++2a allows inline assembly statements.
2126   case Stmt::CXXTryStmtClass:
2127     if (Cxx2aLoc.isInvalid())
2128       Cxx2aLoc = S->getBeginLoc();
2129     for (Stmt *SubStmt : S->children()) {
2130       if (SubStmt &&
2131           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2132                                       Cxx1yLoc, Cxx2aLoc, Kind))
2133         return false;
2134     }
2135     return true;
2136 
2137   case Stmt::CXXCatchStmtClass:
2138     // Do not bother checking the language mode (already covered by the
2139     // try block check).
2140     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2141                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2142                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2143       return false;
2144     return true;
2145 
2146   default:
2147     if (!isa<Expr>(S))
2148       break;
2149 
2150     // C++1y allows expression-statements.
2151     if (!Cxx1yLoc.isValid())
2152       Cxx1yLoc = S->getBeginLoc();
2153     return true;
2154   }
2155 
2156   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2157     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2158         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2159   }
2160   return false;
2161 }
2162 
2163 /// Check the body for the given constexpr function declaration only contains
2164 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2165 ///
2166 /// \return true if the body is OK, false if we have found or diagnosed a
2167 /// problem.
2168 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2169                                        Stmt *Body,
2170                                        Sema::CheckConstexprKind Kind) {
2171   SmallVector<SourceLocation, 4> ReturnStmts;
2172 
2173   if (isa<CXXTryStmt>(Body)) {
2174     // C++11 [dcl.constexpr]p3:
2175     //  The definition of a constexpr function shall satisfy the following
2176     //  constraints: [...]
2177     // - its function-body shall be = delete, = default, or a
2178     //   compound-statement
2179     //
2180     // C++11 [dcl.constexpr]p4:
2181     //  In the definition of a constexpr constructor, [...]
2182     // - its function-body shall not be a function-try-block;
2183     //
2184     // This restriction is lifted in C++2a, as long as inner statements also
2185     // apply the general constexpr rules.
2186     switch (Kind) {
2187     case Sema::CheckConstexprKind::CheckValid:
2188       if (!SemaRef.getLangOpts().CPlusPlus20)
2189         return false;
2190       break;
2191 
2192     case Sema::CheckConstexprKind::Diagnose:
2193       SemaRef.Diag(Body->getBeginLoc(),
2194            !SemaRef.getLangOpts().CPlusPlus20
2195                ? diag::ext_constexpr_function_try_block_cxx20
2196                : diag::warn_cxx17_compat_constexpr_function_try_block)
2197           << isa<CXXConstructorDecl>(Dcl);
2198       break;
2199     }
2200   }
2201 
2202   // - its function-body shall be [...] a compound-statement that contains only
2203   //   [... list of cases ...]
2204   //
2205   // Note that walking the children here is enough to properly check for
2206   // CompoundStmt and CXXTryStmt body.
2207   SourceLocation Cxx1yLoc, Cxx2aLoc;
2208   for (Stmt *SubStmt : Body->children()) {
2209     if (SubStmt &&
2210         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2211                                     Cxx1yLoc, Cxx2aLoc, Kind))
2212       return false;
2213   }
2214 
2215   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2216     // If this is only valid as an extension, report that we don't satisfy the
2217     // constraints of the current language.
2218     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2219         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2220       return false;
2221   } else if (Cxx2aLoc.isValid()) {
2222     SemaRef.Diag(Cxx2aLoc,
2223          SemaRef.getLangOpts().CPlusPlus20
2224            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2225            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2226       << isa<CXXConstructorDecl>(Dcl);
2227   } else if (Cxx1yLoc.isValid()) {
2228     SemaRef.Diag(Cxx1yLoc,
2229          SemaRef.getLangOpts().CPlusPlus14
2230            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2231            : diag::ext_constexpr_body_invalid_stmt)
2232       << isa<CXXConstructorDecl>(Dcl);
2233   }
2234 
2235   if (const CXXConstructorDecl *Constructor
2236         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2237     const CXXRecordDecl *RD = Constructor->getParent();
2238     // DR1359:
2239     // - every non-variant non-static data member and base class sub-object
2240     //   shall be initialized;
2241     // DR1460:
2242     // - if the class is a union having variant members, exactly one of them
2243     //   shall be initialized;
2244     if (RD->isUnion()) {
2245       if (Constructor->getNumCtorInitializers() == 0 &&
2246           RD->hasVariantMembers()) {
2247         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2248           SemaRef.Diag(
2249               Dcl->getLocation(),
2250               SemaRef.getLangOpts().CPlusPlus20
2251                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2252                   : diag::ext_constexpr_union_ctor_no_init);
2253         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2254           return false;
2255         }
2256       }
2257     } else if (!Constructor->isDependentContext() &&
2258                !Constructor->isDelegatingConstructor()) {
2259       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2260 
2261       // Skip detailed checking if we have enough initializers, and we would
2262       // allow at most one initializer per member.
2263       bool AnyAnonStructUnionMembers = false;
2264       unsigned Fields = 0;
2265       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2266            E = RD->field_end(); I != E; ++I, ++Fields) {
2267         if (I->isAnonymousStructOrUnion()) {
2268           AnyAnonStructUnionMembers = true;
2269           break;
2270         }
2271       }
2272       // DR1460:
2273       // - if the class is a union-like class, but is not a union, for each of
2274       //   its anonymous union members having variant members, exactly one of
2275       //   them shall be initialized;
2276       if (AnyAnonStructUnionMembers ||
2277           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2278         // Check initialization of non-static data members. Base classes are
2279         // always initialized so do not need to be checked. Dependent bases
2280         // might not have initializers in the member initializer list.
2281         llvm::SmallSet<Decl*, 16> Inits;
2282         for (const auto *I: Constructor->inits()) {
2283           if (FieldDecl *FD = I->getMember())
2284             Inits.insert(FD);
2285           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2286             Inits.insert(ID->chain_begin(), ID->chain_end());
2287         }
2288 
2289         bool Diagnosed = false;
2290         for (auto *I : RD->fields())
2291           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2292                                              Kind))
2293             return false;
2294       }
2295     }
2296   } else {
2297     if (ReturnStmts.empty()) {
2298       // C++1y doesn't require constexpr functions to contain a 'return'
2299       // statement. We still do, unless the return type might be void, because
2300       // otherwise if there's no return statement, the function cannot
2301       // be used in a core constant expression.
2302       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2303                 (Dcl->getReturnType()->isVoidType() ||
2304                  Dcl->getReturnType()->isDependentType());
2305       switch (Kind) {
2306       case Sema::CheckConstexprKind::Diagnose:
2307         SemaRef.Diag(Dcl->getLocation(),
2308                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2309                         : diag::err_constexpr_body_no_return)
2310             << Dcl->isConsteval();
2311         if (!OK)
2312           return false;
2313         break;
2314 
2315       case Sema::CheckConstexprKind::CheckValid:
2316         // The formal requirements don't include this rule in C++14, even
2317         // though the "must be able to produce a constant expression" rules
2318         // still imply it in some cases.
2319         if (!SemaRef.getLangOpts().CPlusPlus14)
2320           return false;
2321         break;
2322       }
2323     } else if (ReturnStmts.size() > 1) {
2324       switch (Kind) {
2325       case Sema::CheckConstexprKind::Diagnose:
2326         SemaRef.Diag(
2327             ReturnStmts.back(),
2328             SemaRef.getLangOpts().CPlusPlus14
2329                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2330                 : diag::ext_constexpr_body_multiple_return);
2331         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2332           SemaRef.Diag(ReturnStmts[I],
2333                        diag::note_constexpr_body_previous_return);
2334         break;
2335 
2336       case Sema::CheckConstexprKind::CheckValid:
2337         if (!SemaRef.getLangOpts().CPlusPlus14)
2338           return false;
2339         break;
2340       }
2341     }
2342   }
2343 
2344   // C++11 [dcl.constexpr]p5:
2345   //   if no function argument values exist such that the function invocation
2346   //   substitution would produce a constant expression, the program is
2347   //   ill-formed; no diagnostic required.
2348   // C++11 [dcl.constexpr]p3:
2349   //   - every constructor call and implicit conversion used in initializing the
2350   //     return value shall be one of those allowed in a constant expression.
2351   // C++11 [dcl.constexpr]p4:
2352   //   - every constructor involved in initializing non-static data members and
2353   //     base class sub-objects shall be a constexpr constructor.
2354   //
2355   // Note that this rule is distinct from the "requirements for a constexpr
2356   // function", so is not checked in CheckValid mode.
2357   SmallVector<PartialDiagnosticAt, 8> Diags;
2358   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2359       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2360     SemaRef.Diag(Dcl->getLocation(),
2361                  diag::ext_constexpr_function_never_constant_expr)
2362         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2363     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2364       SemaRef.Diag(Diags[I].first, Diags[I].second);
2365     // Don't return false here: we allow this for compatibility in
2366     // system headers.
2367   }
2368 
2369   return true;
2370 }
2371 
2372 /// Get the class that is directly named by the current context. This is the
2373 /// class for which an unqualified-id in this scope could name a constructor
2374 /// or destructor.
2375 ///
2376 /// If the scope specifier denotes a class, this will be that class.
2377 /// If the scope specifier is empty, this will be the class whose
2378 /// member-specification we are currently within. Otherwise, there
2379 /// is no such class.
2380 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2381   assert(getLangOpts().CPlusPlus && "No class names in C!");
2382 
2383   if (SS && SS->isInvalid())
2384     return nullptr;
2385 
2386   if (SS && SS->isNotEmpty()) {
2387     DeclContext *DC = computeDeclContext(*SS, true);
2388     return dyn_cast_or_null<CXXRecordDecl>(DC);
2389   }
2390 
2391   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2392 }
2393 
2394 /// isCurrentClassName - Determine whether the identifier II is the
2395 /// name of the class type currently being defined. In the case of
2396 /// nested classes, this will only return true if II is the name of
2397 /// the innermost class.
2398 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2399                               const CXXScopeSpec *SS) {
2400   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2401   return CurDecl && &II == CurDecl->getIdentifier();
2402 }
2403 
2404 /// Determine whether the identifier II is a typo for the name of
2405 /// the class type currently being defined. If so, update it to the identifier
2406 /// that should have been used.
2407 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2408   assert(getLangOpts().CPlusPlus && "No class names in C!");
2409 
2410   if (!getLangOpts().SpellChecking)
2411     return false;
2412 
2413   CXXRecordDecl *CurDecl;
2414   if (SS && SS->isSet() && !SS->isInvalid()) {
2415     DeclContext *DC = computeDeclContext(*SS, true);
2416     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2417   } else
2418     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2419 
2420   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2421       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2422           < II->getLength()) {
2423     II = CurDecl->getIdentifier();
2424     return true;
2425   }
2426 
2427   return false;
2428 }
2429 
2430 /// Determine whether the given class is a base class of the given
2431 /// class, including looking at dependent bases.
2432 static bool findCircularInheritance(const CXXRecordDecl *Class,
2433                                     const CXXRecordDecl *Current) {
2434   SmallVector<const CXXRecordDecl*, 8> Queue;
2435 
2436   Class = Class->getCanonicalDecl();
2437   while (true) {
2438     for (const auto &I : Current->bases()) {
2439       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2440       if (!Base)
2441         continue;
2442 
2443       Base = Base->getDefinition();
2444       if (!Base)
2445         continue;
2446 
2447       if (Base->getCanonicalDecl() == Class)
2448         return true;
2449 
2450       Queue.push_back(Base);
2451     }
2452 
2453     if (Queue.empty())
2454       return false;
2455 
2456     Current = Queue.pop_back_val();
2457   }
2458 
2459   return false;
2460 }
2461 
2462 /// Check the validity of a C++ base class specifier.
2463 ///
2464 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2465 /// and returns NULL otherwise.
2466 CXXBaseSpecifier *
2467 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2468                          SourceRange SpecifierRange,
2469                          bool Virtual, AccessSpecifier Access,
2470                          TypeSourceInfo *TInfo,
2471                          SourceLocation EllipsisLoc) {
2472   QualType BaseType = TInfo->getType();
2473   if (BaseType->containsErrors()) {
2474     // Already emitted a diagnostic when parsing the error type.
2475     return nullptr;
2476   }
2477   // C++ [class.union]p1:
2478   //   A union shall not have base classes.
2479   if (Class->isUnion()) {
2480     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2481       << SpecifierRange;
2482     return nullptr;
2483   }
2484 
2485   if (EllipsisLoc.isValid() &&
2486       !TInfo->getType()->containsUnexpandedParameterPack()) {
2487     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2488       << TInfo->getTypeLoc().getSourceRange();
2489     EllipsisLoc = SourceLocation();
2490   }
2491 
2492   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2493 
2494   if (BaseType->isDependentType()) {
2495     // Make sure that we don't have circular inheritance among our dependent
2496     // bases. For non-dependent bases, the check for completeness below handles
2497     // this.
2498     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2499       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2500           ((BaseDecl = BaseDecl->getDefinition()) &&
2501            findCircularInheritance(Class, BaseDecl))) {
2502         Diag(BaseLoc, diag::err_circular_inheritance)
2503           << BaseType << Context.getTypeDeclType(Class);
2504 
2505         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2506           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2507             << BaseType;
2508 
2509         return nullptr;
2510       }
2511     }
2512 
2513     // Make sure that we don't make an ill-formed AST where the type of the
2514     // Class is non-dependent and its attached base class specifier is an
2515     // dependent type, which violates invariants in many clang code paths (e.g.
2516     // constexpr evaluator). If this case happens (in errory-recovery mode), we
2517     // explicitly mark the Class decl invalid. The diagnostic was already
2518     // emitted.
2519     if (!Class->getTypeForDecl()->isDependentType())
2520       Class->setInvalidDecl();
2521     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2522                                           Class->getTagKind() == TTK_Class,
2523                                           Access, TInfo, EllipsisLoc);
2524   }
2525 
2526   // Base specifiers must be record types.
2527   if (!BaseType->isRecordType()) {
2528     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2529     return nullptr;
2530   }
2531 
2532   // C++ [class.union]p1:
2533   //   A union shall not be used as a base class.
2534   if (BaseType->isUnionType()) {
2535     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2536     return nullptr;
2537   }
2538 
2539   // For the MS ABI, propagate DLL attributes to base class templates.
2540   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2541     if (Attr *ClassAttr = getDLLAttr(Class)) {
2542       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2543               BaseType->getAsCXXRecordDecl())) {
2544         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2545                                             BaseLoc);
2546       }
2547     }
2548   }
2549 
2550   // C++ [class.derived]p2:
2551   //   The class-name in a base-specifier shall not be an incompletely
2552   //   defined class.
2553   if (RequireCompleteType(BaseLoc, BaseType,
2554                           diag::err_incomplete_base_class, SpecifierRange)) {
2555     Class->setInvalidDecl();
2556     return nullptr;
2557   }
2558 
2559   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2560   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2561   assert(BaseDecl && "Record type has no declaration");
2562   BaseDecl = BaseDecl->getDefinition();
2563   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2564   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2565   assert(CXXBaseDecl && "Base type is not a C++ type");
2566 
2567   // Microsoft docs say:
2568   // "If a base-class has a code_seg attribute, derived classes must have the
2569   // same attribute."
2570   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2571   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2572   if ((DerivedCSA || BaseCSA) &&
2573       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2574     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2575     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2576       << CXXBaseDecl;
2577     return nullptr;
2578   }
2579 
2580   // A class which contains a flexible array member is not suitable for use as a
2581   // base class:
2582   //   - If the layout determines that a base comes before another base,
2583   //     the flexible array member would index into the subsequent base.
2584   //   - If the layout determines that base comes before the derived class,
2585   //     the flexible array member would index into the derived class.
2586   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2587     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2588       << CXXBaseDecl->getDeclName();
2589     return nullptr;
2590   }
2591 
2592   // C++ [class]p3:
2593   //   If a class is marked final and it appears as a base-type-specifier in
2594   //   base-clause, the program is ill-formed.
2595   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2596     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2597       << CXXBaseDecl->getDeclName()
2598       << FA->isSpelledAsSealed();
2599     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2600         << CXXBaseDecl->getDeclName() << FA->getRange();
2601     return nullptr;
2602   }
2603 
2604   if (BaseDecl->isInvalidDecl())
2605     Class->setInvalidDecl();
2606 
2607   // Create the base specifier.
2608   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2609                                         Class->getTagKind() == TTK_Class,
2610                                         Access, TInfo, EllipsisLoc);
2611 }
2612 
2613 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2614 /// one entry in the base class list of a class specifier, for
2615 /// example:
2616 ///    class foo : public bar, virtual private baz {
2617 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2618 BaseResult
2619 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2620                          ParsedAttributes &Attributes,
2621                          bool Virtual, AccessSpecifier Access,
2622                          ParsedType basetype, SourceLocation BaseLoc,
2623                          SourceLocation EllipsisLoc) {
2624   if (!classdecl)
2625     return true;
2626 
2627   AdjustDeclIfTemplate(classdecl);
2628   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2629   if (!Class)
2630     return true;
2631 
2632   // We haven't yet attached the base specifiers.
2633   Class->setIsParsingBaseSpecifiers();
2634 
2635   // We do not support any C++11 attributes on base-specifiers yet.
2636   // Diagnose any attributes we see.
2637   for (const ParsedAttr &AL : Attributes) {
2638     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2639       continue;
2640     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2641                           ? (unsigned)diag::warn_unknown_attribute_ignored
2642                           : (unsigned)diag::err_base_specifier_attribute)
2643         << AL << AL.getRange();
2644   }
2645 
2646   TypeSourceInfo *TInfo = nullptr;
2647   GetTypeFromParser(basetype, &TInfo);
2648 
2649   if (EllipsisLoc.isInvalid() &&
2650       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2651                                       UPPC_BaseType))
2652     return true;
2653 
2654   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2655                                                       Virtual, Access, TInfo,
2656                                                       EllipsisLoc))
2657     return BaseSpec;
2658   else
2659     Class->setInvalidDecl();
2660 
2661   return true;
2662 }
2663 
2664 /// Use small set to collect indirect bases.  As this is only used
2665 /// locally, there's no need to abstract the small size parameter.
2666 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2667 
2668 /// Recursively add the bases of Type.  Don't add Type itself.
2669 static void
2670 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2671                   const QualType &Type)
2672 {
2673   // Even though the incoming type is a base, it might not be
2674   // a class -- it could be a template parm, for instance.
2675   if (auto Rec = Type->getAs<RecordType>()) {
2676     auto Decl = Rec->getAsCXXRecordDecl();
2677 
2678     // Iterate over its bases.
2679     for (const auto &BaseSpec : Decl->bases()) {
2680       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2681         .getUnqualifiedType();
2682       if (Set.insert(Base).second)
2683         // If we've not already seen it, recurse.
2684         NoteIndirectBases(Context, Set, Base);
2685     }
2686   }
2687 }
2688 
2689 /// Performs the actual work of attaching the given base class
2690 /// specifiers to a C++ class.
2691 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2692                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2693  if (Bases.empty())
2694     return false;
2695 
2696   // Used to keep track of which base types we have already seen, so
2697   // that we can properly diagnose redundant direct base types. Note
2698   // that the key is always the unqualified canonical type of the base
2699   // class.
2700   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2701 
2702   // Used to track indirect bases so we can see if a direct base is
2703   // ambiguous.
2704   IndirectBaseSet IndirectBaseTypes;
2705 
2706   // Copy non-redundant base specifiers into permanent storage.
2707   unsigned NumGoodBases = 0;
2708   bool Invalid = false;
2709   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2710     QualType NewBaseType
2711       = Context.getCanonicalType(Bases[idx]->getType());
2712     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2713 
2714     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2715     if (KnownBase) {
2716       // C++ [class.mi]p3:
2717       //   A class shall not be specified as a direct base class of a
2718       //   derived class more than once.
2719       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2720           << KnownBase->getType() << Bases[idx]->getSourceRange();
2721 
2722       // Delete the duplicate base class specifier; we're going to
2723       // overwrite its pointer later.
2724       Context.Deallocate(Bases[idx]);
2725 
2726       Invalid = true;
2727     } else {
2728       // Okay, add this new base class.
2729       KnownBase = Bases[idx];
2730       Bases[NumGoodBases++] = Bases[idx];
2731 
2732       if (NewBaseType->isDependentType())
2733         continue;
2734       // Note this base's direct & indirect bases, if there could be ambiguity.
2735       if (Bases.size() > 1)
2736         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2737 
2738       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2739         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2740         if (Class->isInterface() &&
2741               (!RD->isInterfaceLike() ||
2742                KnownBase->getAccessSpecifier() != AS_public)) {
2743           // The Microsoft extension __interface does not permit bases that
2744           // are not themselves public interfaces.
2745           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2746               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2747               << RD->getSourceRange();
2748           Invalid = true;
2749         }
2750         if (RD->hasAttr<WeakAttr>())
2751           Class->addAttr(WeakAttr::CreateImplicit(Context));
2752       }
2753     }
2754   }
2755 
2756   // Attach the remaining base class specifiers to the derived class.
2757   Class->setBases(Bases.data(), NumGoodBases);
2758 
2759   // Check that the only base classes that are duplicate are virtual.
2760   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2761     // Check whether this direct base is inaccessible due to ambiguity.
2762     QualType BaseType = Bases[idx]->getType();
2763 
2764     // Skip all dependent types in templates being used as base specifiers.
2765     // Checks below assume that the base specifier is a CXXRecord.
2766     if (BaseType->isDependentType())
2767       continue;
2768 
2769     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2770       .getUnqualifiedType();
2771 
2772     if (IndirectBaseTypes.count(CanonicalBase)) {
2773       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2774                          /*DetectVirtual=*/true);
2775       bool found
2776         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2777       assert(found);
2778       (void)found;
2779 
2780       if (Paths.isAmbiguous(CanonicalBase))
2781         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2782             << BaseType << getAmbiguousPathsDisplayString(Paths)
2783             << Bases[idx]->getSourceRange();
2784       else
2785         assert(Bases[idx]->isVirtual());
2786     }
2787 
2788     // Delete the base class specifier, since its data has been copied
2789     // into the CXXRecordDecl.
2790     Context.Deallocate(Bases[idx]);
2791   }
2792 
2793   return Invalid;
2794 }
2795 
2796 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2797 /// class, after checking whether there are any duplicate base
2798 /// classes.
2799 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2800                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2801   if (!ClassDecl || Bases.empty())
2802     return;
2803 
2804   AdjustDeclIfTemplate(ClassDecl);
2805   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2806 }
2807 
2808 /// Determine whether the type \p Derived is a C++ class that is
2809 /// derived from the type \p Base.
2810 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2811   if (!getLangOpts().CPlusPlus)
2812     return false;
2813 
2814   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2815   if (!DerivedRD)
2816     return false;
2817 
2818   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2819   if (!BaseRD)
2820     return false;
2821 
2822   // If either the base or the derived type is invalid, don't try to
2823   // check whether one is derived from the other.
2824   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2825     return false;
2826 
2827   // FIXME: In a modules build, do we need the entire path to be visible for us
2828   // to be able to use the inheritance relationship?
2829   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2830     return false;
2831 
2832   return DerivedRD->isDerivedFrom(BaseRD);
2833 }
2834 
2835 /// Determine whether the type \p Derived is a C++ class that is
2836 /// derived from the type \p Base.
2837 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2838                          CXXBasePaths &Paths) {
2839   if (!getLangOpts().CPlusPlus)
2840     return false;
2841 
2842   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2843   if (!DerivedRD)
2844     return false;
2845 
2846   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2847   if (!BaseRD)
2848     return false;
2849 
2850   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2851     return false;
2852 
2853   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2854 }
2855 
2856 static void BuildBasePathArray(const CXXBasePath &Path,
2857                                CXXCastPath &BasePathArray) {
2858   // We first go backward and check if we have a virtual base.
2859   // FIXME: It would be better if CXXBasePath had the base specifier for
2860   // the nearest virtual base.
2861   unsigned Start = 0;
2862   for (unsigned I = Path.size(); I != 0; --I) {
2863     if (Path[I - 1].Base->isVirtual()) {
2864       Start = I - 1;
2865       break;
2866     }
2867   }
2868 
2869   // Now add all bases.
2870   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2871     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2872 }
2873 
2874 
2875 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2876                               CXXCastPath &BasePathArray) {
2877   assert(BasePathArray.empty() && "Base path array must be empty!");
2878   assert(Paths.isRecordingPaths() && "Must record paths!");
2879   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2880 }
2881 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2882 /// conversion (where Derived and Base are class types) is
2883 /// well-formed, meaning that the conversion is unambiguous (and
2884 /// that all of the base classes are accessible). Returns true
2885 /// and emits a diagnostic if the code is ill-formed, returns false
2886 /// otherwise. Loc is the location where this routine should point to
2887 /// if there is an error, and Range is the source range to highlight
2888 /// if there is an error.
2889 ///
2890 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2891 /// diagnostic for the respective type of error will be suppressed, but the
2892 /// check for ill-formed code will still be performed.
2893 bool
2894 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2895                                    unsigned InaccessibleBaseID,
2896                                    unsigned AmbiguousBaseConvID,
2897                                    SourceLocation Loc, SourceRange Range,
2898                                    DeclarationName Name,
2899                                    CXXCastPath *BasePath,
2900                                    bool IgnoreAccess) {
2901   // First, determine whether the path from Derived to Base is
2902   // ambiguous. This is slightly more expensive than checking whether
2903   // the Derived to Base conversion exists, because here we need to
2904   // explore multiple paths to determine if there is an ambiguity.
2905   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2906                      /*DetectVirtual=*/false);
2907   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2908   if (!DerivationOkay)
2909     return true;
2910 
2911   const CXXBasePath *Path = nullptr;
2912   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2913     Path = &Paths.front();
2914 
2915   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2916   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2917   // user to access such bases.
2918   if (!Path && getLangOpts().MSVCCompat) {
2919     for (const CXXBasePath &PossiblePath : Paths) {
2920       if (PossiblePath.size() == 1) {
2921         Path = &PossiblePath;
2922         if (AmbiguousBaseConvID)
2923           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2924               << Base << Derived << Range;
2925         break;
2926       }
2927     }
2928   }
2929 
2930   if (Path) {
2931     if (!IgnoreAccess) {
2932       // Check that the base class can be accessed.
2933       switch (
2934           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2935       case AR_inaccessible:
2936         return true;
2937       case AR_accessible:
2938       case AR_dependent:
2939       case AR_delayed:
2940         break;
2941       }
2942     }
2943 
2944     // Build a base path if necessary.
2945     if (BasePath)
2946       ::BuildBasePathArray(*Path, *BasePath);
2947     return false;
2948   }
2949 
2950   if (AmbiguousBaseConvID) {
2951     // We know that the derived-to-base conversion is ambiguous, and
2952     // we're going to produce a diagnostic. Perform the derived-to-base
2953     // search just one more time to compute all of the possible paths so
2954     // that we can print them out. This is more expensive than any of
2955     // the previous derived-to-base checks we've done, but at this point
2956     // performance isn't as much of an issue.
2957     Paths.clear();
2958     Paths.setRecordingPaths(true);
2959     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2960     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2961     (void)StillOkay;
2962 
2963     // Build up a textual representation of the ambiguous paths, e.g.,
2964     // D -> B -> A, that will be used to illustrate the ambiguous
2965     // conversions in the diagnostic. We only print one of the paths
2966     // to each base class subobject.
2967     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2968 
2969     Diag(Loc, AmbiguousBaseConvID)
2970     << Derived << Base << PathDisplayStr << Range << Name;
2971   }
2972   return true;
2973 }
2974 
2975 bool
2976 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2977                                    SourceLocation Loc, SourceRange Range,
2978                                    CXXCastPath *BasePath,
2979                                    bool IgnoreAccess) {
2980   return CheckDerivedToBaseConversion(
2981       Derived, Base, diag::err_upcast_to_inaccessible_base,
2982       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2983       BasePath, IgnoreAccess);
2984 }
2985 
2986 
2987 /// Builds a string representing ambiguous paths from a
2988 /// specific derived class to different subobjects of the same base
2989 /// class.
2990 ///
2991 /// This function builds a string that can be used in error messages
2992 /// to show the different paths that one can take through the
2993 /// inheritance hierarchy to go from the derived class to different
2994 /// subobjects of a base class. The result looks something like this:
2995 /// @code
2996 /// struct D -> struct B -> struct A
2997 /// struct D -> struct C -> struct A
2998 /// @endcode
2999 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3000   std::string PathDisplayStr;
3001   std::set<unsigned> DisplayedPaths;
3002   for (CXXBasePaths::paths_iterator Path = Paths.begin();
3003        Path != Paths.end(); ++Path) {
3004     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3005       // We haven't displayed a path to this particular base
3006       // class subobject yet.
3007       PathDisplayStr += "\n    ";
3008       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3009       for (CXXBasePath::const_iterator Element = Path->begin();
3010            Element != Path->end(); ++Element)
3011         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3012     }
3013   }
3014 
3015   return PathDisplayStr;
3016 }
3017 
3018 //===----------------------------------------------------------------------===//
3019 // C++ class member Handling
3020 //===----------------------------------------------------------------------===//
3021 
3022 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3023 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3024                                 SourceLocation ColonLoc,
3025                                 const ParsedAttributesView &Attrs) {
3026   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3027   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3028                                                   ASLoc, ColonLoc);
3029   CurContext->addHiddenDecl(ASDecl);
3030   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3031 }
3032 
3033 /// CheckOverrideControl - Check C++11 override control semantics.
3034 void Sema::CheckOverrideControl(NamedDecl *D) {
3035   if (D->isInvalidDecl())
3036     return;
3037 
3038   // We only care about "override" and "final" declarations.
3039   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3040     return;
3041 
3042   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3043 
3044   // We can't check dependent instance methods.
3045   if (MD && MD->isInstance() &&
3046       (MD->getParent()->hasAnyDependentBases() ||
3047        MD->getType()->isDependentType()))
3048     return;
3049 
3050   if (MD && !MD->isVirtual()) {
3051     // If we have a non-virtual method, check if if hides a virtual method.
3052     // (In that case, it's most likely the method has the wrong type.)
3053     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3054     FindHiddenVirtualMethods(MD, OverloadedMethods);
3055 
3056     if (!OverloadedMethods.empty()) {
3057       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3058         Diag(OA->getLocation(),
3059              diag::override_keyword_hides_virtual_member_function)
3060           << "override" << (OverloadedMethods.size() > 1);
3061       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3062         Diag(FA->getLocation(),
3063              diag::override_keyword_hides_virtual_member_function)
3064           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3065           << (OverloadedMethods.size() > 1);
3066       }
3067       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3068       MD->setInvalidDecl();
3069       return;
3070     }
3071     // Fall through into the general case diagnostic.
3072     // FIXME: We might want to attempt typo correction here.
3073   }
3074 
3075   if (!MD || !MD->isVirtual()) {
3076     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3077       Diag(OA->getLocation(),
3078            diag::override_keyword_only_allowed_on_virtual_member_functions)
3079         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3080       D->dropAttr<OverrideAttr>();
3081     }
3082     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3083       Diag(FA->getLocation(),
3084            diag::override_keyword_only_allowed_on_virtual_member_functions)
3085         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3086         << FixItHint::CreateRemoval(FA->getLocation());
3087       D->dropAttr<FinalAttr>();
3088     }
3089     return;
3090   }
3091 
3092   // C++11 [class.virtual]p5:
3093   //   If a function is marked with the virt-specifier override and
3094   //   does not override a member function of a base class, the program is
3095   //   ill-formed.
3096   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3097   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3098     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3099       << MD->getDeclName();
3100 }
3101 
3102 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3103   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3104     return;
3105   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3106   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3107     return;
3108 
3109   SourceLocation Loc = MD->getLocation();
3110   SourceLocation SpellingLoc = Loc;
3111   if (getSourceManager().isMacroArgExpansion(Loc))
3112     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3113   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3114   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3115       return;
3116 
3117   if (MD->size_overridden_methods() > 0) {
3118     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3119       unsigned DiagID =
3120           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3121               ? DiagInconsistent
3122               : DiagSuggest;
3123       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3124       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3125       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3126     };
3127     if (isa<CXXDestructorDecl>(MD))
3128       EmitDiag(
3129           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3130           diag::warn_suggest_destructor_marked_not_override_overriding);
3131     else
3132       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3133                diag::warn_suggest_function_marked_not_override_overriding);
3134   }
3135 }
3136 
3137 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3138 /// function overrides a virtual member function marked 'final', according to
3139 /// C++11 [class.virtual]p4.
3140 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3141                                                   const CXXMethodDecl *Old) {
3142   FinalAttr *FA = Old->getAttr<FinalAttr>();
3143   if (!FA)
3144     return false;
3145 
3146   Diag(New->getLocation(), diag::err_final_function_overridden)
3147     << New->getDeclName()
3148     << FA->isSpelledAsSealed();
3149   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3150   return true;
3151 }
3152 
3153 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3154   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3155   // FIXME: Destruction of ObjC lifetime types has side-effects.
3156   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3157     return !RD->isCompleteDefinition() ||
3158            !RD->hasTrivialDefaultConstructor() ||
3159            !RD->hasTrivialDestructor();
3160   return false;
3161 }
3162 
3163 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3164   ParsedAttributesView::const_iterator Itr =
3165       llvm::find_if(list, [](const ParsedAttr &AL) {
3166         return AL.isDeclspecPropertyAttribute();
3167       });
3168   if (Itr != list.end())
3169     return &*Itr;
3170   return nullptr;
3171 }
3172 
3173 // Check if there is a field shadowing.
3174 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3175                                       DeclarationName FieldName,
3176                                       const CXXRecordDecl *RD,
3177                                       bool DeclIsField) {
3178   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3179     return;
3180 
3181   // To record a shadowed field in a base
3182   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3183   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3184                            CXXBasePath &Path) {
3185     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3186     // Record an ambiguous path directly
3187     if (Bases.find(Base) != Bases.end())
3188       return true;
3189     for (const auto Field : Base->lookup(FieldName)) {
3190       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3191           Field->getAccess() != AS_private) {
3192         assert(Field->getAccess() != AS_none);
3193         assert(Bases.find(Base) == Bases.end());
3194         Bases[Base] = Field;
3195         return true;
3196       }
3197     }
3198     return false;
3199   };
3200 
3201   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3202                      /*DetectVirtual=*/true);
3203   if (!RD->lookupInBases(FieldShadowed, Paths))
3204     return;
3205 
3206   for (const auto &P : Paths) {
3207     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3208     auto It = Bases.find(Base);
3209     // Skip duplicated bases
3210     if (It == Bases.end())
3211       continue;
3212     auto BaseField = It->second;
3213     assert(BaseField->getAccess() != AS_private);
3214     if (AS_none !=
3215         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3216       Diag(Loc, diag::warn_shadow_field)
3217         << FieldName << RD << Base << DeclIsField;
3218       Diag(BaseField->getLocation(), diag::note_shadow_field);
3219       Bases.erase(It);
3220     }
3221   }
3222 }
3223 
3224 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3225 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3226 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3227 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3228 /// present (but parsing it has been deferred).
3229 NamedDecl *
3230 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3231                                MultiTemplateParamsArg TemplateParameterLists,
3232                                Expr *BW, const VirtSpecifiers &VS,
3233                                InClassInitStyle InitStyle) {
3234   const DeclSpec &DS = D.getDeclSpec();
3235   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3236   DeclarationName Name = NameInfo.getName();
3237   SourceLocation Loc = NameInfo.getLoc();
3238 
3239   // For anonymous bitfields, the location should point to the type.
3240   if (Loc.isInvalid())
3241     Loc = D.getBeginLoc();
3242 
3243   Expr *BitWidth = static_cast<Expr*>(BW);
3244 
3245   assert(isa<CXXRecordDecl>(CurContext));
3246   assert(!DS.isFriendSpecified());
3247 
3248   bool isFunc = D.isDeclarationOfFunction();
3249   const ParsedAttr *MSPropertyAttr =
3250       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3251 
3252   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3253     // The Microsoft extension __interface only permits public member functions
3254     // and prohibits constructors, destructors, operators, non-public member
3255     // functions, static methods and data members.
3256     unsigned InvalidDecl;
3257     bool ShowDeclName = true;
3258     if (!isFunc &&
3259         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3260       InvalidDecl = 0;
3261     else if (!isFunc)
3262       InvalidDecl = 1;
3263     else if (AS != AS_public)
3264       InvalidDecl = 2;
3265     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3266       InvalidDecl = 3;
3267     else switch (Name.getNameKind()) {
3268       case DeclarationName::CXXConstructorName:
3269         InvalidDecl = 4;
3270         ShowDeclName = false;
3271         break;
3272 
3273       case DeclarationName::CXXDestructorName:
3274         InvalidDecl = 5;
3275         ShowDeclName = false;
3276         break;
3277 
3278       case DeclarationName::CXXOperatorName:
3279       case DeclarationName::CXXConversionFunctionName:
3280         InvalidDecl = 6;
3281         break;
3282 
3283       default:
3284         InvalidDecl = 0;
3285         break;
3286     }
3287 
3288     if (InvalidDecl) {
3289       if (ShowDeclName)
3290         Diag(Loc, diag::err_invalid_member_in_interface)
3291           << (InvalidDecl-1) << Name;
3292       else
3293         Diag(Loc, diag::err_invalid_member_in_interface)
3294           << (InvalidDecl-1) << "";
3295       return nullptr;
3296     }
3297   }
3298 
3299   // C++ 9.2p6: A member shall not be declared to have automatic storage
3300   // duration (auto, register) or with the extern storage-class-specifier.
3301   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3302   // data members and cannot be applied to names declared const or static,
3303   // and cannot be applied to reference members.
3304   switch (DS.getStorageClassSpec()) {
3305   case DeclSpec::SCS_unspecified:
3306   case DeclSpec::SCS_typedef:
3307   case DeclSpec::SCS_static:
3308     break;
3309   case DeclSpec::SCS_mutable:
3310     if (isFunc) {
3311       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3312 
3313       // FIXME: It would be nicer if the keyword was ignored only for this
3314       // declarator. Otherwise we could get follow-up errors.
3315       D.getMutableDeclSpec().ClearStorageClassSpecs();
3316     }
3317     break;
3318   default:
3319     Diag(DS.getStorageClassSpecLoc(),
3320          diag::err_storageclass_invalid_for_member);
3321     D.getMutableDeclSpec().ClearStorageClassSpecs();
3322     break;
3323   }
3324 
3325   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3326                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3327                       !isFunc);
3328 
3329   if (DS.hasConstexprSpecifier() && isInstField) {
3330     SemaDiagnosticBuilder B =
3331         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3332     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3333     if (InitStyle == ICIS_NoInit) {
3334       B << 0 << 0;
3335       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3336         B << FixItHint::CreateRemoval(ConstexprLoc);
3337       else {
3338         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3339         D.getMutableDeclSpec().ClearConstexprSpec();
3340         const char *PrevSpec;
3341         unsigned DiagID;
3342         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3343             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3344         (void)Failed;
3345         assert(!Failed && "Making a constexpr member const shouldn't fail");
3346       }
3347     } else {
3348       B << 1;
3349       const char *PrevSpec;
3350       unsigned DiagID;
3351       if (D.getMutableDeclSpec().SetStorageClassSpec(
3352           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3353           Context.getPrintingPolicy())) {
3354         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3355                "This is the only DeclSpec that should fail to be applied");
3356         B << 1;
3357       } else {
3358         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3359         isInstField = false;
3360       }
3361     }
3362   }
3363 
3364   NamedDecl *Member;
3365   if (isInstField) {
3366     CXXScopeSpec &SS = D.getCXXScopeSpec();
3367 
3368     // Data members must have identifiers for names.
3369     if (!Name.isIdentifier()) {
3370       Diag(Loc, diag::err_bad_variable_name)
3371         << Name;
3372       return nullptr;
3373     }
3374 
3375     IdentifierInfo *II = Name.getAsIdentifierInfo();
3376 
3377     // Member field could not be with "template" keyword.
3378     // So TemplateParameterLists should be empty in this case.
3379     if (TemplateParameterLists.size()) {
3380       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3381       if (TemplateParams->size()) {
3382         // There is no such thing as a member field template.
3383         Diag(D.getIdentifierLoc(), diag::err_template_member)
3384             << II
3385             << SourceRange(TemplateParams->getTemplateLoc(),
3386                 TemplateParams->getRAngleLoc());
3387       } else {
3388         // There is an extraneous 'template<>' for this member.
3389         Diag(TemplateParams->getTemplateLoc(),
3390             diag::err_template_member_noparams)
3391             << II
3392             << SourceRange(TemplateParams->getTemplateLoc(),
3393                 TemplateParams->getRAngleLoc());
3394       }
3395       return nullptr;
3396     }
3397 
3398     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3399       Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3400           << II
3401           << SourceRange(D.getName().TemplateId->LAngleLoc,
3402                          D.getName().TemplateId->RAngleLoc)
3403           << D.getName().TemplateId->LAngleLoc;
3404     }
3405 
3406     if (SS.isSet() && !SS.isInvalid()) {
3407       // The user provided a superfluous scope specifier inside a class
3408       // definition:
3409       //
3410       // class X {
3411       //   int X::member;
3412       // };
3413       if (DeclContext *DC = computeDeclContext(SS, false))
3414         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3415                                      D.getName().getKind() ==
3416                                          UnqualifiedIdKind::IK_TemplateId);
3417       else
3418         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3419           << Name << SS.getRange();
3420 
3421       SS.clear();
3422     }
3423 
3424     if (MSPropertyAttr) {
3425       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3426                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3427       if (!Member)
3428         return nullptr;
3429       isInstField = false;
3430     } else {
3431       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3432                                 BitWidth, InitStyle, AS);
3433       if (!Member)
3434         return nullptr;
3435     }
3436 
3437     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3438   } else {
3439     Member = HandleDeclarator(S, D, TemplateParameterLists);
3440     if (!Member)
3441       return nullptr;
3442 
3443     // Non-instance-fields can't have a bitfield.
3444     if (BitWidth) {
3445       if (Member->isInvalidDecl()) {
3446         // don't emit another diagnostic.
3447       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3448         // C++ 9.6p3: A bit-field shall not be a static member.
3449         // "static member 'A' cannot be a bit-field"
3450         Diag(Loc, diag::err_static_not_bitfield)
3451           << Name << BitWidth->getSourceRange();
3452       } else if (isa<TypedefDecl>(Member)) {
3453         // "typedef member 'x' cannot be a bit-field"
3454         Diag(Loc, diag::err_typedef_not_bitfield)
3455           << Name << BitWidth->getSourceRange();
3456       } else {
3457         // A function typedef ("typedef int f(); f a;").
3458         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3459         Diag(Loc, diag::err_not_integral_type_bitfield)
3460           << Name << cast<ValueDecl>(Member)->getType()
3461           << BitWidth->getSourceRange();
3462       }
3463 
3464       BitWidth = nullptr;
3465       Member->setInvalidDecl();
3466     }
3467 
3468     NamedDecl *NonTemplateMember = Member;
3469     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3470       NonTemplateMember = FunTmpl->getTemplatedDecl();
3471     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3472       NonTemplateMember = VarTmpl->getTemplatedDecl();
3473 
3474     Member->setAccess(AS);
3475 
3476     // If we have declared a member function template or static data member
3477     // template, set the access of the templated declaration as well.
3478     if (NonTemplateMember != Member)
3479       NonTemplateMember->setAccess(AS);
3480 
3481     // C++ [temp.deduct.guide]p3:
3482     //   A deduction guide [...] for a member class template [shall be
3483     //   declared] with the same access [as the template].
3484     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3485       auto *TD = DG->getDeducedTemplate();
3486       // Access specifiers are only meaningful if both the template and the
3487       // deduction guide are from the same scope.
3488       if (AS != TD->getAccess() &&
3489           TD->getDeclContext()->getRedeclContext()->Equals(
3490               DG->getDeclContext()->getRedeclContext())) {
3491         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3492         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3493             << TD->getAccess();
3494         const AccessSpecDecl *LastAccessSpec = nullptr;
3495         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3496           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3497             LastAccessSpec = AccessSpec;
3498         }
3499         assert(LastAccessSpec && "differing access with no access specifier");
3500         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3501             << AS;
3502       }
3503     }
3504   }
3505 
3506   if (VS.isOverrideSpecified())
3507     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3508                                          AttributeCommonInfo::AS_Keyword));
3509   if (VS.isFinalSpecified())
3510     Member->addAttr(FinalAttr::Create(
3511         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3512         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3513 
3514   if (VS.getLastLocation().isValid()) {
3515     // Update the end location of a method that has a virt-specifiers.
3516     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3517       MD->setRangeEnd(VS.getLastLocation());
3518   }
3519 
3520   CheckOverrideControl(Member);
3521 
3522   assert((Name || isInstField) && "No identifier for non-field ?");
3523 
3524   if (isInstField) {
3525     FieldDecl *FD = cast<FieldDecl>(Member);
3526     FieldCollector->Add(FD);
3527 
3528     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3529       // Remember all explicit private FieldDecls that have a name, no side
3530       // effects and are not part of a dependent type declaration.
3531       if (!FD->isImplicit() && FD->getDeclName() &&
3532           FD->getAccess() == AS_private &&
3533           !FD->hasAttr<UnusedAttr>() &&
3534           !FD->getParent()->isDependentContext() &&
3535           !InitializationHasSideEffects(*FD))
3536         UnusedPrivateFields.insert(FD);
3537     }
3538   }
3539 
3540   return Member;
3541 }
3542 
3543 namespace {
3544   class UninitializedFieldVisitor
3545       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3546     Sema &S;
3547     // List of Decls to generate a warning on.  Also remove Decls that become
3548     // initialized.
3549     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3550     // List of base classes of the record.  Classes are removed after their
3551     // initializers.
3552     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3553     // Vector of decls to be removed from the Decl set prior to visiting the
3554     // nodes.  These Decls may have been initialized in the prior initializer.
3555     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3556     // If non-null, add a note to the warning pointing back to the constructor.
3557     const CXXConstructorDecl *Constructor;
3558     // Variables to hold state when processing an initializer list.  When
3559     // InitList is true, special case initialization of FieldDecls matching
3560     // InitListFieldDecl.
3561     bool InitList;
3562     FieldDecl *InitListFieldDecl;
3563     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3564 
3565   public:
3566     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3567     UninitializedFieldVisitor(Sema &S,
3568                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3569                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3570       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3571         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3572 
3573     // Returns true if the use of ME is not an uninitialized use.
3574     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3575                                          bool CheckReferenceOnly) {
3576       llvm::SmallVector<FieldDecl*, 4> Fields;
3577       bool ReferenceField = false;
3578       while (ME) {
3579         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3580         if (!FD)
3581           return false;
3582         Fields.push_back(FD);
3583         if (FD->getType()->isReferenceType())
3584           ReferenceField = true;
3585         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3586       }
3587 
3588       // Binding a reference to an uninitialized field is not an
3589       // uninitialized use.
3590       if (CheckReferenceOnly && !ReferenceField)
3591         return true;
3592 
3593       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3594       // Discard the first field since it is the field decl that is being
3595       // initialized.
3596       for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3597         UsedFieldIndex.push_back(FD->getFieldIndex());
3598 
3599       for (auto UsedIter = UsedFieldIndex.begin(),
3600                 UsedEnd = UsedFieldIndex.end(),
3601                 OrigIter = InitFieldIndex.begin(),
3602                 OrigEnd = InitFieldIndex.end();
3603            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3604         if (*UsedIter < *OrigIter)
3605           return true;
3606         if (*UsedIter > *OrigIter)
3607           break;
3608       }
3609 
3610       return false;
3611     }
3612 
3613     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3614                           bool AddressOf) {
3615       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3616         return;
3617 
3618       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3619       // or union.
3620       MemberExpr *FieldME = ME;
3621 
3622       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3623 
3624       Expr *Base = ME;
3625       while (MemberExpr *SubME =
3626                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3627 
3628         if (isa<VarDecl>(SubME->getMemberDecl()))
3629           return;
3630 
3631         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3632           if (!FD->isAnonymousStructOrUnion())
3633             FieldME = SubME;
3634 
3635         if (!FieldME->getType().isPODType(S.Context))
3636           AllPODFields = false;
3637 
3638         Base = SubME->getBase();
3639       }
3640 
3641       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3642         Visit(Base);
3643         return;
3644       }
3645 
3646       if (AddressOf && AllPODFields)
3647         return;
3648 
3649       ValueDecl* FoundVD = FieldME->getMemberDecl();
3650 
3651       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3652         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3653           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3654         }
3655 
3656         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3657           QualType T = BaseCast->getType();
3658           if (T->isPointerType() &&
3659               BaseClasses.count(T->getPointeeType())) {
3660             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3661                 << T->getPointeeType() << FoundVD;
3662           }
3663         }
3664       }
3665 
3666       if (!Decls.count(FoundVD))
3667         return;
3668 
3669       const bool IsReference = FoundVD->getType()->isReferenceType();
3670 
3671       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3672         // Special checking for initializer lists.
3673         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3674           return;
3675         }
3676       } else {
3677         // Prevent double warnings on use of unbounded references.
3678         if (CheckReferenceOnly && !IsReference)
3679           return;
3680       }
3681 
3682       unsigned diag = IsReference
3683           ? diag::warn_reference_field_is_uninit
3684           : diag::warn_field_is_uninit;
3685       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3686       if (Constructor)
3687         S.Diag(Constructor->getLocation(),
3688                diag::note_uninit_in_this_constructor)
3689           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3690 
3691     }
3692 
3693     void HandleValue(Expr *E, bool AddressOf) {
3694       E = E->IgnoreParens();
3695 
3696       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3697         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3698                          AddressOf /*AddressOf*/);
3699         return;
3700       }
3701 
3702       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3703         Visit(CO->getCond());
3704         HandleValue(CO->getTrueExpr(), AddressOf);
3705         HandleValue(CO->getFalseExpr(), AddressOf);
3706         return;
3707       }
3708 
3709       if (BinaryConditionalOperator *BCO =
3710               dyn_cast<BinaryConditionalOperator>(E)) {
3711         Visit(BCO->getCond());
3712         HandleValue(BCO->getFalseExpr(), AddressOf);
3713         return;
3714       }
3715 
3716       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3717         HandleValue(OVE->getSourceExpr(), AddressOf);
3718         return;
3719       }
3720 
3721       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3722         switch (BO->getOpcode()) {
3723         default:
3724           break;
3725         case(BO_PtrMemD):
3726         case(BO_PtrMemI):
3727           HandleValue(BO->getLHS(), AddressOf);
3728           Visit(BO->getRHS());
3729           return;
3730         case(BO_Comma):
3731           Visit(BO->getLHS());
3732           HandleValue(BO->getRHS(), AddressOf);
3733           return;
3734         }
3735       }
3736 
3737       Visit(E);
3738     }
3739 
3740     void CheckInitListExpr(InitListExpr *ILE) {
3741       InitFieldIndex.push_back(0);
3742       for (auto Child : ILE->children()) {
3743         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3744           CheckInitListExpr(SubList);
3745         } else {
3746           Visit(Child);
3747         }
3748         ++InitFieldIndex.back();
3749       }
3750       InitFieldIndex.pop_back();
3751     }
3752 
3753     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3754                           FieldDecl *Field, const Type *BaseClass) {
3755       // Remove Decls that may have been initialized in the previous
3756       // initializer.
3757       for (ValueDecl* VD : DeclsToRemove)
3758         Decls.erase(VD);
3759       DeclsToRemove.clear();
3760 
3761       Constructor = FieldConstructor;
3762       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3763 
3764       if (ILE && Field) {
3765         InitList = true;
3766         InitListFieldDecl = Field;
3767         InitFieldIndex.clear();
3768         CheckInitListExpr(ILE);
3769       } else {
3770         InitList = false;
3771         Visit(E);
3772       }
3773 
3774       if (Field)
3775         Decls.erase(Field);
3776       if (BaseClass)
3777         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3778     }
3779 
3780     void VisitMemberExpr(MemberExpr *ME) {
3781       // All uses of unbounded reference fields will warn.
3782       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3783     }
3784 
3785     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3786       if (E->getCastKind() == CK_LValueToRValue) {
3787         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3788         return;
3789       }
3790 
3791       Inherited::VisitImplicitCastExpr(E);
3792     }
3793 
3794     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3795       if (E->getConstructor()->isCopyConstructor()) {
3796         Expr *ArgExpr = E->getArg(0);
3797         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3798           if (ILE->getNumInits() == 1)
3799             ArgExpr = ILE->getInit(0);
3800         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3801           if (ICE->getCastKind() == CK_NoOp)
3802             ArgExpr = ICE->getSubExpr();
3803         HandleValue(ArgExpr, false /*AddressOf*/);
3804         return;
3805       }
3806       Inherited::VisitCXXConstructExpr(E);
3807     }
3808 
3809     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3810       Expr *Callee = E->getCallee();
3811       if (isa<MemberExpr>(Callee)) {
3812         HandleValue(Callee, false /*AddressOf*/);
3813         for (auto Arg : E->arguments())
3814           Visit(Arg);
3815         return;
3816       }
3817 
3818       Inherited::VisitCXXMemberCallExpr(E);
3819     }
3820 
3821     void VisitCallExpr(CallExpr *E) {
3822       // Treat std::move as a use.
3823       if (E->isCallToStdMove()) {
3824         HandleValue(E->getArg(0), /*AddressOf=*/false);
3825         return;
3826       }
3827 
3828       Inherited::VisitCallExpr(E);
3829     }
3830 
3831     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3832       Expr *Callee = E->getCallee();
3833 
3834       if (isa<UnresolvedLookupExpr>(Callee))
3835         return Inherited::VisitCXXOperatorCallExpr(E);
3836 
3837       Visit(Callee);
3838       for (auto Arg : E->arguments())
3839         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3840     }
3841 
3842     void VisitBinaryOperator(BinaryOperator *E) {
3843       // If a field assignment is detected, remove the field from the
3844       // uninitiailized field set.
3845       if (E->getOpcode() == BO_Assign)
3846         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3847           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3848             if (!FD->getType()->isReferenceType())
3849               DeclsToRemove.push_back(FD);
3850 
3851       if (E->isCompoundAssignmentOp()) {
3852         HandleValue(E->getLHS(), false /*AddressOf*/);
3853         Visit(E->getRHS());
3854         return;
3855       }
3856 
3857       Inherited::VisitBinaryOperator(E);
3858     }
3859 
3860     void VisitUnaryOperator(UnaryOperator *E) {
3861       if (E->isIncrementDecrementOp()) {
3862         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3863         return;
3864       }
3865       if (E->getOpcode() == UO_AddrOf) {
3866         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3867           HandleValue(ME->getBase(), true /*AddressOf*/);
3868           return;
3869         }
3870       }
3871 
3872       Inherited::VisitUnaryOperator(E);
3873     }
3874   };
3875 
3876   // Diagnose value-uses of fields to initialize themselves, e.g.
3877   //   foo(foo)
3878   // where foo is not also a parameter to the constructor.
3879   // Also diagnose across field uninitialized use such as
3880   //   x(y), y(x)
3881   // TODO: implement -Wuninitialized and fold this into that framework.
3882   static void DiagnoseUninitializedFields(
3883       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3884 
3885     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3886                                            Constructor->getLocation())) {
3887       return;
3888     }
3889 
3890     if (Constructor->isInvalidDecl())
3891       return;
3892 
3893     const CXXRecordDecl *RD = Constructor->getParent();
3894 
3895     if (RD->isDependentContext())
3896       return;
3897 
3898     // Holds fields that are uninitialized.
3899     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3900 
3901     // At the beginning, all fields are uninitialized.
3902     for (auto *I : RD->decls()) {
3903       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3904         UninitializedFields.insert(FD);
3905       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3906         UninitializedFields.insert(IFD->getAnonField());
3907       }
3908     }
3909 
3910     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3911     for (auto I : RD->bases())
3912       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3913 
3914     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3915       return;
3916 
3917     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3918                                                    UninitializedFields,
3919                                                    UninitializedBaseClasses);
3920 
3921     for (const auto *FieldInit : Constructor->inits()) {
3922       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3923         break;
3924 
3925       Expr *InitExpr = FieldInit->getInit();
3926       if (!InitExpr)
3927         continue;
3928 
3929       if (CXXDefaultInitExpr *Default =
3930               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3931         InitExpr = Default->getExpr();
3932         if (!InitExpr)
3933           continue;
3934         // In class initializers will point to the constructor.
3935         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3936                                               FieldInit->getAnyMember(),
3937                                               FieldInit->getBaseClass());
3938       } else {
3939         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3940                                               FieldInit->getAnyMember(),
3941                                               FieldInit->getBaseClass());
3942       }
3943     }
3944   }
3945 } // namespace
3946 
3947 /// Enter a new C++ default initializer scope. After calling this, the
3948 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3949 /// parsing or instantiating the initializer failed.
3950 void Sema::ActOnStartCXXInClassMemberInitializer() {
3951   // Create a synthetic function scope to represent the call to the constructor
3952   // that notionally surrounds a use of this initializer.
3953   PushFunctionScope();
3954 }
3955 
3956 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3957   if (!D.isFunctionDeclarator())
3958     return;
3959   auto &FTI = D.getFunctionTypeInfo();
3960   if (!FTI.Params)
3961     return;
3962   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3963                                                           FTI.NumParams)) {
3964     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3965     if (ParamDecl->getDeclName())
3966       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3967   }
3968 }
3969 
3970 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3971   return ActOnRequiresClause(ConstraintExpr);
3972 }
3973 
3974 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
3975   if (ConstraintExpr.isInvalid())
3976     return ExprError();
3977 
3978   ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
3979   if (ConstraintExpr.isInvalid())
3980     return ExprError();
3981 
3982   if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
3983                                       UPPC_RequiresClause))
3984     return ExprError();
3985 
3986   return ConstraintExpr;
3987 }
3988 
3989 /// This is invoked after parsing an in-class initializer for a
3990 /// non-static C++ class member, and after instantiating an in-class initializer
3991 /// in a class template. Such actions are deferred until the class is complete.
3992 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3993                                                   SourceLocation InitLoc,
3994                                                   Expr *InitExpr) {
3995   // Pop the notional constructor scope we created earlier.
3996   PopFunctionScopeInfo(nullptr, D);
3997 
3998   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3999   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4000          "must set init style when field is created");
4001 
4002   if (!InitExpr) {
4003     D->setInvalidDecl();
4004     if (FD)
4005       FD->removeInClassInitializer();
4006     return;
4007   }
4008 
4009   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4010     FD->setInvalidDecl();
4011     FD->removeInClassInitializer();
4012     return;
4013   }
4014 
4015   ExprResult Init = InitExpr;
4016   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
4017     InitializedEntity Entity =
4018         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4019     InitializationKind Kind =
4020         FD->getInClassInitStyle() == ICIS_ListInit
4021             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4022                                                    InitExpr->getBeginLoc(),
4023                                                    InitExpr->getEndLoc())
4024             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4025     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4026     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4027     if (Init.isInvalid()) {
4028       FD->setInvalidDecl();
4029       return;
4030     }
4031   }
4032 
4033   // C++11 [class.base.init]p7:
4034   //   The initialization of each base and member constitutes a
4035   //   full-expression.
4036   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4037   if (Init.isInvalid()) {
4038     FD->setInvalidDecl();
4039     return;
4040   }
4041 
4042   InitExpr = Init.get();
4043 
4044   FD->setInClassInitializer(InitExpr);
4045 }
4046 
4047 /// Find the direct and/or virtual base specifiers that
4048 /// correspond to the given base type, for use in base initialization
4049 /// within a constructor.
4050 static bool FindBaseInitializer(Sema &SemaRef,
4051                                 CXXRecordDecl *ClassDecl,
4052                                 QualType BaseType,
4053                                 const CXXBaseSpecifier *&DirectBaseSpec,
4054                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4055   // First, check for a direct base class.
4056   DirectBaseSpec = nullptr;
4057   for (const auto &Base : ClassDecl->bases()) {
4058     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4059       // We found a direct base of this type. That's what we're
4060       // initializing.
4061       DirectBaseSpec = &Base;
4062       break;
4063     }
4064   }
4065 
4066   // Check for a virtual base class.
4067   // FIXME: We might be able to short-circuit this if we know in advance that
4068   // there are no virtual bases.
4069   VirtualBaseSpec = nullptr;
4070   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4071     // We haven't found a base yet; search the class hierarchy for a
4072     // virtual base class.
4073     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4074                        /*DetectVirtual=*/false);
4075     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4076                               SemaRef.Context.getTypeDeclType(ClassDecl),
4077                               BaseType, Paths)) {
4078       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4079            Path != Paths.end(); ++Path) {
4080         if (Path->back().Base->isVirtual()) {
4081           VirtualBaseSpec = Path->back().Base;
4082           break;
4083         }
4084       }
4085     }
4086   }
4087 
4088   return DirectBaseSpec || VirtualBaseSpec;
4089 }
4090 
4091 /// Handle a C++ member initializer using braced-init-list syntax.
4092 MemInitResult
4093 Sema::ActOnMemInitializer(Decl *ConstructorD,
4094                           Scope *S,
4095                           CXXScopeSpec &SS,
4096                           IdentifierInfo *MemberOrBase,
4097                           ParsedType TemplateTypeTy,
4098                           const DeclSpec &DS,
4099                           SourceLocation IdLoc,
4100                           Expr *InitList,
4101                           SourceLocation EllipsisLoc) {
4102   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4103                              DS, IdLoc, InitList,
4104                              EllipsisLoc);
4105 }
4106 
4107 /// Handle a C++ member initializer using parentheses syntax.
4108 MemInitResult
4109 Sema::ActOnMemInitializer(Decl *ConstructorD,
4110                           Scope *S,
4111                           CXXScopeSpec &SS,
4112                           IdentifierInfo *MemberOrBase,
4113                           ParsedType TemplateTypeTy,
4114                           const DeclSpec &DS,
4115                           SourceLocation IdLoc,
4116                           SourceLocation LParenLoc,
4117                           ArrayRef<Expr *> Args,
4118                           SourceLocation RParenLoc,
4119                           SourceLocation EllipsisLoc) {
4120   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4121   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4122                              DS, IdLoc, List, EllipsisLoc);
4123 }
4124 
4125 namespace {
4126 
4127 // Callback to only accept typo corrections that can be a valid C++ member
4128 // initializer: either a non-static field member or a base class.
4129 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4130 public:
4131   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4132       : ClassDecl(ClassDecl) {}
4133 
4134   bool ValidateCandidate(const TypoCorrection &candidate) override {
4135     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4136       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4137         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4138       return isa<TypeDecl>(ND);
4139     }
4140     return false;
4141   }
4142 
4143   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4144     return std::make_unique<MemInitializerValidatorCCC>(*this);
4145   }
4146 
4147 private:
4148   CXXRecordDecl *ClassDecl;
4149 };
4150 
4151 }
4152 
4153 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4154                                              CXXScopeSpec &SS,
4155                                              ParsedType TemplateTypeTy,
4156                                              IdentifierInfo *MemberOrBase) {
4157   if (SS.getScopeRep() || TemplateTypeTy)
4158     return nullptr;
4159   for (auto *D : ClassDecl->lookup(MemberOrBase))
4160     if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4161       return cast<ValueDecl>(D);
4162   return nullptr;
4163 }
4164 
4165 /// Handle a C++ member initializer.
4166 MemInitResult
4167 Sema::BuildMemInitializer(Decl *ConstructorD,
4168                           Scope *S,
4169                           CXXScopeSpec &SS,
4170                           IdentifierInfo *MemberOrBase,
4171                           ParsedType TemplateTypeTy,
4172                           const DeclSpec &DS,
4173                           SourceLocation IdLoc,
4174                           Expr *Init,
4175                           SourceLocation EllipsisLoc) {
4176   ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4177                                              /*RecoverUncorrectedTypos=*/true);
4178   if (!Res.isUsable())
4179     return true;
4180   Init = Res.get();
4181 
4182   if (!ConstructorD)
4183     return true;
4184 
4185   AdjustDeclIfTemplate(ConstructorD);
4186 
4187   CXXConstructorDecl *Constructor
4188     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4189   if (!Constructor) {
4190     // The user wrote a constructor initializer on a function that is
4191     // not a C++ constructor. Ignore the error for now, because we may
4192     // have more member initializers coming; we'll diagnose it just
4193     // once in ActOnMemInitializers.
4194     return true;
4195   }
4196 
4197   CXXRecordDecl *ClassDecl = Constructor->getParent();
4198 
4199   // C++ [class.base.init]p2:
4200   //   Names in a mem-initializer-id are looked up in the scope of the
4201   //   constructor's class and, if not found in that scope, are looked
4202   //   up in the scope containing the constructor's definition.
4203   //   [Note: if the constructor's class contains a member with the
4204   //   same name as a direct or virtual base class of the class, a
4205   //   mem-initializer-id naming the member or base class and composed
4206   //   of a single identifier refers to the class member. A
4207   //   mem-initializer-id for the hidden base class may be specified
4208   //   using a qualified name. ]
4209 
4210   // Look for a member, first.
4211   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4212           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4213     if (EllipsisLoc.isValid())
4214       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4215           << MemberOrBase
4216           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4217 
4218     return BuildMemberInitializer(Member, Init, IdLoc);
4219   }
4220   // It didn't name a member, so see if it names a class.
4221   QualType BaseType;
4222   TypeSourceInfo *TInfo = nullptr;
4223 
4224   if (TemplateTypeTy) {
4225     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4226     if (BaseType.isNull())
4227       return true;
4228   } else if (DS.getTypeSpecType() == TST_decltype) {
4229     BaseType = BuildDecltypeType(DS.getRepAsExpr());
4230   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4231     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4232     return true;
4233   } else {
4234     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4235     LookupParsedName(R, S, &SS);
4236 
4237     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4238     if (!TyD) {
4239       if (R.isAmbiguous()) return true;
4240 
4241       // We don't want access-control diagnostics here.
4242       R.suppressDiagnostics();
4243 
4244       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4245         bool NotUnknownSpecialization = false;
4246         DeclContext *DC = computeDeclContext(SS, false);
4247         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4248           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4249 
4250         if (!NotUnknownSpecialization) {
4251           // When the scope specifier can refer to a member of an unknown
4252           // specialization, we take it as a type name.
4253           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4254                                        SS.getWithLocInContext(Context),
4255                                        *MemberOrBase, IdLoc);
4256           if (BaseType.isNull())
4257             return true;
4258 
4259           TInfo = Context.CreateTypeSourceInfo(BaseType);
4260           DependentNameTypeLoc TL =
4261               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4262           if (!TL.isNull()) {
4263             TL.setNameLoc(IdLoc);
4264             TL.setElaboratedKeywordLoc(SourceLocation());
4265             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4266           }
4267 
4268           R.clear();
4269           R.setLookupName(MemberOrBase);
4270         }
4271       }
4272 
4273       // If no results were found, try to correct typos.
4274       TypoCorrection Corr;
4275       MemInitializerValidatorCCC CCC(ClassDecl);
4276       if (R.empty() && BaseType.isNull() &&
4277           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4278                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4279         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4280           // We have found a non-static data member with a similar
4281           // name to what was typed; complain and initialize that
4282           // member.
4283           diagnoseTypo(Corr,
4284                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4285                          << MemberOrBase << true);
4286           return BuildMemberInitializer(Member, Init, IdLoc);
4287         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4288           const CXXBaseSpecifier *DirectBaseSpec;
4289           const CXXBaseSpecifier *VirtualBaseSpec;
4290           if (FindBaseInitializer(*this, ClassDecl,
4291                                   Context.getTypeDeclType(Type),
4292                                   DirectBaseSpec, VirtualBaseSpec)) {
4293             // We have found a direct or virtual base class with a
4294             // similar name to what was typed; complain and initialize
4295             // that base class.
4296             diagnoseTypo(Corr,
4297                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4298                            << MemberOrBase << false,
4299                          PDiag() /*Suppress note, we provide our own.*/);
4300 
4301             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4302                                                               : VirtualBaseSpec;
4303             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4304                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4305 
4306             TyD = Type;
4307           }
4308         }
4309       }
4310 
4311       if (!TyD && BaseType.isNull()) {
4312         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4313           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4314         return true;
4315       }
4316     }
4317 
4318     if (BaseType.isNull()) {
4319       BaseType = Context.getTypeDeclType(TyD);
4320       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4321       if (SS.isSet()) {
4322         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4323                                              BaseType);
4324         TInfo = Context.CreateTypeSourceInfo(BaseType);
4325         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4326         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4327         TL.setElaboratedKeywordLoc(SourceLocation());
4328         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4329       }
4330     }
4331   }
4332 
4333   if (!TInfo)
4334     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4335 
4336   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4337 }
4338 
4339 MemInitResult
4340 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4341                              SourceLocation IdLoc) {
4342   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4343   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4344   assert((DirectMember || IndirectMember) &&
4345          "Member must be a FieldDecl or IndirectFieldDecl");
4346 
4347   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4348     return true;
4349 
4350   if (Member->isInvalidDecl())
4351     return true;
4352 
4353   MultiExprArg Args;
4354   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4355     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4356   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4357     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4358   } else {
4359     // Template instantiation doesn't reconstruct ParenListExprs for us.
4360     Args = Init;
4361   }
4362 
4363   SourceRange InitRange = Init->getSourceRange();
4364 
4365   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4366     // Can't check initialization for a member of dependent type or when
4367     // any of the arguments are type-dependent expressions.
4368     DiscardCleanupsInEvaluationContext();
4369   } else {
4370     bool InitList = false;
4371     if (isa<InitListExpr>(Init)) {
4372       InitList = true;
4373       Args = Init;
4374     }
4375 
4376     // Initialize the member.
4377     InitializedEntity MemberEntity =
4378       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4379                    : InitializedEntity::InitializeMember(IndirectMember,
4380                                                          nullptr);
4381     InitializationKind Kind =
4382         InitList ? InitializationKind::CreateDirectList(
4383                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4384                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4385                                                     InitRange.getEnd());
4386 
4387     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4388     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4389                                             nullptr);
4390     if (!MemberInit.isInvalid()) {
4391       // C++11 [class.base.init]p7:
4392       //   The initialization of each base and member constitutes a
4393       //   full-expression.
4394       MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4395                                        /*DiscardedValue*/ false);
4396     }
4397 
4398     if (MemberInit.isInvalid()) {
4399       // Args were sensible expressions but we couldn't initialize the member
4400       // from them. Preserve them in a RecoveryExpr instead.
4401       Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4402                                 Member->getType())
4403                  .get();
4404       if (!Init)
4405         return true;
4406     } else {
4407       Init = MemberInit.get();
4408     }
4409   }
4410 
4411   if (DirectMember) {
4412     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4413                                             InitRange.getBegin(), Init,
4414                                             InitRange.getEnd());
4415   } else {
4416     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4417                                             InitRange.getBegin(), Init,
4418                                             InitRange.getEnd());
4419   }
4420 }
4421 
4422 MemInitResult
4423 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4424                                  CXXRecordDecl *ClassDecl) {
4425   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4426   if (!LangOpts.CPlusPlus11)
4427     return Diag(NameLoc, diag::err_delegating_ctor)
4428       << TInfo->getTypeLoc().getLocalSourceRange();
4429   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4430 
4431   bool InitList = true;
4432   MultiExprArg Args = Init;
4433   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4434     InitList = false;
4435     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4436   }
4437 
4438   SourceRange InitRange = Init->getSourceRange();
4439   // Initialize the object.
4440   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4441                                      QualType(ClassDecl->getTypeForDecl(), 0));
4442   InitializationKind Kind =
4443       InitList ? InitializationKind::CreateDirectList(
4444                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4445                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4446                                                   InitRange.getEnd());
4447   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4448   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4449                                               Args, nullptr);
4450   if (!DelegationInit.isInvalid()) {
4451     assert((DelegationInit.get()->containsErrors() ||
4452             cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4453            "Delegating constructor with no target?");
4454 
4455     // C++11 [class.base.init]p7:
4456     //   The initialization of each base and member constitutes a
4457     //   full-expression.
4458     DelegationInit = ActOnFinishFullExpr(
4459         DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4460   }
4461 
4462   if (DelegationInit.isInvalid()) {
4463     DelegationInit =
4464         CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4465                            QualType(ClassDecl->getTypeForDecl(), 0));
4466     if (DelegationInit.isInvalid())
4467       return true;
4468   } else {
4469     // If we are in a dependent context, template instantiation will
4470     // perform this type-checking again. Just save the arguments that we
4471     // received in a ParenListExpr.
4472     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4473     // of the information that we have about the base
4474     // initializer. However, deconstructing the ASTs is a dicey process,
4475     // and this approach is far more likely to get the corner cases right.
4476     if (CurContext->isDependentContext())
4477       DelegationInit = Init;
4478   }
4479 
4480   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4481                                           DelegationInit.getAs<Expr>(),
4482                                           InitRange.getEnd());
4483 }
4484 
4485 MemInitResult
4486 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4487                            Expr *Init, CXXRecordDecl *ClassDecl,
4488                            SourceLocation EllipsisLoc) {
4489   SourceLocation BaseLoc
4490     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4491 
4492   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4493     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4494              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4495 
4496   // C++ [class.base.init]p2:
4497   //   [...] Unless the mem-initializer-id names a nonstatic data
4498   //   member of the constructor's class or a direct or virtual base
4499   //   of that class, the mem-initializer is ill-formed. A
4500   //   mem-initializer-list can initialize a base class using any
4501   //   name that denotes that base class type.
4502 
4503   // We can store the initializers in "as-written" form and delay analysis until
4504   // instantiation if the constructor is dependent. But not for dependent
4505   // (broken) code in a non-template! SetCtorInitializers does not expect this.
4506   bool Dependent = CurContext->isDependentContext() &&
4507                    (BaseType->isDependentType() || Init->isTypeDependent());
4508 
4509   SourceRange InitRange = Init->getSourceRange();
4510   if (EllipsisLoc.isValid()) {
4511     // This is a pack expansion.
4512     if (!BaseType->containsUnexpandedParameterPack())  {
4513       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4514         << SourceRange(BaseLoc, InitRange.getEnd());
4515 
4516       EllipsisLoc = SourceLocation();
4517     }
4518   } else {
4519     // Check for any unexpanded parameter packs.
4520     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4521       return true;
4522 
4523     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4524       return true;
4525   }
4526 
4527   // Check for direct and virtual base classes.
4528   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4529   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4530   if (!Dependent) {
4531     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4532                                        BaseType))
4533       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4534 
4535     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4536                         VirtualBaseSpec);
4537 
4538     // C++ [base.class.init]p2:
4539     // Unless the mem-initializer-id names a nonstatic data member of the
4540     // constructor's class or a direct or virtual base of that class, the
4541     // mem-initializer is ill-formed.
4542     if (!DirectBaseSpec && !VirtualBaseSpec) {
4543       // If the class has any dependent bases, then it's possible that
4544       // one of those types will resolve to the same type as
4545       // BaseType. Therefore, just treat this as a dependent base
4546       // class initialization.  FIXME: Should we try to check the
4547       // initialization anyway? It seems odd.
4548       if (ClassDecl->hasAnyDependentBases())
4549         Dependent = true;
4550       else
4551         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4552           << BaseType << Context.getTypeDeclType(ClassDecl)
4553           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4554     }
4555   }
4556 
4557   if (Dependent) {
4558     DiscardCleanupsInEvaluationContext();
4559 
4560     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4561                                             /*IsVirtual=*/false,
4562                                             InitRange.getBegin(), Init,
4563                                             InitRange.getEnd(), EllipsisLoc);
4564   }
4565 
4566   // C++ [base.class.init]p2:
4567   //   If a mem-initializer-id is ambiguous because it designates both
4568   //   a direct non-virtual base class and an inherited virtual base
4569   //   class, the mem-initializer is ill-formed.
4570   if (DirectBaseSpec && VirtualBaseSpec)
4571     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4572       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4573 
4574   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4575   if (!BaseSpec)
4576     BaseSpec = VirtualBaseSpec;
4577 
4578   // Initialize the base.
4579   bool InitList = true;
4580   MultiExprArg Args = Init;
4581   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4582     InitList = false;
4583     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4584   }
4585 
4586   InitializedEntity BaseEntity =
4587     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4588   InitializationKind Kind =
4589       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4590                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4591                                                   InitRange.getEnd());
4592   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4593   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4594   if (!BaseInit.isInvalid()) {
4595     // C++11 [class.base.init]p7:
4596     //   The initialization of each base and member constitutes a
4597     //   full-expression.
4598     BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4599                                    /*DiscardedValue*/ false);
4600   }
4601 
4602   if (BaseInit.isInvalid()) {
4603     BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4604                                   Args, BaseType);
4605     if (BaseInit.isInvalid())
4606       return true;
4607   } else {
4608     // If we are in a dependent context, template instantiation will
4609     // perform this type-checking again. Just save the arguments that we
4610     // received in a ParenListExpr.
4611     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4612     // of the information that we have about the base
4613     // initializer. However, deconstructing the ASTs is a dicey process,
4614     // and this approach is far more likely to get the corner cases right.
4615     if (CurContext->isDependentContext())
4616       BaseInit = Init;
4617   }
4618 
4619   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4620                                           BaseSpec->isVirtual(),
4621                                           InitRange.getBegin(),
4622                                           BaseInit.getAs<Expr>(),
4623                                           InitRange.getEnd(), EllipsisLoc);
4624 }
4625 
4626 // Create a static_cast\<T&&>(expr).
4627 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4628   if (T.isNull()) T = E->getType();
4629   QualType TargetType = SemaRef.BuildReferenceType(
4630       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4631   SourceLocation ExprLoc = E->getBeginLoc();
4632   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4633       TargetType, ExprLoc);
4634 
4635   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4636                                    SourceRange(ExprLoc, ExprLoc),
4637                                    E->getSourceRange()).get();
4638 }
4639 
4640 /// ImplicitInitializerKind - How an implicit base or member initializer should
4641 /// initialize its base or member.
4642 enum ImplicitInitializerKind {
4643   IIK_Default,
4644   IIK_Copy,
4645   IIK_Move,
4646   IIK_Inherit
4647 };
4648 
4649 static bool
4650 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4651                              ImplicitInitializerKind ImplicitInitKind,
4652                              CXXBaseSpecifier *BaseSpec,
4653                              bool IsInheritedVirtualBase,
4654                              CXXCtorInitializer *&CXXBaseInit) {
4655   InitializedEntity InitEntity
4656     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4657                                         IsInheritedVirtualBase);
4658 
4659   ExprResult BaseInit;
4660 
4661   switch (ImplicitInitKind) {
4662   case IIK_Inherit:
4663   case IIK_Default: {
4664     InitializationKind InitKind
4665       = InitializationKind::CreateDefault(Constructor->getLocation());
4666     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4667     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4668     break;
4669   }
4670 
4671   case IIK_Move:
4672   case IIK_Copy: {
4673     bool Moving = ImplicitInitKind == IIK_Move;
4674     ParmVarDecl *Param = Constructor->getParamDecl(0);
4675     QualType ParamType = Param->getType().getNonReferenceType();
4676 
4677     Expr *CopyCtorArg =
4678       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4679                           SourceLocation(), Param, false,
4680                           Constructor->getLocation(), ParamType,
4681                           VK_LValue, nullptr);
4682 
4683     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4684 
4685     // Cast to the base class to avoid ambiguities.
4686     QualType ArgTy =
4687       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4688                                        ParamType.getQualifiers());
4689 
4690     if (Moving) {
4691       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4692     }
4693 
4694     CXXCastPath BasePath;
4695     BasePath.push_back(BaseSpec);
4696     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4697                                             CK_UncheckedDerivedToBase,
4698                                             Moving ? VK_XValue : VK_LValue,
4699                                             &BasePath).get();
4700 
4701     InitializationKind InitKind
4702       = InitializationKind::CreateDirect(Constructor->getLocation(),
4703                                          SourceLocation(), SourceLocation());
4704     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4705     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4706     break;
4707   }
4708   }
4709 
4710   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4711   if (BaseInit.isInvalid())
4712     return true;
4713 
4714   CXXBaseInit =
4715     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4716                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4717                                                         SourceLocation()),
4718                                              BaseSpec->isVirtual(),
4719                                              SourceLocation(),
4720                                              BaseInit.getAs<Expr>(),
4721                                              SourceLocation(),
4722                                              SourceLocation());
4723 
4724   return false;
4725 }
4726 
4727 static bool RefersToRValueRef(Expr *MemRef) {
4728   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4729   return Referenced->getType()->isRValueReferenceType();
4730 }
4731 
4732 static bool
4733 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4734                                ImplicitInitializerKind ImplicitInitKind,
4735                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4736                                CXXCtorInitializer *&CXXMemberInit) {
4737   if (Field->isInvalidDecl())
4738     return true;
4739 
4740   SourceLocation Loc = Constructor->getLocation();
4741 
4742   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4743     bool Moving = ImplicitInitKind == IIK_Move;
4744     ParmVarDecl *Param = Constructor->getParamDecl(0);
4745     QualType ParamType = Param->getType().getNonReferenceType();
4746 
4747     // Suppress copying zero-width bitfields.
4748     if (Field->isZeroLengthBitField(SemaRef.Context))
4749       return false;
4750 
4751     Expr *MemberExprBase =
4752       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4753                           SourceLocation(), Param, false,
4754                           Loc, ParamType, VK_LValue, nullptr);
4755 
4756     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4757 
4758     if (Moving) {
4759       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4760     }
4761 
4762     // Build a reference to this field within the parameter.
4763     CXXScopeSpec SS;
4764     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4765                               Sema::LookupMemberName);
4766     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4767                                   : cast<ValueDecl>(Field), AS_public);
4768     MemberLookup.resolveKind();
4769     ExprResult CtorArg
4770       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4771                                          ParamType, Loc,
4772                                          /*IsArrow=*/false,
4773                                          SS,
4774                                          /*TemplateKWLoc=*/SourceLocation(),
4775                                          /*FirstQualifierInScope=*/nullptr,
4776                                          MemberLookup,
4777                                          /*TemplateArgs=*/nullptr,
4778                                          /*S*/nullptr);
4779     if (CtorArg.isInvalid())
4780       return true;
4781 
4782     // C++11 [class.copy]p15:
4783     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4784     //     with static_cast<T&&>(x.m);
4785     if (RefersToRValueRef(CtorArg.get())) {
4786       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4787     }
4788 
4789     InitializedEntity Entity =
4790         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4791                                                        /*Implicit*/ true)
4792                  : InitializedEntity::InitializeMember(Field, nullptr,
4793                                                        /*Implicit*/ true);
4794 
4795     // Direct-initialize to use the copy constructor.
4796     InitializationKind InitKind =
4797       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4798 
4799     Expr *CtorArgE = CtorArg.getAs<Expr>();
4800     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4801     ExprResult MemberInit =
4802         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4803     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4804     if (MemberInit.isInvalid())
4805       return true;
4806 
4807     if (Indirect)
4808       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4809           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4810     else
4811       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4812           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4813     return false;
4814   }
4815 
4816   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4817          "Unhandled implicit init kind!");
4818 
4819   QualType FieldBaseElementType =
4820     SemaRef.Context.getBaseElementType(Field->getType());
4821 
4822   if (FieldBaseElementType->isRecordType()) {
4823     InitializedEntity InitEntity =
4824         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4825                                                        /*Implicit*/ true)
4826                  : InitializedEntity::InitializeMember(Field, nullptr,
4827                                                        /*Implicit*/ true);
4828     InitializationKind InitKind =
4829       InitializationKind::CreateDefault(Loc);
4830 
4831     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4832     ExprResult MemberInit =
4833       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4834 
4835     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4836     if (MemberInit.isInvalid())
4837       return true;
4838 
4839     if (Indirect)
4840       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4841                                                                Indirect, Loc,
4842                                                                Loc,
4843                                                                MemberInit.get(),
4844                                                                Loc);
4845     else
4846       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4847                                                                Field, Loc, Loc,
4848                                                                MemberInit.get(),
4849                                                                Loc);
4850     return false;
4851   }
4852 
4853   if (!Field->getParent()->isUnion()) {
4854     if (FieldBaseElementType->isReferenceType()) {
4855       SemaRef.Diag(Constructor->getLocation(),
4856                    diag::err_uninitialized_member_in_ctor)
4857       << (int)Constructor->isImplicit()
4858       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4859       << 0 << Field->getDeclName();
4860       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4861       return true;
4862     }
4863 
4864     if (FieldBaseElementType.isConstQualified()) {
4865       SemaRef.Diag(Constructor->getLocation(),
4866                    diag::err_uninitialized_member_in_ctor)
4867       << (int)Constructor->isImplicit()
4868       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4869       << 1 << Field->getDeclName();
4870       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4871       return true;
4872     }
4873   }
4874 
4875   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4876     // ARC and Weak:
4877     //   Default-initialize Objective-C pointers to NULL.
4878     CXXMemberInit
4879       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4880                                                  Loc, Loc,
4881                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4882                                                  Loc);
4883     return false;
4884   }
4885 
4886   // Nothing to initialize.
4887   CXXMemberInit = nullptr;
4888   return false;
4889 }
4890 
4891 namespace {
4892 struct BaseAndFieldInfo {
4893   Sema &S;
4894   CXXConstructorDecl *Ctor;
4895   bool AnyErrorsInInits;
4896   ImplicitInitializerKind IIK;
4897   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4898   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4899   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4900 
4901   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4902     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4903     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4904     if (Ctor->getInheritedConstructor())
4905       IIK = IIK_Inherit;
4906     else if (Generated && Ctor->isCopyConstructor())
4907       IIK = IIK_Copy;
4908     else if (Generated && Ctor->isMoveConstructor())
4909       IIK = IIK_Move;
4910     else
4911       IIK = IIK_Default;
4912   }
4913 
4914   bool isImplicitCopyOrMove() const {
4915     switch (IIK) {
4916     case IIK_Copy:
4917     case IIK_Move:
4918       return true;
4919 
4920     case IIK_Default:
4921     case IIK_Inherit:
4922       return false;
4923     }
4924 
4925     llvm_unreachable("Invalid ImplicitInitializerKind!");
4926   }
4927 
4928   bool addFieldInitializer(CXXCtorInitializer *Init) {
4929     AllToInit.push_back(Init);
4930 
4931     // Check whether this initializer makes the field "used".
4932     if (Init->getInit()->HasSideEffects(S.Context))
4933       S.UnusedPrivateFields.remove(Init->getAnyMember());
4934 
4935     return false;
4936   }
4937 
4938   bool isInactiveUnionMember(FieldDecl *Field) {
4939     RecordDecl *Record = Field->getParent();
4940     if (!Record->isUnion())
4941       return false;
4942 
4943     if (FieldDecl *Active =
4944             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4945       return Active != Field->getCanonicalDecl();
4946 
4947     // In an implicit copy or move constructor, ignore any in-class initializer.
4948     if (isImplicitCopyOrMove())
4949       return true;
4950 
4951     // If there's no explicit initialization, the field is active only if it
4952     // has an in-class initializer...
4953     if (Field->hasInClassInitializer())
4954       return false;
4955     // ... or it's an anonymous struct or union whose class has an in-class
4956     // initializer.
4957     if (!Field->isAnonymousStructOrUnion())
4958       return true;
4959     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4960     return !FieldRD->hasInClassInitializer();
4961   }
4962 
4963   /// Determine whether the given field is, or is within, a union member
4964   /// that is inactive (because there was an initializer given for a different
4965   /// member of the union, or because the union was not initialized at all).
4966   bool isWithinInactiveUnionMember(FieldDecl *Field,
4967                                    IndirectFieldDecl *Indirect) {
4968     if (!Indirect)
4969       return isInactiveUnionMember(Field);
4970 
4971     for (auto *C : Indirect->chain()) {
4972       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4973       if (Field && isInactiveUnionMember(Field))
4974         return true;
4975     }
4976     return false;
4977   }
4978 };
4979 }
4980 
4981 /// Determine whether the given type is an incomplete or zero-lenfgth
4982 /// array type.
4983 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4984   if (T->isIncompleteArrayType())
4985     return true;
4986 
4987   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4988     if (!ArrayT->getSize())
4989       return true;
4990 
4991     T = ArrayT->getElementType();
4992   }
4993 
4994   return false;
4995 }
4996 
4997 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4998                                     FieldDecl *Field,
4999                                     IndirectFieldDecl *Indirect = nullptr) {
5000   if (Field->isInvalidDecl())
5001     return false;
5002 
5003   // Overwhelmingly common case: we have a direct initializer for this field.
5004   if (CXXCtorInitializer *Init =
5005           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5006     return Info.addFieldInitializer(Init);
5007 
5008   // C++11 [class.base.init]p8:
5009   //   if the entity is a non-static data member that has a
5010   //   brace-or-equal-initializer and either
5011   //   -- the constructor's class is a union and no other variant member of that
5012   //      union is designated by a mem-initializer-id or
5013   //   -- the constructor's class is not a union, and, if the entity is a member
5014   //      of an anonymous union, no other member of that union is designated by
5015   //      a mem-initializer-id,
5016   //   the entity is initialized as specified in [dcl.init].
5017   //
5018   // We also apply the same rules to handle anonymous structs within anonymous
5019   // unions.
5020   if (Info.isWithinInactiveUnionMember(Field, Indirect))
5021     return false;
5022 
5023   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5024     ExprResult DIE =
5025         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5026     if (DIE.isInvalid())
5027       return true;
5028 
5029     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5030     SemaRef.checkInitializerLifetime(Entity, DIE.get());
5031 
5032     CXXCtorInitializer *Init;
5033     if (Indirect)
5034       Init = new (SemaRef.Context)
5035           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5036                              SourceLocation(), DIE.get(), SourceLocation());
5037     else
5038       Init = new (SemaRef.Context)
5039           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5040                              SourceLocation(), DIE.get(), SourceLocation());
5041     return Info.addFieldInitializer(Init);
5042   }
5043 
5044   // Don't initialize incomplete or zero-length arrays.
5045   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5046     return false;
5047 
5048   // Don't try to build an implicit initializer if there were semantic
5049   // errors in any of the initializers (and therefore we might be
5050   // missing some that the user actually wrote).
5051   if (Info.AnyErrorsInInits)
5052     return false;
5053 
5054   CXXCtorInitializer *Init = nullptr;
5055   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5056                                      Indirect, Init))
5057     return true;
5058 
5059   if (!Init)
5060     return false;
5061 
5062   return Info.addFieldInitializer(Init);
5063 }
5064 
5065 bool
5066 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5067                                CXXCtorInitializer *Initializer) {
5068   assert(Initializer->isDelegatingInitializer());
5069   Constructor->setNumCtorInitializers(1);
5070   CXXCtorInitializer **initializer =
5071     new (Context) CXXCtorInitializer*[1];
5072   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5073   Constructor->setCtorInitializers(initializer);
5074 
5075   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5076     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5077     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5078   }
5079 
5080   DelegatingCtorDecls.push_back(Constructor);
5081 
5082   DiagnoseUninitializedFields(*this, Constructor);
5083 
5084   return false;
5085 }
5086 
5087 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5088                                ArrayRef<CXXCtorInitializer *> Initializers) {
5089   if (Constructor->isDependentContext()) {
5090     // Just store the initializers as written, they will be checked during
5091     // instantiation.
5092     if (!Initializers.empty()) {
5093       Constructor->setNumCtorInitializers(Initializers.size());
5094       CXXCtorInitializer **baseOrMemberInitializers =
5095         new (Context) CXXCtorInitializer*[Initializers.size()];
5096       memcpy(baseOrMemberInitializers, Initializers.data(),
5097              Initializers.size() * sizeof(CXXCtorInitializer*));
5098       Constructor->setCtorInitializers(baseOrMemberInitializers);
5099     }
5100 
5101     // Let template instantiation know whether we had errors.
5102     if (AnyErrors)
5103       Constructor->setInvalidDecl();
5104 
5105     return false;
5106   }
5107 
5108   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5109 
5110   // We need to build the initializer AST according to order of construction
5111   // and not what user specified in the Initializers list.
5112   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5113   if (!ClassDecl)
5114     return true;
5115 
5116   bool HadError = false;
5117 
5118   for (unsigned i = 0; i < Initializers.size(); i++) {
5119     CXXCtorInitializer *Member = Initializers[i];
5120 
5121     if (Member->isBaseInitializer())
5122       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5123     else {
5124       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5125 
5126       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5127         for (auto *C : F->chain()) {
5128           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5129           if (FD && FD->getParent()->isUnion())
5130             Info.ActiveUnionMember.insert(std::make_pair(
5131                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5132         }
5133       } else if (FieldDecl *FD = Member->getMember()) {
5134         if (FD->getParent()->isUnion())
5135           Info.ActiveUnionMember.insert(std::make_pair(
5136               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5137       }
5138     }
5139   }
5140 
5141   // Keep track of the direct virtual bases.
5142   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5143   for (auto &I : ClassDecl->bases()) {
5144     if (I.isVirtual())
5145       DirectVBases.insert(&I);
5146   }
5147 
5148   // Push virtual bases before others.
5149   for (auto &VBase : ClassDecl->vbases()) {
5150     if (CXXCtorInitializer *Value
5151         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5152       // [class.base.init]p7, per DR257:
5153       //   A mem-initializer where the mem-initializer-id names a virtual base
5154       //   class is ignored during execution of a constructor of any class that
5155       //   is not the most derived class.
5156       if (ClassDecl->isAbstract()) {
5157         // FIXME: Provide a fixit to remove the base specifier. This requires
5158         // tracking the location of the associated comma for a base specifier.
5159         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5160           << VBase.getType() << ClassDecl;
5161         DiagnoseAbstractType(ClassDecl);
5162       }
5163 
5164       Info.AllToInit.push_back(Value);
5165     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5166       // [class.base.init]p8, per DR257:
5167       //   If a given [...] base class is not named by a mem-initializer-id
5168       //   [...] and the entity is not a virtual base class of an abstract
5169       //   class, then [...] the entity is default-initialized.
5170       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5171       CXXCtorInitializer *CXXBaseInit;
5172       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5173                                        &VBase, IsInheritedVirtualBase,
5174                                        CXXBaseInit)) {
5175         HadError = true;
5176         continue;
5177       }
5178 
5179       Info.AllToInit.push_back(CXXBaseInit);
5180     }
5181   }
5182 
5183   // Non-virtual bases.
5184   for (auto &Base : ClassDecl->bases()) {
5185     // Virtuals are in the virtual base list and already constructed.
5186     if (Base.isVirtual())
5187       continue;
5188 
5189     if (CXXCtorInitializer *Value
5190           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5191       Info.AllToInit.push_back(Value);
5192     } else if (!AnyErrors) {
5193       CXXCtorInitializer *CXXBaseInit;
5194       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5195                                        &Base, /*IsInheritedVirtualBase=*/false,
5196                                        CXXBaseInit)) {
5197         HadError = true;
5198         continue;
5199       }
5200 
5201       Info.AllToInit.push_back(CXXBaseInit);
5202     }
5203   }
5204 
5205   // Fields.
5206   for (auto *Mem : ClassDecl->decls()) {
5207     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5208       // C++ [class.bit]p2:
5209       //   A declaration for a bit-field that omits the identifier declares an
5210       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5211       //   initialized.
5212       if (F->isUnnamedBitfield())
5213         continue;
5214 
5215       // If we're not generating the implicit copy/move constructor, then we'll
5216       // handle anonymous struct/union fields based on their individual
5217       // indirect fields.
5218       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5219         continue;
5220 
5221       if (CollectFieldInitializer(*this, Info, F))
5222         HadError = true;
5223       continue;
5224     }
5225 
5226     // Beyond this point, we only consider default initialization.
5227     if (Info.isImplicitCopyOrMove())
5228       continue;
5229 
5230     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5231       if (F->getType()->isIncompleteArrayType()) {
5232         assert(ClassDecl->hasFlexibleArrayMember() &&
5233                "Incomplete array type is not valid");
5234         continue;
5235       }
5236 
5237       // Initialize each field of an anonymous struct individually.
5238       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5239         HadError = true;
5240 
5241       continue;
5242     }
5243   }
5244 
5245   unsigned NumInitializers = Info.AllToInit.size();
5246   if (NumInitializers > 0) {
5247     Constructor->setNumCtorInitializers(NumInitializers);
5248     CXXCtorInitializer **baseOrMemberInitializers =
5249       new (Context) CXXCtorInitializer*[NumInitializers];
5250     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5251            NumInitializers * sizeof(CXXCtorInitializer*));
5252     Constructor->setCtorInitializers(baseOrMemberInitializers);
5253 
5254     // Constructors implicitly reference the base and member
5255     // destructors.
5256     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5257                                            Constructor->getParent());
5258   }
5259 
5260   return HadError;
5261 }
5262 
5263 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5264   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5265     const RecordDecl *RD = RT->getDecl();
5266     if (RD->isAnonymousStructOrUnion()) {
5267       for (auto *Field : RD->fields())
5268         PopulateKeysForFields(Field, IdealInits);
5269       return;
5270     }
5271   }
5272   IdealInits.push_back(Field->getCanonicalDecl());
5273 }
5274 
5275 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5276   return Context.getCanonicalType(BaseType).getTypePtr();
5277 }
5278 
5279 static const void *GetKeyForMember(ASTContext &Context,
5280                                    CXXCtorInitializer *Member) {
5281   if (!Member->isAnyMemberInitializer())
5282     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5283 
5284   return Member->getAnyMember()->getCanonicalDecl();
5285 }
5286 
5287 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5288                                  const CXXCtorInitializer *Previous,
5289                                  const CXXCtorInitializer *Current) {
5290   if (Previous->isAnyMemberInitializer())
5291     Diag << 0 << Previous->getAnyMember();
5292   else
5293     Diag << 1 << Previous->getTypeSourceInfo()->getType();
5294 
5295   if (Current->isAnyMemberInitializer())
5296     Diag << 0 << Current->getAnyMember();
5297   else
5298     Diag << 1 << Current->getTypeSourceInfo()->getType();
5299 }
5300 
5301 static void DiagnoseBaseOrMemInitializerOrder(
5302     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5303     ArrayRef<CXXCtorInitializer *> Inits) {
5304   if (Constructor->getDeclContext()->isDependentContext())
5305     return;
5306 
5307   // Don't check initializers order unless the warning is enabled at the
5308   // location of at least one initializer.
5309   bool ShouldCheckOrder = false;
5310   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5311     CXXCtorInitializer *Init = Inits[InitIndex];
5312     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5313                                  Init->getSourceLocation())) {
5314       ShouldCheckOrder = true;
5315       break;
5316     }
5317   }
5318   if (!ShouldCheckOrder)
5319     return;
5320 
5321   // Build the list of bases and members in the order that they'll
5322   // actually be initialized.  The explicit initializers should be in
5323   // this same order but may be missing things.
5324   SmallVector<const void*, 32> IdealInitKeys;
5325 
5326   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5327 
5328   // 1. Virtual bases.
5329   for (const auto &VBase : ClassDecl->vbases())
5330     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5331 
5332   // 2. Non-virtual bases.
5333   for (const auto &Base : ClassDecl->bases()) {
5334     if (Base.isVirtual())
5335       continue;
5336     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5337   }
5338 
5339   // 3. Direct fields.
5340   for (auto *Field : ClassDecl->fields()) {
5341     if (Field->isUnnamedBitfield())
5342       continue;
5343 
5344     PopulateKeysForFields(Field, IdealInitKeys);
5345   }
5346 
5347   unsigned NumIdealInits = IdealInitKeys.size();
5348   unsigned IdealIndex = 0;
5349 
5350   // Track initializers that are in an incorrect order for either a warning or
5351   // note if multiple ones occur.
5352   SmallVector<unsigned> WarnIndexes;
5353   // Correlates the index of an initializer in the init-list to the index of
5354   // the field/base in the class.
5355   SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5356 
5357   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5358     const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5359 
5360     // Scan forward to try to find this initializer in the idealized
5361     // initializers list.
5362     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5363       if (InitKey == IdealInitKeys[IdealIndex])
5364         break;
5365 
5366     // If we didn't find this initializer, it must be because we
5367     // scanned past it on a previous iteration.  That can only
5368     // happen if we're out of order;  emit a warning.
5369     if (IdealIndex == NumIdealInits && InitIndex) {
5370       WarnIndexes.push_back(InitIndex);
5371 
5372       // Move back to the initializer's location in the ideal list.
5373       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5374         if (InitKey == IdealInitKeys[IdealIndex])
5375           break;
5376 
5377       assert(IdealIndex < NumIdealInits &&
5378              "initializer not found in initializer list");
5379     }
5380     CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5381   }
5382 
5383   if (WarnIndexes.empty())
5384     return;
5385 
5386   // Sort based on the ideal order, first in the pair.
5387   llvm::sort(CorrelatedInitOrder,
5388              [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; });
5389 
5390   // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5391   // emit the diagnostic before we can try adding notes.
5392   {
5393     Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5394         Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5395         WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5396                                 : diag::warn_some_initializers_out_of_order);
5397 
5398     for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5399       if (CorrelatedInitOrder[I].second == I)
5400         continue;
5401       // Ideally we would be using InsertFromRange here, but clang doesn't
5402       // appear to handle InsertFromRange correctly when the source range is
5403       // modified by another fix-it.
5404       D << FixItHint::CreateReplacement(
5405           Inits[I]->getSourceRange(),
5406           Lexer::getSourceText(
5407               CharSourceRange::getTokenRange(
5408                   Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5409               SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5410     }
5411 
5412     // If there is only 1 item out of order, the warning expects the name and
5413     // type of each being added to it.
5414     if (WarnIndexes.size() == 1) {
5415       AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5416                            Inits[WarnIndexes.front()]);
5417       return;
5418     }
5419   }
5420   // More than 1 item to warn, create notes letting the user know which ones
5421   // are bad.
5422   for (unsigned WarnIndex : WarnIndexes) {
5423     const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5424     auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5425                           diag::note_initializer_out_of_order);
5426     AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5427     D << PrevInit->getSourceRange();
5428   }
5429 }
5430 
5431 namespace {
5432 bool CheckRedundantInit(Sema &S,
5433                         CXXCtorInitializer *Init,
5434                         CXXCtorInitializer *&PrevInit) {
5435   if (!PrevInit) {
5436     PrevInit = Init;
5437     return false;
5438   }
5439 
5440   if (FieldDecl *Field = Init->getAnyMember())
5441     S.Diag(Init->getSourceLocation(),
5442            diag::err_multiple_mem_initialization)
5443       << Field->getDeclName()
5444       << Init->getSourceRange();
5445   else {
5446     const Type *BaseClass = Init->getBaseClass();
5447     assert(BaseClass && "neither field nor base");
5448     S.Diag(Init->getSourceLocation(),
5449            diag::err_multiple_base_initialization)
5450       << QualType(BaseClass, 0)
5451       << Init->getSourceRange();
5452   }
5453   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5454     << 0 << PrevInit->getSourceRange();
5455 
5456   return true;
5457 }
5458 
5459 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5460 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5461 
5462 bool CheckRedundantUnionInit(Sema &S,
5463                              CXXCtorInitializer *Init,
5464                              RedundantUnionMap &Unions) {
5465   FieldDecl *Field = Init->getAnyMember();
5466   RecordDecl *Parent = Field->getParent();
5467   NamedDecl *Child = Field;
5468 
5469   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5470     if (Parent->isUnion()) {
5471       UnionEntry &En = Unions[Parent];
5472       if (En.first && En.first != Child) {
5473         S.Diag(Init->getSourceLocation(),
5474                diag::err_multiple_mem_union_initialization)
5475           << Field->getDeclName()
5476           << Init->getSourceRange();
5477         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5478           << 0 << En.second->getSourceRange();
5479         return true;
5480       }
5481       if (!En.first) {
5482         En.first = Child;
5483         En.second = Init;
5484       }
5485       if (!Parent->isAnonymousStructOrUnion())
5486         return false;
5487     }
5488 
5489     Child = Parent;
5490     Parent = cast<RecordDecl>(Parent->getDeclContext());
5491   }
5492 
5493   return false;
5494 }
5495 } // namespace
5496 
5497 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5498 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5499                                 SourceLocation ColonLoc,
5500                                 ArrayRef<CXXCtorInitializer*> MemInits,
5501                                 bool AnyErrors) {
5502   if (!ConstructorDecl)
5503     return;
5504 
5505   AdjustDeclIfTemplate(ConstructorDecl);
5506 
5507   CXXConstructorDecl *Constructor
5508     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5509 
5510   if (!Constructor) {
5511     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5512     return;
5513   }
5514 
5515   // Mapping for the duplicate initializers check.
5516   // For member initializers, this is keyed with a FieldDecl*.
5517   // For base initializers, this is keyed with a Type*.
5518   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5519 
5520   // Mapping for the inconsistent anonymous-union initializers check.
5521   RedundantUnionMap MemberUnions;
5522 
5523   bool HadError = false;
5524   for (unsigned i = 0; i < MemInits.size(); i++) {
5525     CXXCtorInitializer *Init = MemInits[i];
5526 
5527     // Set the source order index.
5528     Init->setSourceOrder(i);
5529 
5530     if (Init->isAnyMemberInitializer()) {
5531       const void *Key = GetKeyForMember(Context, Init);
5532       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5533           CheckRedundantUnionInit(*this, Init, MemberUnions))
5534         HadError = true;
5535     } else if (Init->isBaseInitializer()) {
5536       const void *Key = GetKeyForMember(Context, Init);
5537       if (CheckRedundantInit(*this, Init, Members[Key]))
5538         HadError = true;
5539     } else {
5540       assert(Init->isDelegatingInitializer());
5541       // This must be the only initializer
5542       if (MemInits.size() != 1) {
5543         Diag(Init->getSourceLocation(),
5544              diag::err_delegating_initializer_alone)
5545           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5546         // We will treat this as being the only initializer.
5547       }
5548       SetDelegatingInitializer(Constructor, MemInits[i]);
5549       // Return immediately as the initializer is set.
5550       return;
5551     }
5552   }
5553 
5554   if (HadError)
5555     return;
5556 
5557   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5558 
5559   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5560 
5561   DiagnoseUninitializedFields(*this, Constructor);
5562 }
5563 
5564 void
5565 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5566                                              CXXRecordDecl *ClassDecl) {
5567   // Ignore dependent contexts. Also ignore unions, since their members never
5568   // have destructors implicitly called.
5569   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5570     return;
5571 
5572   // FIXME: all the access-control diagnostics are positioned on the
5573   // field/base declaration.  That's probably good; that said, the
5574   // user might reasonably want to know why the destructor is being
5575   // emitted, and we currently don't say.
5576 
5577   // Non-static data members.
5578   for (auto *Field : ClassDecl->fields()) {
5579     if (Field->isInvalidDecl())
5580       continue;
5581 
5582     // Don't destroy incomplete or zero-length arrays.
5583     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5584       continue;
5585 
5586     QualType FieldType = Context.getBaseElementType(Field->getType());
5587 
5588     const RecordType* RT = FieldType->getAs<RecordType>();
5589     if (!RT)
5590       continue;
5591 
5592     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5593     if (FieldClassDecl->isInvalidDecl())
5594       continue;
5595     if (FieldClassDecl->hasIrrelevantDestructor())
5596       continue;
5597     // The destructor for an implicit anonymous union member is never invoked.
5598     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5599       continue;
5600 
5601     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5602     assert(Dtor && "No dtor found for FieldClassDecl!");
5603     CheckDestructorAccess(Field->getLocation(), Dtor,
5604                           PDiag(diag::err_access_dtor_field)
5605                             << Field->getDeclName()
5606                             << FieldType);
5607 
5608     MarkFunctionReferenced(Location, Dtor);
5609     DiagnoseUseOfDecl(Dtor, Location);
5610   }
5611 
5612   // We only potentially invoke the destructors of potentially constructed
5613   // subobjects.
5614   bool VisitVirtualBases = !ClassDecl->isAbstract();
5615 
5616   // If the destructor exists and has already been marked used in the MS ABI,
5617   // then virtual base destructors have already been checked and marked used.
5618   // Skip checking them again to avoid duplicate diagnostics.
5619   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5620     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5621     if (Dtor && Dtor->isUsed())
5622       VisitVirtualBases = false;
5623   }
5624 
5625   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5626 
5627   // Bases.
5628   for (const auto &Base : ClassDecl->bases()) {
5629     const RecordType *RT = Base.getType()->getAs<RecordType>();
5630     if (!RT)
5631       continue;
5632 
5633     // Remember direct virtual bases.
5634     if (Base.isVirtual()) {
5635       if (!VisitVirtualBases)
5636         continue;
5637       DirectVirtualBases.insert(RT);
5638     }
5639 
5640     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5641     // If our base class is invalid, we probably can't get its dtor anyway.
5642     if (BaseClassDecl->isInvalidDecl())
5643       continue;
5644     if (BaseClassDecl->hasIrrelevantDestructor())
5645       continue;
5646 
5647     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5648     assert(Dtor && "No dtor found for BaseClassDecl!");
5649 
5650     // FIXME: caret should be on the start of the class name
5651     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5652                           PDiag(diag::err_access_dtor_base)
5653                               << Base.getType() << Base.getSourceRange(),
5654                           Context.getTypeDeclType(ClassDecl));
5655 
5656     MarkFunctionReferenced(Location, Dtor);
5657     DiagnoseUseOfDecl(Dtor, Location);
5658   }
5659 
5660   if (VisitVirtualBases)
5661     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5662                                          &DirectVirtualBases);
5663 }
5664 
5665 void Sema::MarkVirtualBaseDestructorsReferenced(
5666     SourceLocation Location, CXXRecordDecl *ClassDecl,
5667     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5668   // Virtual bases.
5669   for (const auto &VBase : ClassDecl->vbases()) {
5670     // Bases are always records in a well-formed non-dependent class.
5671     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5672 
5673     // Ignore already visited direct virtual bases.
5674     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5675       continue;
5676 
5677     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5678     // If our base class is invalid, we probably can't get its dtor anyway.
5679     if (BaseClassDecl->isInvalidDecl())
5680       continue;
5681     if (BaseClassDecl->hasIrrelevantDestructor())
5682       continue;
5683 
5684     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5685     assert(Dtor && "No dtor found for BaseClassDecl!");
5686     if (CheckDestructorAccess(
5687             ClassDecl->getLocation(), Dtor,
5688             PDiag(diag::err_access_dtor_vbase)
5689                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5690             Context.getTypeDeclType(ClassDecl)) ==
5691         AR_accessible) {
5692       CheckDerivedToBaseConversion(
5693           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5694           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5695           SourceRange(), DeclarationName(), nullptr);
5696     }
5697 
5698     MarkFunctionReferenced(Location, Dtor);
5699     DiagnoseUseOfDecl(Dtor, Location);
5700   }
5701 }
5702 
5703 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5704   if (!CDtorDecl)
5705     return;
5706 
5707   if (CXXConstructorDecl *Constructor
5708       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5709     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5710     DiagnoseUninitializedFields(*this, Constructor);
5711   }
5712 }
5713 
5714 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5715   if (!getLangOpts().CPlusPlus)
5716     return false;
5717 
5718   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5719   if (!RD)
5720     return false;
5721 
5722   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5723   // class template specialization here, but doing so breaks a lot of code.
5724 
5725   // We can't answer whether something is abstract until it has a
5726   // definition. If it's currently being defined, we'll walk back
5727   // over all the declarations when we have a full definition.
5728   const CXXRecordDecl *Def = RD->getDefinition();
5729   if (!Def || Def->isBeingDefined())
5730     return false;
5731 
5732   return RD->isAbstract();
5733 }
5734 
5735 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5736                                   TypeDiagnoser &Diagnoser) {
5737   if (!isAbstractType(Loc, T))
5738     return false;
5739 
5740   T = Context.getBaseElementType(T);
5741   Diagnoser.diagnose(*this, Loc, T);
5742   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5743   return true;
5744 }
5745 
5746 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5747   // Check if we've already emitted the list of pure virtual functions
5748   // for this class.
5749   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5750     return;
5751 
5752   // If the diagnostic is suppressed, don't emit the notes. We're only
5753   // going to emit them once, so try to attach them to a diagnostic we're
5754   // actually going to show.
5755   if (Diags.isLastDiagnosticIgnored())
5756     return;
5757 
5758   CXXFinalOverriderMap FinalOverriders;
5759   RD->getFinalOverriders(FinalOverriders);
5760 
5761   // Keep a set of seen pure methods so we won't diagnose the same method
5762   // more than once.
5763   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5764 
5765   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5766                                    MEnd = FinalOverriders.end();
5767        M != MEnd;
5768        ++M) {
5769     for (OverridingMethods::iterator SO = M->second.begin(),
5770                                   SOEnd = M->second.end();
5771          SO != SOEnd; ++SO) {
5772       // C++ [class.abstract]p4:
5773       //   A class is abstract if it contains or inherits at least one
5774       //   pure virtual function for which the final overrider is pure
5775       //   virtual.
5776 
5777       //
5778       if (SO->second.size() != 1)
5779         continue;
5780 
5781       if (!SO->second.front().Method->isPure())
5782         continue;
5783 
5784       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5785         continue;
5786 
5787       Diag(SO->second.front().Method->getLocation(),
5788            diag::note_pure_virtual_function)
5789         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5790     }
5791   }
5792 
5793   if (!PureVirtualClassDiagSet)
5794     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5795   PureVirtualClassDiagSet->insert(RD);
5796 }
5797 
5798 namespace {
5799 struct AbstractUsageInfo {
5800   Sema &S;
5801   CXXRecordDecl *Record;
5802   CanQualType AbstractType;
5803   bool Invalid;
5804 
5805   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5806     : S(S), Record(Record),
5807       AbstractType(S.Context.getCanonicalType(
5808                    S.Context.getTypeDeclType(Record))),
5809       Invalid(false) {}
5810 
5811   void DiagnoseAbstractType() {
5812     if (Invalid) return;
5813     S.DiagnoseAbstractType(Record);
5814     Invalid = true;
5815   }
5816 
5817   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5818 };
5819 
5820 struct CheckAbstractUsage {
5821   AbstractUsageInfo &Info;
5822   const NamedDecl *Ctx;
5823 
5824   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5825     : Info(Info), Ctx(Ctx) {}
5826 
5827   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5828     switch (TL.getTypeLocClass()) {
5829 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5830 #define TYPELOC(CLASS, PARENT) \
5831     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5832 #include "clang/AST/TypeLocNodes.def"
5833     }
5834   }
5835 
5836   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5837     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5838     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5839       if (!TL.getParam(I))
5840         continue;
5841 
5842       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5843       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5844     }
5845   }
5846 
5847   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5848     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5849   }
5850 
5851   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5852     // Visit the type parameters from a permissive context.
5853     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5854       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5855       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5856         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5857           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5858       // TODO: other template argument types?
5859     }
5860   }
5861 
5862   // Visit pointee types from a permissive context.
5863 #define CheckPolymorphic(Type) \
5864   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5865     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5866   }
5867   CheckPolymorphic(PointerTypeLoc)
5868   CheckPolymorphic(ReferenceTypeLoc)
5869   CheckPolymorphic(MemberPointerTypeLoc)
5870   CheckPolymorphic(BlockPointerTypeLoc)
5871   CheckPolymorphic(AtomicTypeLoc)
5872 
5873   /// Handle all the types we haven't given a more specific
5874   /// implementation for above.
5875   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5876     // Every other kind of type that we haven't called out already
5877     // that has an inner type is either (1) sugar or (2) contains that
5878     // inner type in some way as a subobject.
5879     if (TypeLoc Next = TL.getNextTypeLoc())
5880       return Visit(Next, Sel);
5881 
5882     // If there's no inner type and we're in a permissive context,
5883     // don't diagnose.
5884     if (Sel == Sema::AbstractNone) return;
5885 
5886     // Check whether the type matches the abstract type.
5887     QualType T = TL.getType();
5888     if (T->isArrayType()) {
5889       Sel = Sema::AbstractArrayType;
5890       T = Info.S.Context.getBaseElementType(T);
5891     }
5892     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5893     if (CT != Info.AbstractType) return;
5894 
5895     // It matched; do some magic.
5896     // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
5897     if (Sel == Sema::AbstractArrayType) {
5898       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5899         << T << TL.getSourceRange();
5900     } else {
5901       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5902         << Sel << T << TL.getSourceRange();
5903     }
5904     Info.DiagnoseAbstractType();
5905   }
5906 };
5907 
5908 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5909                                   Sema::AbstractDiagSelID Sel) {
5910   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5911 }
5912 
5913 }
5914 
5915 /// Check for invalid uses of an abstract type in a function declaration.
5916 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5917                                     FunctionDecl *FD) {
5918   // No need to do the check on definitions, which require that
5919   // the return/param types be complete.
5920   if (FD->doesThisDeclarationHaveABody())
5921     return;
5922 
5923   // For safety's sake, just ignore it if we don't have type source
5924   // information.  This should never happen for non-implicit methods,
5925   // but...
5926   if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5927     Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
5928 }
5929 
5930 /// Check for invalid uses of an abstract type in a variable0 declaration.
5931 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5932                                     VarDecl *VD) {
5933   // No need to do the check on definitions, which require that
5934   // the type is complete.
5935   if (VD->isThisDeclarationADefinition())
5936     return;
5937 
5938   Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
5939                  Sema::AbstractVariableType);
5940 }
5941 
5942 /// Check for invalid uses of an abstract type within a class definition.
5943 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5944                                     CXXRecordDecl *RD) {
5945   for (auto *D : RD->decls()) {
5946     if (D->isImplicit()) continue;
5947 
5948     // Step through friends to the befriended declaration.
5949     if (auto *FD = dyn_cast<FriendDecl>(D)) {
5950       D = FD->getFriendDecl();
5951       if (!D) continue;
5952     }
5953 
5954     // Functions and function templates.
5955     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5956       CheckAbstractClassUsage(Info, FD);
5957     } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
5958       CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
5959 
5960     // Fields and static variables.
5961     } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
5962       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5963         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5964     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
5965       CheckAbstractClassUsage(Info, VD);
5966     } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
5967       CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
5968 
5969     // Nested classes and class templates.
5970     } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5971       CheckAbstractClassUsage(Info, RD);
5972     } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
5973       CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
5974     }
5975   }
5976 }
5977 
5978 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5979   Attr *ClassAttr = getDLLAttr(Class);
5980   if (!ClassAttr)
5981     return;
5982 
5983   assert(ClassAttr->getKind() == attr::DLLExport);
5984 
5985   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5986 
5987   if (TSK == TSK_ExplicitInstantiationDeclaration)
5988     // Don't go any further if this is just an explicit instantiation
5989     // declaration.
5990     return;
5991 
5992   // Add a context note to explain how we got to any diagnostics produced below.
5993   struct MarkingClassDllexported {
5994     Sema &S;
5995     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5996                             SourceLocation AttrLoc)
5997         : S(S) {
5998       Sema::CodeSynthesisContext Ctx;
5999       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6000       Ctx.PointOfInstantiation = AttrLoc;
6001       Ctx.Entity = Class;
6002       S.pushCodeSynthesisContext(Ctx);
6003     }
6004     ~MarkingClassDllexported() {
6005       S.popCodeSynthesisContext();
6006     }
6007   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6008 
6009   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6010     S.MarkVTableUsed(Class->getLocation(), Class, true);
6011 
6012   for (Decl *Member : Class->decls()) {
6013     // Skip members that were not marked exported.
6014     if (!Member->hasAttr<DLLExportAttr>())
6015       continue;
6016 
6017     // Defined static variables that are members of an exported base
6018     // class must be marked export too.
6019     auto *VD = dyn_cast<VarDecl>(Member);
6020     if (VD && VD->getStorageClass() == SC_Static &&
6021         TSK == TSK_ImplicitInstantiation)
6022       S.MarkVariableReferenced(VD->getLocation(), VD);
6023 
6024     auto *MD = dyn_cast<CXXMethodDecl>(Member);
6025     if (!MD)
6026       continue;
6027 
6028     if (MD->isUserProvided()) {
6029       // Instantiate non-default class member functions ...
6030 
6031       // .. except for certain kinds of template specializations.
6032       if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6033         continue;
6034 
6035       // If this is an MS ABI dllexport default constructor, instantiate any
6036       // default arguments.
6037       if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6038         auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6039         if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6040           S.InstantiateDefaultCtorDefaultArgs(CD);
6041         }
6042       }
6043 
6044       S.MarkFunctionReferenced(Class->getLocation(), MD);
6045 
6046       // The function will be passed to the consumer when its definition is
6047       // encountered.
6048     } else if (MD->isExplicitlyDefaulted()) {
6049       // Synthesize and instantiate explicitly defaulted methods.
6050       S.MarkFunctionReferenced(Class->getLocation(), MD);
6051 
6052       if (TSK != TSK_ExplicitInstantiationDefinition) {
6053         // Except for explicit instantiation defs, we will not see the
6054         // definition again later, so pass it to the consumer now.
6055         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6056       }
6057     } else if (!MD->isTrivial() ||
6058                MD->isCopyAssignmentOperator() ||
6059                MD->isMoveAssignmentOperator()) {
6060       // Synthesize and instantiate non-trivial implicit methods, and the copy
6061       // and move assignment operators. The latter are exported even if they
6062       // are trivial, because the address of an operator can be taken and
6063       // should compare equal across libraries.
6064       S.MarkFunctionReferenced(Class->getLocation(), MD);
6065 
6066       // There is no later point when we will see the definition of this
6067       // function, so pass it to the consumer now.
6068       S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6069     }
6070   }
6071 }
6072 
6073 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6074                                                         CXXRecordDecl *Class) {
6075   // Only the MS ABI has default constructor closures, so we don't need to do
6076   // this semantic checking anywhere else.
6077   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6078     return;
6079 
6080   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6081   for (Decl *Member : Class->decls()) {
6082     // Look for exported default constructors.
6083     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6084     if (!CD || !CD->isDefaultConstructor())
6085       continue;
6086     auto *Attr = CD->getAttr<DLLExportAttr>();
6087     if (!Attr)
6088       continue;
6089 
6090     // If the class is non-dependent, mark the default arguments as ODR-used so
6091     // that we can properly codegen the constructor closure.
6092     if (!Class->isDependentContext()) {
6093       for (ParmVarDecl *PD : CD->parameters()) {
6094         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6095         S.DiscardCleanupsInEvaluationContext();
6096       }
6097     }
6098 
6099     if (LastExportedDefaultCtor) {
6100       S.Diag(LastExportedDefaultCtor->getLocation(),
6101              diag::err_attribute_dll_ambiguous_default_ctor)
6102           << Class;
6103       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6104           << CD->getDeclName();
6105       return;
6106     }
6107     LastExportedDefaultCtor = CD;
6108   }
6109 }
6110 
6111 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6112                                                        CXXRecordDecl *Class) {
6113   bool ErrorReported = false;
6114   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6115                                                      ClassTemplateDecl *TD) {
6116     if (ErrorReported)
6117       return;
6118     S.Diag(TD->getLocation(),
6119            diag::err_cuda_device_builtin_surftex_cls_template)
6120         << /*surface*/ 0 << TD;
6121     ErrorReported = true;
6122   };
6123 
6124   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6125   if (!TD) {
6126     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6127     if (!SD) {
6128       S.Diag(Class->getLocation(),
6129              diag::err_cuda_device_builtin_surftex_ref_decl)
6130           << /*surface*/ 0 << Class;
6131       S.Diag(Class->getLocation(),
6132              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6133           << Class;
6134       return;
6135     }
6136     TD = SD->getSpecializedTemplate();
6137   }
6138 
6139   TemplateParameterList *Params = TD->getTemplateParameters();
6140   unsigned N = Params->size();
6141 
6142   if (N != 2) {
6143     reportIllegalClassTemplate(S, TD);
6144     S.Diag(TD->getLocation(),
6145            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6146         << TD << 2;
6147   }
6148   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6149     reportIllegalClassTemplate(S, TD);
6150     S.Diag(TD->getLocation(),
6151            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6152         << TD << /*1st*/ 0 << /*type*/ 0;
6153   }
6154   if (N > 1) {
6155     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6156     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6157       reportIllegalClassTemplate(S, TD);
6158       S.Diag(TD->getLocation(),
6159              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6160           << TD << /*2nd*/ 1 << /*integer*/ 1;
6161     }
6162   }
6163 }
6164 
6165 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6166                                                        CXXRecordDecl *Class) {
6167   bool ErrorReported = false;
6168   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6169                                                      ClassTemplateDecl *TD) {
6170     if (ErrorReported)
6171       return;
6172     S.Diag(TD->getLocation(),
6173            diag::err_cuda_device_builtin_surftex_cls_template)
6174         << /*texture*/ 1 << TD;
6175     ErrorReported = true;
6176   };
6177 
6178   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6179   if (!TD) {
6180     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6181     if (!SD) {
6182       S.Diag(Class->getLocation(),
6183              diag::err_cuda_device_builtin_surftex_ref_decl)
6184           << /*texture*/ 1 << Class;
6185       S.Diag(Class->getLocation(),
6186              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6187           << Class;
6188       return;
6189     }
6190     TD = SD->getSpecializedTemplate();
6191   }
6192 
6193   TemplateParameterList *Params = TD->getTemplateParameters();
6194   unsigned N = Params->size();
6195 
6196   if (N != 3) {
6197     reportIllegalClassTemplate(S, TD);
6198     S.Diag(TD->getLocation(),
6199            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6200         << TD << 3;
6201   }
6202   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6203     reportIllegalClassTemplate(S, TD);
6204     S.Diag(TD->getLocation(),
6205            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6206         << TD << /*1st*/ 0 << /*type*/ 0;
6207   }
6208   if (N > 1) {
6209     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6210     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6211       reportIllegalClassTemplate(S, TD);
6212       S.Diag(TD->getLocation(),
6213              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6214           << TD << /*2nd*/ 1 << /*integer*/ 1;
6215     }
6216   }
6217   if (N > 2) {
6218     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6219     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6220       reportIllegalClassTemplate(S, TD);
6221       S.Diag(TD->getLocation(),
6222              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6223           << TD << /*3rd*/ 2 << /*integer*/ 1;
6224     }
6225   }
6226 }
6227 
6228 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6229   // Mark any compiler-generated routines with the implicit code_seg attribute.
6230   for (auto *Method : Class->methods()) {
6231     if (Method->isUserProvided())
6232       continue;
6233     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6234       Method->addAttr(A);
6235   }
6236 }
6237 
6238 /// Check class-level dllimport/dllexport attribute.
6239 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6240   Attr *ClassAttr = getDLLAttr(Class);
6241 
6242   // MSVC inherits DLL attributes to partial class template specializations.
6243   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6244     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6245       if (Attr *TemplateAttr =
6246               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6247         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6248         A->setInherited(true);
6249         ClassAttr = A;
6250       }
6251     }
6252   }
6253 
6254   if (!ClassAttr)
6255     return;
6256 
6257   if (!Class->isExternallyVisible()) {
6258     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6259         << Class << ClassAttr;
6260     return;
6261   }
6262 
6263   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6264       !ClassAttr->isInherited()) {
6265     // Diagnose dll attributes on members of class with dll attribute.
6266     for (Decl *Member : Class->decls()) {
6267       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6268         continue;
6269       InheritableAttr *MemberAttr = getDLLAttr(Member);
6270       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6271         continue;
6272 
6273       Diag(MemberAttr->getLocation(),
6274              diag::err_attribute_dll_member_of_dll_class)
6275           << MemberAttr << ClassAttr;
6276       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6277       Member->setInvalidDecl();
6278     }
6279   }
6280 
6281   if (Class->getDescribedClassTemplate())
6282     // Don't inherit dll attribute until the template is instantiated.
6283     return;
6284 
6285   // The class is either imported or exported.
6286   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6287 
6288   // Check if this was a dllimport attribute propagated from a derived class to
6289   // a base class template specialization. We don't apply these attributes to
6290   // static data members.
6291   const bool PropagatedImport =
6292       !ClassExported &&
6293       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6294 
6295   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6296 
6297   // Ignore explicit dllexport on explicit class template instantiation
6298   // declarations, except in MinGW mode.
6299   if (ClassExported && !ClassAttr->isInherited() &&
6300       TSK == TSK_ExplicitInstantiationDeclaration &&
6301       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6302     Class->dropAttr<DLLExportAttr>();
6303     return;
6304   }
6305 
6306   // Force declaration of implicit members so they can inherit the attribute.
6307   ForceDeclarationOfImplicitMembers(Class);
6308 
6309   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6310   // seem to be true in practice?
6311 
6312   for (Decl *Member : Class->decls()) {
6313     VarDecl *VD = dyn_cast<VarDecl>(Member);
6314     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6315 
6316     // Only methods and static fields inherit the attributes.
6317     if (!VD && !MD)
6318       continue;
6319 
6320     if (MD) {
6321       // Don't process deleted methods.
6322       if (MD->isDeleted())
6323         continue;
6324 
6325       if (MD->isInlined()) {
6326         // MinGW does not import or export inline methods. But do it for
6327         // template instantiations.
6328         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6329             TSK != TSK_ExplicitInstantiationDeclaration &&
6330             TSK != TSK_ExplicitInstantiationDefinition)
6331           continue;
6332 
6333         // MSVC versions before 2015 don't export the move assignment operators
6334         // and move constructor, so don't attempt to import/export them if
6335         // we have a definition.
6336         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6337         if ((MD->isMoveAssignmentOperator() ||
6338              (Ctor && Ctor->isMoveConstructor())) &&
6339             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6340           continue;
6341 
6342         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6343         // operator is exported anyway.
6344         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6345             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6346           continue;
6347       }
6348     }
6349 
6350     // Don't apply dllimport attributes to static data members of class template
6351     // instantiations when the attribute is propagated from a derived class.
6352     if (VD && PropagatedImport)
6353       continue;
6354 
6355     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6356       continue;
6357 
6358     if (!getDLLAttr(Member)) {
6359       InheritableAttr *NewAttr = nullptr;
6360 
6361       // Do not export/import inline function when -fno-dllexport-inlines is
6362       // passed. But add attribute for later local static var check.
6363       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6364           TSK != TSK_ExplicitInstantiationDeclaration &&
6365           TSK != TSK_ExplicitInstantiationDefinition) {
6366         if (ClassExported) {
6367           NewAttr = ::new (getASTContext())
6368               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6369         } else {
6370           NewAttr = ::new (getASTContext())
6371               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6372         }
6373       } else {
6374         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6375       }
6376 
6377       NewAttr->setInherited(true);
6378       Member->addAttr(NewAttr);
6379 
6380       if (MD) {
6381         // Propagate DLLAttr to friend re-declarations of MD that have already
6382         // been constructed.
6383         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6384              FD = FD->getPreviousDecl()) {
6385           if (FD->getFriendObjectKind() == Decl::FOK_None)
6386             continue;
6387           assert(!getDLLAttr(FD) &&
6388                  "friend re-decl should not already have a DLLAttr");
6389           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6390           NewAttr->setInherited(true);
6391           FD->addAttr(NewAttr);
6392         }
6393       }
6394     }
6395   }
6396 
6397   if (ClassExported)
6398     DelayedDllExportClasses.push_back(Class);
6399 }
6400 
6401 /// Perform propagation of DLL attributes from a derived class to a
6402 /// templated base class for MS compatibility.
6403 void Sema::propagateDLLAttrToBaseClassTemplate(
6404     CXXRecordDecl *Class, Attr *ClassAttr,
6405     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6406   if (getDLLAttr(
6407           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6408     // If the base class template has a DLL attribute, don't try to change it.
6409     return;
6410   }
6411 
6412   auto TSK = BaseTemplateSpec->getSpecializationKind();
6413   if (!getDLLAttr(BaseTemplateSpec) &&
6414       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6415        TSK == TSK_ImplicitInstantiation)) {
6416     // The template hasn't been instantiated yet (or it has, but only as an
6417     // explicit instantiation declaration or implicit instantiation, which means
6418     // we haven't codegenned any members yet), so propagate the attribute.
6419     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6420     NewAttr->setInherited(true);
6421     BaseTemplateSpec->addAttr(NewAttr);
6422 
6423     // If this was an import, mark that we propagated it from a derived class to
6424     // a base class template specialization.
6425     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6426       ImportAttr->setPropagatedToBaseTemplate();
6427 
6428     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6429     // needs to be run again to work see the new attribute. Otherwise this will
6430     // get run whenever the template is instantiated.
6431     if (TSK != TSK_Undeclared)
6432       checkClassLevelDLLAttribute(BaseTemplateSpec);
6433 
6434     return;
6435   }
6436 
6437   if (getDLLAttr(BaseTemplateSpec)) {
6438     // The template has already been specialized or instantiated with an
6439     // attribute, explicitly or through propagation. We should not try to change
6440     // it.
6441     return;
6442   }
6443 
6444   // The template was previously instantiated or explicitly specialized without
6445   // a dll attribute, It's too late for us to add an attribute, so warn that
6446   // this is unsupported.
6447   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6448       << BaseTemplateSpec->isExplicitSpecialization();
6449   Diag(ClassAttr->getLocation(), diag::note_attribute);
6450   if (BaseTemplateSpec->isExplicitSpecialization()) {
6451     Diag(BaseTemplateSpec->getLocation(),
6452            diag::note_template_class_explicit_specialization_was_here)
6453         << BaseTemplateSpec;
6454   } else {
6455     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6456            diag::note_template_class_instantiation_was_here)
6457         << BaseTemplateSpec;
6458   }
6459 }
6460 
6461 /// Determine the kind of defaulting that would be done for a given function.
6462 ///
6463 /// If the function is both a default constructor and a copy / move constructor
6464 /// (due to having a default argument for the first parameter), this picks
6465 /// CXXDefaultConstructor.
6466 ///
6467 /// FIXME: Check that case is properly handled by all callers.
6468 Sema::DefaultedFunctionKind
6469 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6470   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6471     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6472       if (Ctor->isDefaultConstructor())
6473         return Sema::CXXDefaultConstructor;
6474 
6475       if (Ctor->isCopyConstructor())
6476         return Sema::CXXCopyConstructor;
6477 
6478       if (Ctor->isMoveConstructor())
6479         return Sema::CXXMoveConstructor;
6480     }
6481 
6482     if (MD->isCopyAssignmentOperator())
6483       return Sema::CXXCopyAssignment;
6484 
6485     if (MD->isMoveAssignmentOperator())
6486       return Sema::CXXMoveAssignment;
6487 
6488     if (isa<CXXDestructorDecl>(FD))
6489       return Sema::CXXDestructor;
6490   }
6491 
6492   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6493   case OO_EqualEqual:
6494     return DefaultedComparisonKind::Equal;
6495 
6496   case OO_ExclaimEqual:
6497     return DefaultedComparisonKind::NotEqual;
6498 
6499   case OO_Spaceship:
6500     // No point allowing this if <=> doesn't exist in the current language mode.
6501     if (!getLangOpts().CPlusPlus20)
6502       break;
6503     return DefaultedComparisonKind::ThreeWay;
6504 
6505   case OO_Less:
6506   case OO_LessEqual:
6507   case OO_Greater:
6508   case OO_GreaterEqual:
6509     // No point allowing this if <=> doesn't exist in the current language mode.
6510     if (!getLangOpts().CPlusPlus20)
6511       break;
6512     return DefaultedComparisonKind::Relational;
6513 
6514   default:
6515     break;
6516   }
6517 
6518   // Not defaultable.
6519   return DefaultedFunctionKind();
6520 }
6521 
6522 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6523                                     SourceLocation DefaultLoc) {
6524   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6525   if (DFK.isComparison())
6526     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6527 
6528   switch (DFK.asSpecialMember()) {
6529   case Sema::CXXDefaultConstructor:
6530     S.DefineImplicitDefaultConstructor(DefaultLoc,
6531                                        cast<CXXConstructorDecl>(FD));
6532     break;
6533   case Sema::CXXCopyConstructor:
6534     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6535     break;
6536   case Sema::CXXCopyAssignment:
6537     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6538     break;
6539   case Sema::CXXDestructor:
6540     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6541     break;
6542   case Sema::CXXMoveConstructor:
6543     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6544     break;
6545   case Sema::CXXMoveAssignment:
6546     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6547     break;
6548   case Sema::CXXInvalid:
6549     llvm_unreachable("Invalid special member.");
6550   }
6551 }
6552 
6553 /// Determine whether a type is permitted to be passed or returned in
6554 /// registers, per C++ [class.temporary]p3.
6555 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6556                                TargetInfo::CallingConvKind CCK) {
6557   if (D->isDependentType() || D->isInvalidDecl())
6558     return false;
6559 
6560   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6561   // The PS4 platform ABI follows the behavior of Clang 3.2.
6562   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6563     return !D->hasNonTrivialDestructorForCall() &&
6564            !D->hasNonTrivialCopyConstructorForCall();
6565 
6566   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6567     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6568     bool DtorIsTrivialForCall = false;
6569 
6570     // If a class has at least one non-deleted, trivial copy constructor, it
6571     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6572     //
6573     // Note: This permits classes with non-trivial copy or move ctors to be
6574     // passed in registers, so long as they *also* have a trivial copy ctor,
6575     // which is non-conforming.
6576     if (D->needsImplicitCopyConstructor()) {
6577       if (!D->defaultedCopyConstructorIsDeleted()) {
6578         if (D->hasTrivialCopyConstructor())
6579           CopyCtorIsTrivial = true;
6580         if (D->hasTrivialCopyConstructorForCall())
6581           CopyCtorIsTrivialForCall = true;
6582       }
6583     } else {
6584       for (const CXXConstructorDecl *CD : D->ctors()) {
6585         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6586           if (CD->isTrivial())
6587             CopyCtorIsTrivial = true;
6588           if (CD->isTrivialForCall())
6589             CopyCtorIsTrivialForCall = true;
6590         }
6591       }
6592     }
6593 
6594     if (D->needsImplicitDestructor()) {
6595       if (!D->defaultedDestructorIsDeleted() &&
6596           D->hasTrivialDestructorForCall())
6597         DtorIsTrivialForCall = true;
6598     } else if (const auto *DD = D->getDestructor()) {
6599       if (!DD->isDeleted() && DD->isTrivialForCall())
6600         DtorIsTrivialForCall = true;
6601     }
6602 
6603     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6604     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6605       return true;
6606 
6607     // If a class has a destructor, we'd really like to pass it indirectly
6608     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6609     // impossible for small types, which it will pass in a single register or
6610     // stack slot. Most objects with dtors are large-ish, so handle that early.
6611     // We can't call out all large objects as being indirect because there are
6612     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6613     // how we pass large POD types.
6614 
6615     // Note: This permits small classes with nontrivial destructors to be
6616     // passed in registers, which is non-conforming.
6617     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6618     uint64_t TypeSize = isAArch64 ? 128 : 64;
6619 
6620     if (CopyCtorIsTrivial &&
6621         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6622       return true;
6623     return false;
6624   }
6625 
6626   // Per C++ [class.temporary]p3, the relevant condition is:
6627   //   each copy constructor, move constructor, and destructor of X is
6628   //   either trivial or deleted, and X has at least one non-deleted copy
6629   //   or move constructor
6630   bool HasNonDeletedCopyOrMove = false;
6631 
6632   if (D->needsImplicitCopyConstructor() &&
6633       !D->defaultedCopyConstructorIsDeleted()) {
6634     if (!D->hasTrivialCopyConstructorForCall())
6635       return false;
6636     HasNonDeletedCopyOrMove = true;
6637   }
6638 
6639   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6640       !D->defaultedMoveConstructorIsDeleted()) {
6641     if (!D->hasTrivialMoveConstructorForCall())
6642       return false;
6643     HasNonDeletedCopyOrMove = true;
6644   }
6645 
6646   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6647       !D->hasTrivialDestructorForCall())
6648     return false;
6649 
6650   for (const CXXMethodDecl *MD : D->methods()) {
6651     if (MD->isDeleted())
6652       continue;
6653 
6654     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6655     if (CD && CD->isCopyOrMoveConstructor())
6656       HasNonDeletedCopyOrMove = true;
6657     else if (!isa<CXXDestructorDecl>(MD))
6658       continue;
6659 
6660     if (!MD->isTrivialForCall())
6661       return false;
6662   }
6663 
6664   return HasNonDeletedCopyOrMove;
6665 }
6666 
6667 /// Report an error regarding overriding, along with any relevant
6668 /// overridden methods.
6669 ///
6670 /// \param DiagID the primary error to report.
6671 /// \param MD the overriding method.
6672 static bool
6673 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6674                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6675   bool IssuedDiagnostic = false;
6676   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6677     if (Report(O)) {
6678       if (!IssuedDiagnostic) {
6679         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6680         IssuedDiagnostic = true;
6681       }
6682       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6683     }
6684   }
6685   return IssuedDiagnostic;
6686 }
6687 
6688 /// Perform semantic checks on a class definition that has been
6689 /// completing, introducing implicitly-declared members, checking for
6690 /// abstract types, etc.
6691 ///
6692 /// \param S The scope in which the class was parsed. Null if we didn't just
6693 ///        parse a class definition.
6694 /// \param Record The completed class.
6695 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6696   if (!Record)
6697     return;
6698 
6699   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6700     AbstractUsageInfo Info(*this, Record);
6701     CheckAbstractClassUsage(Info, Record);
6702   }
6703 
6704   // If this is not an aggregate type and has no user-declared constructor,
6705   // complain about any non-static data members of reference or const scalar
6706   // type, since they will never get initializers.
6707   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6708       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6709       !Record->isLambda()) {
6710     bool Complained = false;
6711     for (const auto *F : Record->fields()) {
6712       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6713         continue;
6714 
6715       if (F->getType()->isReferenceType() ||
6716           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6717         if (!Complained) {
6718           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6719             << Record->getTagKind() << Record;
6720           Complained = true;
6721         }
6722 
6723         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6724           << F->getType()->isReferenceType()
6725           << F->getDeclName();
6726       }
6727     }
6728   }
6729 
6730   if (Record->getIdentifier()) {
6731     // C++ [class.mem]p13:
6732     //   If T is the name of a class, then each of the following shall have a
6733     //   name different from T:
6734     //     - every member of every anonymous union that is a member of class T.
6735     //
6736     // C++ [class.mem]p14:
6737     //   In addition, if class T has a user-declared constructor (12.1), every
6738     //   non-static data member of class T shall have a name different from T.
6739     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6740     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6741          ++I) {
6742       NamedDecl *D = (*I)->getUnderlyingDecl();
6743       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6744            Record->hasUserDeclaredConstructor()) ||
6745           isa<IndirectFieldDecl>(D)) {
6746         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6747           << D->getDeclName();
6748         break;
6749       }
6750     }
6751   }
6752 
6753   // Warn if the class has virtual methods but non-virtual public destructor.
6754   if (Record->isPolymorphic() && !Record->isDependentType()) {
6755     CXXDestructorDecl *dtor = Record->getDestructor();
6756     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6757         !Record->hasAttr<FinalAttr>())
6758       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6759            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6760   }
6761 
6762   if (Record->isAbstract()) {
6763     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6764       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6765         << FA->isSpelledAsSealed();
6766       DiagnoseAbstractType(Record);
6767     }
6768   }
6769 
6770   // Warn if the class has a final destructor but is not itself marked final.
6771   if (!Record->hasAttr<FinalAttr>()) {
6772     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6773       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6774         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6775             << FA->isSpelledAsSealed()
6776             << FixItHint::CreateInsertion(
6777                    getLocForEndOfToken(Record->getLocation()),
6778                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6779         Diag(Record->getLocation(),
6780              diag::note_final_dtor_non_final_class_silence)
6781             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6782       }
6783     }
6784   }
6785 
6786   // See if trivial_abi has to be dropped.
6787   if (Record->hasAttr<TrivialABIAttr>())
6788     checkIllFormedTrivialABIStruct(*Record);
6789 
6790   // Set HasTrivialSpecialMemberForCall if the record has attribute
6791   // "trivial_abi".
6792   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6793 
6794   if (HasTrivialABI)
6795     Record->setHasTrivialSpecialMemberForCall();
6796 
6797   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6798   // We check these last because they can depend on the properties of the
6799   // primary comparison functions (==, <=>).
6800   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6801 
6802   // Perform checks that can't be done until we know all the properties of a
6803   // member function (whether it's defaulted, deleted, virtual, overriding,
6804   // ...).
6805   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6806     // A static function cannot override anything.
6807     if (MD->getStorageClass() == SC_Static) {
6808       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6809                           [](const CXXMethodDecl *) { return true; }))
6810         return;
6811     }
6812 
6813     // A deleted function cannot override a non-deleted function and vice
6814     // versa.
6815     if (ReportOverrides(*this,
6816                         MD->isDeleted() ? diag::err_deleted_override
6817                                         : diag::err_non_deleted_override,
6818                         MD, [&](const CXXMethodDecl *V) {
6819                           return MD->isDeleted() != V->isDeleted();
6820                         })) {
6821       if (MD->isDefaulted() && MD->isDeleted())
6822         // Explain why this defaulted function was deleted.
6823         DiagnoseDeletedDefaultedFunction(MD);
6824       return;
6825     }
6826 
6827     // A consteval function cannot override a non-consteval function and vice
6828     // versa.
6829     if (ReportOverrides(*this,
6830                         MD->isConsteval() ? diag::err_consteval_override
6831                                           : diag::err_non_consteval_override,
6832                         MD, [&](const CXXMethodDecl *V) {
6833                           return MD->isConsteval() != V->isConsteval();
6834                         })) {
6835       if (MD->isDefaulted() && MD->isDeleted())
6836         // Explain why this defaulted function was deleted.
6837         DiagnoseDeletedDefaultedFunction(MD);
6838       return;
6839     }
6840   };
6841 
6842   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6843     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6844       return false;
6845 
6846     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6847     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6848         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6849       DefaultedSecondaryComparisons.push_back(FD);
6850       return true;
6851     }
6852 
6853     CheckExplicitlyDefaultedFunction(S, FD);
6854     return false;
6855   };
6856 
6857   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6858     // Check whether the explicitly-defaulted members are valid.
6859     bool Incomplete = CheckForDefaultedFunction(M);
6860 
6861     // Skip the rest of the checks for a member of a dependent class.
6862     if (Record->isDependentType())
6863       return;
6864 
6865     // For an explicitly defaulted or deleted special member, we defer
6866     // determining triviality until the class is complete. That time is now!
6867     CXXSpecialMember CSM = getSpecialMember(M);
6868     if (!M->isImplicit() && !M->isUserProvided()) {
6869       if (CSM != CXXInvalid) {
6870         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6871         // Inform the class that we've finished declaring this member.
6872         Record->finishedDefaultedOrDeletedMember(M);
6873         M->setTrivialForCall(
6874             HasTrivialABI ||
6875             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6876         Record->setTrivialForCallFlags(M);
6877       }
6878     }
6879 
6880     // Set triviality for the purpose of calls if this is a user-provided
6881     // copy/move constructor or destructor.
6882     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6883          CSM == CXXDestructor) && M->isUserProvided()) {
6884       M->setTrivialForCall(HasTrivialABI);
6885       Record->setTrivialForCallFlags(M);
6886     }
6887 
6888     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6889         M->hasAttr<DLLExportAttr>()) {
6890       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6891           M->isTrivial() &&
6892           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6893            CSM == CXXDestructor))
6894         M->dropAttr<DLLExportAttr>();
6895 
6896       if (M->hasAttr<DLLExportAttr>()) {
6897         // Define after any fields with in-class initializers have been parsed.
6898         DelayedDllExportMemberFunctions.push_back(M);
6899       }
6900     }
6901 
6902     // Define defaulted constexpr virtual functions that override a base class
6903     // function right away.
6904     // FIXME: We can defer doing this until the vtable is marked as used.
6905     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6906       DefineDefaultedFunction(*this, M, M->getLocation());
6907 
6908     if (!Incomplete)
6909       CheckCompletedMemberFunction(M);
6910   };
6911 
6912   // Check the destructor before any other member function. We need to
6913   // determine whether it's trivial in order to determine whether the claas
6914   // type is a literal type, which is a prerequisite for determining whether
6915   // other special member functions are valid and whether they're implicitly
6916   // 'constexpr'.
6917   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6918     CompleteMemberFunction(Dtor);
6919 
6920   bool HasMethodWithOverrideControl = false,
6921        HasOverridingMethodWithoutOverrideControl = false;
6922   for (auto *D : Record->decls()) {
6923     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6924       // FIXME: We could do this check for dependent types with non-dependent
6925       // bases.
6926       if (!Record->isDependentType()) {
6927         // See if a method overloads virtual methods in a base
6928         // class without overriding any.
6929         if (!M->isStatic())
6930           DiagnoseHiddenVirtualMethods(M);
6931         if (M->hasAttr<OverrideAttr>())
6932           HasMethodWithOverrideControl = true;
6933         else if (M->size_overridden_methods() > 0)
6934           HasOverridingMethodWithoutOverrideControl = true;
6935       }
6936 
6937       if (!isa<CXXDestructorDecl>(M))
6938         CompleteMemberFunction(M);
6939     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6940       CheckForDefaultedFunction(
6941           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6942     }
6943   }
6944 
6945   if (HasOverridingMethodWithoutOverrideControl) {
6946     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6947     for (auto *M : Record->methods())
6948       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6949   }
6950 
6951   // Check the defaulted secondary comparisons after any other member functions.
6952   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6953     CheckExplicitlyDefaultedFunction(S, FD);
6954 
6955     // If this is a member function, we deferred checking it until now.
6956     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6957       CheckCompletedMemberFunction(MD);
6958   }
6959 
6960   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6961   // whether this class uses any C++ features that are implemented
6962   // completely differently in MSVC, and if so, emit a diagnostic.
6963   // That diagnostic defaults to an error, but we allow projects to
6964   // map it down to a warning (or ignore it).  It's a fairly common
6965   // practice among users of the ms_struct pragma to mass-annotate
6966   // headers, sweeping up a bunch of types that the project doesn't
6967   // really rely on MSVC-compatible layout for.  We must therefore
6968   // support "ms_struct except for C++ stuff" as a secondary ABI.
6969   // Don't emit this diagnostic if the feature was enabled as a
6970   // language option (as opposed to via a pragma or attribute), as
6971   // the option -mms-bitfields otherwise essentially makes it impossible
6972   // to build C++ code, unless this diagnostic is turned off.
6973   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6974       (Record->isPolymorphic() || Record->getNumBases())) {
6975     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6976   }
6977 
6978   checkClassLevelDLLAttribute(Record);
6979   checkClassLevelCodeSegAttribute(Record);
6980 
6981   bool ClangABICompat4 =
6982       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6983   TargetInfo::CallingConvKind CCK =
6984       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6985   bool CanPass = canPassInRegisters(*this, Record, CCK);
6986 
6987   // Do not change ArgPassingRestrictions if it has already been set to
6988   // APK_CanNeverPassInRegs.
6989   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6990     Record->setArgPassingRestrictions(CanPass
6991                                           ? RecordDecl::APK_CanPassInRegs
6992                                           : RecordDecl::APK_CannotPassInRegs);
6993 
6994   // If canPassInRegisters returns true despite the record having a non-trivial
6995   // destructor, the record is destructed in the callee. This happens only when
6996   // the record or one of its subobjects has a field annotated with trivial_abi
6997   // or a field qualified with ObjC __strong/__weak.
6998   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6999     Record->setParamDestroyedInCallee(true);
7000   else if (Record->hasNonTrivialDestructor())
7001     Record->setParamDestroyedInCallee(CanPass);
7002 
7003   if (getLangOpts().ForceEmitVTables) {
7004     // If we want to emit all the vtables, we need to mark it as used.  This
7005     // is especially required for cases like vtable assumption loads.
7006     MarkVTableUsed(Record->getInnerLocStart(), Record);
7007   }
7008 
7009   if (getLangOpts().CUDA) {
7010     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7011       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7012     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7013       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7014   }
7015 }
7016 
7017 /// Look up the special member function that would be called by a special
7018 /// member function for a subobject of class type.
7019 ///
7020 /// \param Class The class type of the subobject.
7021 /// \param CSM The kind of special member function.
7022 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7023 /// \param ConstRHS True if this is a copy operation with a const object
7024 ///        on its RHS, that is, if the argument to the outer special member
7025 ///        function is 'const' and this is not a field marked 'mutable'.
7026 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7027     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7028     unsigned FieldQuals, bool ConstRHS) {
7029   unsigned LHSQuals = 0;
7030   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7031     LHSQuals = FieldQuals;
7032 
7033   unsigned RHSQuals = FieldQuals;
7034   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7035     RHSQuals = 0;
7036   else if (ConstRHS)
7037     RHSQuals |= Qualifiers::Const;
7038 
7039   return S.LookupSpecialMember(Class, CSM,
7040                                RHSQuals & Qualifiers::Const,
7041                                RHSQuals & Qualifiers::Volatile,
7042                                false,
7043                                LHSQuals & Qualifiers::Const,
7044                                LHSQuals & Qualifiers::Volatile);
7045 }
7046 
7047 class Sema::InheritedConstructorInfo {
7048   Sema &S;
7049   SourceLocation UseLoc;
7050 
7051   /// A mapping from the base classes through which the constructor was
7052   /// inherited to the using shadow declaration in that base class (or a null
7053   /// pointer if the constructor was declared in that base class).
7054   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7055       InheritedFromBases;
7056 
7057 public:
7058   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7059                            ConstructorUsingShadowDecl *Shadow)
7060       : S(S), UseLoc(UseLoc) {
7061     bool DiagnosedMultipleConstructedBases = false;
7062     CXXRecordDecl *ConstructedBase = nullptr;
7063     BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7064 
7065     // Find the set of such base class subobjects and check that there's a
7066     // unique constructed subobject.
7067     for (auto *D : Shadow->redecls()) {
7068       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7069       auto *DNominatedBase = DShadow->getNominatedBaseClass();
7070       auto *DConstructedBase = DShadow->getConstructedBaseClass();
7071 
7072       InheritedFromBases.insert(
7073           std::make_pair(DNominatedBase->getCanonicalDecl(),
7074                          DShadow->getNominatedBaseClassShadowDecl()));
7075       if (DShadow->constructsVirtualBase())
7076         InheritedFromBases.insert(
7077             std::make_pair(DConstructedBase->getCanonicalDecl(),
7078                            DShadow->getConstructedBaseClassShadowDecl()));
7079       else
7080         assert(DNominatedBase == DConstructedBase);
7081 
7082       // [class.inhctor.init]p2:
7083       //   If the constructor was inherited from multiple base class subobjects
7084       //   of type B, the program is ill-formed.
7085       if (!ConstructedBase) {
7086         ConstructedBase = DConstructedBase;
7087         ConstructedBaseIntroducer = D->getIntroducer();
7088       } else if (ConstructedBase != DConstructedBase &&
7089                  !Shadow->isInvalidDecl()) {
7090         if (!DiagnosedMultipleConstructedBases) {
7091           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7092               << Shadow->getTargetDecl();
7093           S.Diag(ConstructedBaseIntroducer->getLocation(),
7094                  diag::note_ambiguous_inherited_constructor_using)
7095               << ConstructedBase;
7096           DiagnosedMultipleConstructedBases = true;
7097         }
7098         S.Diag(D->getIntroducer()->getLocation(),
7099                diag::note_ambiguous_inherited_constructor_using)
7100             << DConstructedBase;
7101       }
7102     }
7103 
7104     if (DiagnosedMultipleConstructedBases)
7105       Shadow->setInvalidDecl();
7106   }
7107 
7108   /// Find the constructor to use for inherited construction of a base class,
7109   /// and whether that base class constructor inherits the constructor from a
7110   /// virtual base class (in which case it won't actually invoke it).
7111   std::pair<CXXConstructorDecl *, bool>
7112   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7113     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7114     if (It == InheritedFromBases.end())
7115       return std::make_pair(nullptr, false);
7116 
7117     // This is an intermediary class.
7118     if (It->second)
7119       return std::make_pair(
7120           S.findInheritingConstructor(UseLoc, Ctor, It->second),
7121           It->second->constructsVirtualBase());
7122 
7123     // This is the base class from which the constructor was inherited.
7124     return std::make_pair(Ctor, false);
7125   }
7126 };
7127 
7128 /// Is the special member function which would be selected to perform the
7129 /// specified operation on the specified class type a constexpr constructor?
7130 static bool
7131 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7132                          Sema::CXXSpecialMember CSM, unsigned Quals,
7133                          bool ConstRHS,
7134                          CXXConstructorDecl *InheritedCtor = nullptr,
7135                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7136   // If we're inheriting a constructor, see if we need to call it for this base
7137   // class.
7138   if (InheritedCtor) {
7139     assert(CSM == Sema::CXXDefaultConstructor);
7140     auto BaseCtor =
7141         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7142     if (BaseCtor)
7143       return BaseCtor->isConstexpr();
7144   }
7145 
7146   if (CSM == Sema::CXXDefaultConstructor)
7147     return ClassDecl->hasConstexprDefaultConstructor();
7148   if (CSM == Sema::CXXDestructor)
7149     return ClassDecl->hasConstexprDestructor();
7150 
7151   Sema::SpecialMemberOverloadResult SMOR =
7152       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7153   if (!SMOR.getMethod())
7154     // A constructor we wouldn't select can't be "involved in initializing"
7155     // anything.
7156     return true;
7157   return SMOR.getMethod()->isConstexpr();
7158 }
7159 
7160 /// Determine whether the specified special member function would be constexpr
7161 /// if it were implicitly defined.
7162 static bool defaultedSpecialMemberIsConstexpr(
7163     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7164     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7165     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7166   if (!S.getLangOpts().CPlusPlus11)
7167     return false;
7168 
7169   // C++11 [dcl.constexpr]p4:
7170   // In the definition of a constexpr constructor [...]
7171   bool Ctor = true;
7172   switch (CSM) {
7173   case Sema::CXXDefaultConstructor:
7174     if (Inherited)
7175       break;
7176     // Since default constructor lookup is essentially trivial (and cannot
7177     // involve, for instance, template instantiation), we compute whether a
7178     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7179     //
7180     // This is important for performance; we need to know whether the default
7181     // constructor is constexpr to determine whether the type is a literal type.
7182     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7183 
7184   case Sema::CXXCopyConstructor:
7185   case Sema::CXXMoveConstructor:
7186     // For copy or move constructors, we need to perform overload resolution.
7187     break;
7188 
7189   case Sema::CXXCopyAssignment:
7190   case Sema::CXXMoveAssignment:
7191     if (!S.getLangOpts().CPlusPlus14)
7192       return false;
7193     // In C++1y, we need to perform overload resolution.
7194     Ctor = false;
7195     break;
7196 
7197   case Sema::CXXDestructor:
7198     return ClassDecl->defaultedDestructorIsConstexpr();
7199 
7200   case Sema::CXXInvalid:
7201     return false;
7202   }
7203 
7204   //   -- if the class is a non-empty union, or for each non-empty anonymous
7205   //      union member of a non-union class, exactly one non-static data member
7206   //      shall be initialized; [DR1359]
7207   //
7208   // If we squint, this is guaranteed, since exactly one non-static data member
7209   // will be initialized (if the constructor isn't deleted), we just don't know
7210   // which one.
7211   if (Ctor && ClassDecl->isUnion())
7212     return CSM == Sema::CXXDefaultConstructor
7213                ? ClassDecl->hasInClassInitializer() ||
7214                      !ClassDecl->hasVariantMembers()
7215                : true;
7216 
7217   //   -- the class shall not have any virtual base classes;
7218   if (Ctor && ClassDecl->getNumVBases())
7219     return false;
7220 
7221   // C++1y [class.copy]p26:
7222   //   -- [the class] is a literal type, and
7223   if (!Ctor && !ClassDecl->isLiteral())
7224     return false;
7225 
7226   //   -- every constructor involved in initializing [...] base class
7227   //      sub-objects shall be a constexpr constructor;
7228   //   -- the assignment operator selected to copy/move each direct base
7229   //      class is a constexpr function, and
7230   for (const auto &B : ClassDecl->bases()) {
7231     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7232     if (!BaseType) continue;
7233 
7234     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7235     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7236                                   InheritedCtor, Inherited))
7237       return false;
7238   }
7239 
7240   //   -- every constructor involved in initializing non-static data members
7241   //      [...] shall be a constexpr constructor;
7242   //   -- every non-static data member and base class sub-object shall be
7243   //      initialized
7244   //   -- for each non-static data member of X that is of class type (or array
7245   //      thereof), the assignment operator selected to copy/move that member is
7246   //      a constexpr function
7247   for (const auto *F : ClassDecl->fields()) {
7248     if (F->isInvalidDecl())
7249       continue;
7250     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7251       continue;
7252     QualType BaseType = S.Context.getBaseElementType(F->getType());
7253     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7254       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7255       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7256                                     BaseType.getCVRQualifiers(),
7257                                     ConstArg && !F->isMutable()))
7258         return false;
7259     } else if (CSM == Sema::CXXDefaultConstructor) {
7260       return false;
7261     }
7262   }
7263 
7264   // All OK, it's constexpr!
7265   return true;
7266 }
7267 
7268 namespace {
7269 /// RAII object to register a defaulted function as having its exception
7270 /// specification computed.
7271 struct ComputingExceptionSpec {
7272   Sema &S;
7273 
7274   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7275       : S(S) {
7276     Sema::CodeSynthesisContext Ctx;
7277     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7278     Ctx.PointOfInstantiation = Loc;
7279     Ctx.Entity = FD;
7280     S.pushCodeSynthesisContext(Ctx);
7281   }
7282   ~ComputingExceptionSpec() {
7283     S.popCodeSynthesisContext();
7284   }
7285 };
7286 }
7287 
7288 static Sema::ImplicitExceptionSpecification
7289 ComputeDefaultedSpecialMemberExceptionSpec(
7290     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7291     Sema::InheritedConstructorInfo *ICI);
7292 
7293 static Sema::ImplicitExceptionSpecification
7294 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7295                                         FunctionDecl *FD,
7296                                         Sema::DefaultedComparisonKind DCK);
7297 
7298 static Sema::ImplicitExceptionSpecification
7299 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7300   auto DFK = S.getDefaultedFunctionKind(FD);
7301   if (DFK.isSpecialMember())
7302     return ComputeDefaultedSpecialMemberExceptionSpec(
7303         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7304   if (DFK.isComparison())
7305     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7306                                                    DFK.asComparison());
7307 
7308   auto *CD = cast<CXXConstructorDecl>(FD);
7309   assert(CD->getInheritedConstructor() &&
7310          "only defaulted functions and inherited constructors have implicit "
7311          "exception specs");
7312   Sema::InheritedConstructorInfo ICI(
7313       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7314   return ComputeDefaultedSpecialMemberExceptionSpec(
7315       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7316 }
7317 
7318 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7319                                                             CXXMethodDecl *MD) {
7320   FunctionProtoType::ExtProtoInfo EPI;
7321 
7322   // Build an exception specification pointing back at this member.
7323   EPI.ExceptionSpec.Type = EST_Unevaluated;
7324   EPI.ExceptionSpec.SourceDecl = MD;
7325 
7326   // Set the calling convention to the default for C++ instance methods.
7327   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7328       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7329                                             /*IsCXXMethod=*/true));
7330   return EPI;
7331 }
7332 
7333 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7334   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7335   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7336     return;
7337 
7338   // Evaluate the exception specification.
7339   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7340   auto ESI = IES.getExceptionSpec();
7341 
7342   // Update the type of the special member to use it.
7343   UpdateExceptionSpec(FD, ESI);
7344 }
7345 
7346 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7347   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7348 
7349   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7350   if (!DefKind) {
7351     assert(FD->getDeclContext()->isDependentContext());
7352     return;
7353   }
7354 
7355   if (DefKind.isComparison())
7356     UnusedPrivateFields.clear();
7357 
7358   if (DefKind.isSpecialMember()
7359           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7360                                                   DefKind.asSpecialMember())
7361           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7362     FD->setInvalidDecl();
7363 }
7364 
7365 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7366                                                  CXXSpecialMember CSM) {
7367   CXXRecordDecl *RD = MD->getParent();
7368 
7369   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7370          "not an explicitly-defaulted special member");
7371 
7372   // Defer all checking for special members of a dependent type.
7373   if (RD->isDependentType())
7374     return false;
7375 
7376   // Whether this was the first-declared instance of the constructor.
7377   // This affects whether we implicitly add an exception spec and constexpr.
7378   bool First = MD == MD->getCanonicalDecl();
7379 
7380   bool HadError = false;
7381 
7382   // C++11 [dcl.fct.def.default]p1:
7383   //   A function that is explicitly defaulted shall
7384   //     -- be a special member function [...] (checked elsewhere),
7385   //     -- have the same type (except for ref-qualifiers, and except that a
7386   //        copy operation can take a non-const reference) as an implicit
7387   //        declaration, and
7388   //     -- not have default arguments.
7389   // C++2a changes the second bullet to instead delete the function if it's
7390   // defaulted on its first declaration, unless it's "an assignment operator,
7391   // and its return type differs or its parameter type is not a reference".
7392   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7393   bool ShouldDeleteForTypeMismatch = false;
7394   unsigned ExpectedParams = 1;
7395   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7396     ExpectedParams = 0;
7397   if (MD->getNumParams() != ExpectedParams) {
7398     // This checks for default arguments: a copy or move constructor with a
7399     // default argument is classified as a default constructor, and assignment
7400     // operations and destructors can't have default arguments.
7401     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7402       << CSM << MD->getSourceRange();
7403     HadError = true;
7404   } else if (MD->isVariadic()) {
7405     if (DeleteOnTypeMismatch)
7406       ShouldDeleteForTypeMismatch = true;
7407     else {
7408       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7409         << CSM << MD->getSourceRange();
7410       HadError = true;
7411     }
7412   }
7413 
7414   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7415 
7416   bool CanHaveConstParam = false;
7417   if (CSM == CXXCopyConstructor)
7418     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7419   else if (CSM == CXXCopyAssignment)
7420     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7421 
7422   QualType ReturnType = Context.VoidTy;
7423   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7424     // Check for return type matching.
7425     ReturnType = Type->getReturnType();
7426 
7427     QualType DeclType = Context.getTypeDeclType(RD);
7428     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7429     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7430 
7431     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7432       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7433         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7434       HadError = true;
7435     }
7436 
7437     // A defaulted special member cannot have cv-qualifiers.
7438     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7439       if (DeleteOnTypeMismatch)
7440         ShouldDeleteForTypeMismatch = true;
7441       else {
7442         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7443           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7444         HadError = true;
7445       }
7446     }
7447   }
7448 
7449   // Check for parameter type matching.
7450   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7451   bool HasConstParam = false;
7452   if (ExpectedParams && ArgType->isReferenceType()) {
7453     // Argument must be reference to possibly-const T.
7454     QualType ReferentType = ArgType->getPointeeType();
7455     HasConstParam = ReferentType.isConstQualified();
7456 
7457     if (ReferentType.isVolatileQualified()) {
7458       if (DeleteOnTypeMismatch)
7459         ShouldDeleteForTypeMismatch = true;
7460       else {
7461         Diag(MD->getLocation(),
7462              diag::err_defaulted_special_member_volatile_param) << CSM;
7463         HadError = true;
7464       }
7465     }
7466 
7467     if (HasConstParam && !CanHaveConstParam) {
7468       if (DeleteOnTypeMismatch)
7469         ShouldDeleteForTypeMismatch = true;
7470       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7471         Diag(MD->getLocation(),
7472              diag::err_defaulted_special_member_copy_const_param)
7473           << (CSM == CXXCopyAssignment);
7474         // FIXME: Explain why this special member can't be const.
7475         HadError = true;
7476       } else {
7477         Diag(MD->getLocation(),
7478              diag::err_defaulted_special_member_move_const_param)
7479           << (CSM == CXXMoveAssignment);
7480         HadError = true;
7481       }
7482     }
7483   } else if (ExpectedParams) {
7484     // A copy assignment operator can take its argument by value, but a
7485     // defaulted one cannot.
7486     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7487     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7488     HadError = true;
7489   }
7490 
7491   // C++11 [dcl.fct.def.default]p2:
7492   //   An explicitly-defaulted function may be declared constexpr only if it
7493   //   would have been implicitly declared as constexpr,
7494   // Do not apply this rule to members of class templates, since core issue 1358
7495   // makes such functions always instantiate to constexpr functions. For
7496   // functions which cannot be constexpr (for non-constructors in C++11 and for
7497   // destructors in C++14 and C++17), this is checked elsewhere.
7498   //
7499   // FIXME: This should not apply if the member is deleted.
7500   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7501                                                      HasConstParam);
7502   if ((getLangOpts().CPlusPlus20 ||
7503        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7504                                   : isa<CXXConstructorDecl>(MD))) &&
7505       MD->isConstexpr() && !Constexpr &&
7506       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7507     Diag(MD->getBeginLoc(), MD->isConsteval()
7508                                 ? diag::err_incorrect_defaulted_consteval
7509                                 : diag::err_incorrect_defaulted_constexpr)
7510         << CSM;
7511     // FIXME: Explain why the special member can't be constexpr.
7512     HadError = true;
7513   }
7514 
7515   if (First) {
7516     // C++2a [dcl.fct.def.default]p3:
7517     //   If a function is explicitly defaulted on its first declaration, it is
7518     //   implicitly considered to be constexpr if the implicit declaration
7519     //   would be.
7520     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7521                                           ? ConstexprSpecKind::Consteval
7522                                           : ConstexprSpecKind::Constexpr)
7523                                    : ConstexprSpecKind::Unspecified);
7524 
7525     if (!Type->hasExceptionSpec()) {
7526       // C++2a [except.spec]p3:
7527       //   If a declaration of a function does not have a noexcept-specifier
7528       //   [and] is defaulted on its first declaration, [...] the exception
7529       //   specification is as specified below
7530       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7531       EPI.ExceptionSpec.Type = EST_Unevaluated;
7532       EPI.ExceptionSpec.SourceDecl = MD;
7533       MD->setType(Context.getFunctionType(ReturnType,
7534                                           llvm::makeArrayRef(&ArgType,
7535                                                              ExpectedParams),
7536                                           EPI));
7537     }
7538   }
7539 
7540   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7541     if (First) {
7542       SetDeclDeleted(MD, MD->getLocation());
7543       if (!inTemplateInstantiation() && !HadError) {
7544         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7545         if (ShouldDeleteForTypeMismatch) {
7546           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7547         } else {
7548           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7549         }
7550       }
7551       if (ShouldDeleteForTypeMismatch && !HadError) {
7552         Diag(MD->getLocation(),
7553              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7554       }
7555     } else {
7556       // C++11 [dcl.fct.def.default]p4:
7557       //   [For a] user-provided explicitly-defaulted function [...] if such a
7558       //   function is implicitly defined as deleted, the program is ill-formed.
7559       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7560       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7561       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7562       HadError = true;
7563     }
7564   }
7565 
7566   return HadError;
7567 }
7568 
7569 namespace {
7570 /// Helper class for building and checking a defaulted comparison.
7571 ///
7572 /// Defaulted functions are built in two phases:
7573 ///
7574 ///  * First, the set of operations that the function will perform are
7575 ///    identified, and some of them are checked. If any of the checked
7576 ///    operations is invalid in certain ways, the comparison function is
7577 ///    defined as deleted and no body is built.
7578 ///  * Then, if the function is not defined as deleted, the body is built.
7579 ///
7580 /// This is accomplished by performing two visitation steps over the eventual
7581 /// body of the function.
7582 template<typename Derived, typename ResultList, typename Result,
7583          typename Subobject>
7584 class DefaultedComparisonVisitor {
7585 public:
7586   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7587 
7588   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7589                              DefaultedComparisonKind DCK)
7590       : S(S), RD(RD), FD(FD), DCK(DCK) {
7591     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7592       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7593       // UnresolvedSet to avoid this copy.
7594       Fns.assign(Info->getUnqualifiedLookups().begin(),
7595                  Info->getUnqualifiedLookups().end());
7596     }
7597   }
7598 
7599   ResultList visit() {
7600     // The type of an lvalue naming a parameter of this function.
7601     QualType ParamLvalType =
7602         FD->getParamDecl(0)->getType().getNonReferenceType();
7603 
7604     ResultList Results;
7605 
7606     switch (DCK) {
7607     case DefaultedComparisonKind::None:
7608       llvm_unreachable("not a defaulted comparison");
7609 
7610     case DefaultedComparisonKind::Equal:
7611     case DefaultedComparisonKind::ThreeWay:
7612       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7613       return Results;
7614 
7615     case DefaultedComparisonKind::NotEqual:
7616     case DefaultedComparisonKind::Relational:
7617       Results.add(getDerived().visitExpandedSubobject(
7618           ParamLvalType, getDerived().getCompleteObject()));
7619       return Results;
7620     }
7621     llvm_unreachable("");
7622   }
7623 
7624 protected:
7625   Derived &getDerived() { return static_cast<Derived&>(*this); }
7626 
7627   /// Visit the expanded list of subobjects of the given type, as specified in
7628   /// C++2a [class.compare.default].
7629   ///
7630   /// \return \c true if the ResultList object said we're done, \c false if not.
7631   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7632                        Qualifiers Quals) {
7633     // C++2a [class.compare.default]p4:
7634     //   The direct base class subobjects of C
7635     for (CXXBaseSpecifier &Base : Record->bases())
7636       if (Results.add(getDerived().visitSubobject(
7637               S.Context.getQualifiedType(Base.getType(), Quals),
7638               getDerived().getBase(&Base))))
7639         return true;
7640 
7641     //   followed by the non-static data members of C
7642     for (FieldDecl *Field : Record->fields()) {
7643       // Recursively expand anonymous structs.
7644       if (Field->isAnonymousStructOrUnion()) {
7645         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7646                             Quals))
7647           return true;
7648         continue;
7649       }
7650 
7651       // Figure out the type of an lvalue denoting this field.
7652       Qualifiers FieldQuals = Quals;
7653       if (Field->isMutable())
7654         FieldQuals.removeConst();
7655       QualType FieldType =
7656           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7657 
7658       if (Results.add(getDerived().visitSubobject(
7659               FieldType, getDerived().getField(Field))))
7660         return true;
7661     }
7662 
7663     //   form a list of subobjects.
7664     return false;
7665   }
7666 
7667   Result visitSubobject(QualType Type, Subobject Subobj) {
7668     //   In that list, any subobject of array type is recursively expanded
7669     const ArrayType *AT = S.Context.getAsArrayType(Type);
7670     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7671       return getDerived().visitSubobjectArray(CAT->getElementType(),
7672                                               CAT->getSize(), Subobj);
7673     return getDerived().visitExpandedSubobject(Type, Subobj);
7674   }
7675 
7676   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7677                              Subobject Subobj) {
7678     return getDerived().visitSubobject(Type, Subobj);
7679   }
7680 
7681 protected:
7682   Sema &S;
7683   CXXRecordDecl *RD;
7684   FunctionDecl *FD;
7685   DefaultedComparisonKind DCK;
7686   UnresolvedSet<16> Fns;
7687 };
7688 
7689 /// Information about a defaulted comparison, as determined by
7690 /// DefaultedComparisonAnalyzer.
7691 struct DefaultedComparisonInfo {
7692   bool Deleted = false;
7693   bool Constexpr = true;
7694   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7695 
7696   static DefaultedComparisonInfo deleted() {
7697     DefaultedComparisonInfo Deleted;
7698     Deleted.Deleted = true;
7699     return Deleted;
7700   }
7701 
7702   bool add(const DefaultedComparisonInfo &R) {
7703     Deleted |= R.Deleted;
7704     Constexpr &= R.Constexpr;
7705     Category = commonComparisonType(Category, R.Category);
7706     return Deleted;
7707   }
7708 };
7709 
7710 /// An element in the expanded list of subobjects of a defaulted comparison, as
7711 /// specified in C++2a [class.compare.default]p4.
7712 struct DefaultedComparisonSubobject {
7713   enum { CompleteObject, Member, Base } Kind;
7714   NamedDecl *Decl;
7715   SourceLocation Loc;
7716 };
7717 
7718 /// A visitor over the notional body of a defaulted comparison that determines
7719 /// whether that body would be deleted or constexpr.
7720 class DefaultedComparisonAnalyzer
7721     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7722                                         DefaultedComparisonInfo,
7723                                         DefaultedComparisonInfo,
7724                                         DefaultedComparisonSubobject> {
7725 public:
7726   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7727 
7728 private:
7729   DiagnosticKind Diagnose;
7730 
7731 public:
7732   using Base = DefaultedComparisonVisitor;
7733   using Result = DefaultedComparisonInfo;
7734   using Subobject = DefaultedComparisonSubobject;
7735 
7736   friend Base;
7737 
7738   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7739                               DefaultedComparisonKind DCK,
7740                               DiagnosticKind Diagnose = NoDiagnostics)
7741       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7742 
7743   Result visit() {
7744     if ((DCK == DefaultedComparisonKind::Equal ||
7745          DCK == DefaultedComparisonKind::ThreeWay) &&
7746         RD->hasVariantMembers()) {
7747       // C++2a [class.compare.default]p2 [P2002R0]:
7748       //   A defaulted comparison operator function for class C is defined as
7749       //   deleted if [...] C has variant members.
7750       if (Diagnose == ExplainDeleted) {
7751         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7752           << FD << RD->isUnion() << RD;
7753       }
7754       return Result::deleted();
7755     }
7756 
7757     return Base::visit();
7758   }
7759 
7760 private:
7761   Subobject getCompleteObject() {
7762     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7763   }
7764 
7765   Subobject getBase(CXXBaseSpecifier *Base) {
7766     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7767                      Base->getBaseTypeLoc()};
7768   }
7769 
7770   Subobject getField(FieldDecl *Field) {
7771     return Subobject{Subobject::Member, Field, Field->getLocation()};
7772   }
7773 
7774   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7775     // C++2a [class.compare.default]p2 [P2002R0]:
7776     //   A defaulted <=> or == operator function for class C is defined as
7777     //   deleted if any non-static data member of C is of reference type
7778     if (Type->isReferenceType()) {
7779       if (Diagnose == ExplainDeleted) {
7780         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7781             << FD << RD;
7782       }
7783       return Result::deleted();
7784     }
7785 
7786     // [...] Let xi be an lvalue denoting the ith element [...]
7787     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7788     Expr *Args[] = {&Xi, &Xi};
7789 
7790     // All operators start by trying to apply that same operator recursively.
7791     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7792     assert(OO != OO_None && "not an overloaded operator!");
7793     return visitBinaryOperator(OO, Args, Subobj);
7794   }
7795 
7796   Result
7797   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7798                       Subobject Subobj,
7799                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7800     // Note that there is no need to consider rewritten candidates here if
7801     // we've already found there is no viable 'operator<=>' candidate (and are
7802     // considering synthesizing a '<=>' from '==' and '<').
7803     OverloadCandidateSet CandidateSet(
7804         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7805         OverloadCandidateSet::OperatorRewriteInfo(
7806             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7807 
7808     /// C++2a [class.compare.default]p1 [P2002R0]:
7809     ///   [...] the defaulted function itself is never a candidate for overload
7810     ///   resolution [...]
7811     CandidateSet.exclude(FD);
7812 
7813     if (Args[0]->getType()->isOverloadableType())
7814       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7815     else
7816       // FIXME: We determine whether this is a valid expression by checking to
7817       // see if there's a viable builtin operator candidate for it. That isn't
7818       // really what the rules ask us to do, but should give the right results.
7819       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7820 
7821     Result R;
7822 
7823     OverloadCandidateSet::iterator Best;
7824     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7825     case OR_Success: {
7826       // C++2a [class.compare.secondary]p2 [P2002R0]:
7827       //   The operator function [...] is defined as deleted if [...] the
7828       //   candidate selected by overload resolution is not a rewritten
7829       //   candidate.
7830       if ((DCK == DefaultedComparisonKind::NotEqual ||
7831            DCK == DefaultedComparisonKind::Relational) &&
7832           !Best->RewriteKind) {
7833         if (Diagnose == ExplainDeleted) {
7834           if (Best->Function) {
7835             S.Diag(Best->Function->getLocation(),
7836                    diag::note_defaulted_comparison_not_rewritten_callee)
7837                 << FD;
7838           } else {
7839             assert(Best->Conversions.size() == 2 &&
7840                    Best->Conversions[0].isUserDefined() &&
7841                    "non-user-defined conversion from class to built-in "
7842                    "comparison");
7843             S.Diag(Best->Conversions[0]
7844                        .UserDefined.FoundConversionFunction.getDecl()
7845                        ->getLocation(),
7846                    diag::note_defaulted_comparison_not_rewritten_conversion)
7847                 << FD;
7848           }
7849         }
7850         return Result::deleted();
7851       }
7852 
7853       // Throughout C++2a [class.compare]: if overload resolution does not
7854       // result in a usable function, the candidate function is defined as
7855       // deleted. This requires that we selected an accessible function.
7856       //
7857       // Note that this only considers the access of the function when named
7858       // within the type of the subobject, and not the access path for any
7859       // derived-to-base conversion.
7860       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7861       if (ArgClass && Best->FoundDecl.getDecl() &&
7862           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7863         QualType ObjectType = Subobj.Kind == Subobject::Member
7864                                   ? Args[0]->getType()
7865                                   : S.Context.getRecordType(RD);
7866         if (!S.isMemberAccessibleForDeletion(
7867                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7868                 Diagnose == ExplainDeleted
7869                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7870                           << FD << Subobj.Kind << Subobj.Decl
7871                     : S.PDiag()))
7872           return Result::deleted();
7873       }
7874 
7875       bool NeedsDeducing =
7876           OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7877 
7878       if (FunctionDecl *BestFD = Best->Function) {
7879         // C++2a [class.compare.default]p3 [P2002R0]:
7880         //   A defaulted comparison function is constexpr-compatible if
7881         //   [...] no overlod resolution performed [...] results in a
7882         //   non-constexpr function.
7883         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7884         // If it's not constexpr, explain why not.
7885         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7886           if (Subobj.Kind != Subobject::CompleteObject)
7887             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7888               << Subobj.Kind << Subobj.Decl;
7889           S.Diag(BestFD->getLocation(),
7890                  diag::note_defaulted_comparison_not_constexpr_here);
7891           // Bail out after explaining; we don't want any more notes.
7892           return Result::deleted();
7893         }
7894         R.Constexpr &= BestFD->isConstexpr();
7895 
7896         if (NeedsDeducing) {
7897           // If any callee has an undeduced return type, deduce it now.
7898           // FIXME: It's not clear how a failure here should be handled. For
7899           // now, we produce an eager diagnostic, because that is forward
7900           // compatible with most (all?) other reasonable options.
7901           if (BestFD->getReturnType()->isUndeducedType() &&
7902               S.DeduceReturnType(BestFD, FD->getLocation(),
7903                                  /*Diagnose=*/false)) {
7904             // Don't produce a duplicate error when asked to explain why the
7905             // comparison is deleted: we diagnosed that when initially checking
7906             // the defaulted operator.
7907             if (Diagnose == NoDiagnostics) {
7908               S.Diag(
7909                   FD->getLocation(),
7910                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7911                   << Subobj.Kind << Subobj.Decl;
7912               S.Diag(
7913                   Subobj.Loc,
7914                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7915                   << Subobj.Kind << Subobj.Decl;
7916               S.Diag(BestFD->getLocation(),
7917                      diag::note_defaulted_comparison_cannot_deduce_callee)
7918                   << Subobj.Kind << Subobj.Decl;
7919             }
7920             return Result::deleted();
7921           }
7922           auto *Info = S.Context.CompCategories.lookupInfoForType(
7923               BestFD->getCallResultType());
7924           if (!Info) {
7925             if (Diagnose == ExplainDeleted) {
7926               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7927                   << Subobj.Kind << Subobj.Decl
7928                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7929               S.Diag(BestFD->getLocation(),
7930                      diag::note_defaulted_comparison_cannot_deduce_callee)
7931                   << Subobj.Kind << Subobj.Decl;
7932             }
7933             return Result::deleted();
7934           }
7935           R.Category = Info->Kind;
7936         }
7937       } else {
7938         QualType T = Best->BuiltinParamTypes[0];
7939         assert(T == Best->BuiltinParamTypes[1] &&
7940                "builtin comparison for different types?");
7941         assert(Best->BuiltinParamTypes[2].isNull() &&
7942                "invalid builtin comparison");
7943 
7944         if (NeedsDeducing) {
7945           Optional<ComparisonCategoryType> Cat =
7946               getComparisonCategoryForBuiltinCmp(T);
7947           assert(Cat && "no category for builtin comparison?");
7948           R.Category = *Cat;
7949         }
7950       }
7951 
7952       // Note that we might be rewriting to a different operator. That call is
7953       // not considered until we come to actually build the comparison function.
7954       break;
7955     }
7956 
7957     case OR_Ambiguous:
7958       if (Diagnose == ExplainDeleted) {
7959         unsigned Kind = 0;
7960         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7961           Kind = OO == OO_EqualEqual ? 1 : 2;
7962         CandidateSet.NoteCandidates(
7963             PartialDiagnosticAt(
7964                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7965                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7966             S, OCD_AmbiguousCandidates, Args);
7967       }
7968       R = Result::deleted();
7969       break;
7970 
7971     case OR_Deleted:
7972       if (Diagnose == ExplainDeleted) {
7973         if ((DCK == DefaultedComparisonKind::NotEqual ||
7974              DCK == DefaultedComparisonKind::Relational) &&
7975             !Best->RewriteKind) {
7976           S.Diag(Best->Function->getLocation(),
7977                  diag::note_defaulted_comparison_not_rewritten_callee)
7978               << FD;
7979         } else {
7980           S.Diag(Subobj.Loc,
7981                  diag::note_defaulted_comparison_calls_deleted)
7982               << FD << Subobj.Kind << Subobj.Decl;
7983           S.NoteDeletedFunction(Best->Function);
7984         }
7985       }
7986       R = Result::deleted();
7987       break;
7988 
7989     case OR_No_Viable_Function:
7990       // If there's no usable candidate, we're done unless we can rewrite a
7991       // '<=>' in terms of '==' and '<'.
7992       if (OO == OO_Spaceship &&
7993           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7994         // For any kind of comparison category return type, we need a usable
7995         // '==' and a usable '<'.
7996         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7997                                        &CandidateSet)))
7998           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7999         break;
8000       }
8001 
8002       if (Diagnose == ExplainDeleted) {
8003         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8004             << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
8005 
8006         // For a three-way comparison, list both the candidates for the
8007         // original operator and the candidates for the synthesized operator.
8008         if (SpaceshipCandidates) {
8009           SpaceshipCandidates->NoteCandidates(
8010               S, Args,
8011               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8012                                                       Args, FD->getLocation()));
8013           S.Diag(Subobj.Loc,
8014                  diag::note_defaulted_comparison_no_viable_function_synthesized)
8015               << (OO == OO_EqualEqual ? 0 : 1);
8016         }
8017 
8018         CandidateSet.NoteCandidates(
8019             S, Args,
8020             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8021                                             FD->getLocation()));
8022       }
8023       R = Result::deleted();
8024       break;
8025     }
8026 
8027     return R;
8028   }
8029 };
8030 
8031 /// A list of statements.
8032 struct StmtListResult {
8033   bool IsInvalid = false;
8034   llvm::SmallVector<Stmt*, 16> Stmts;
8035 
8036   bool add(const StmtResult &S) {
8037     IsInvalid |= S.isInvalid();
8038     if (IsInvalid)
8039       return true;
8040     Stmts.push_back(S.get());
8041     return false;
8042   }
8043 };
8044 
8045 /// A visitor over the notional body of a defaulted comparison that synthesizes
8046 /// the actual body.
8047 class DefaultedComparisonSynthesizer
8048     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8049                                         StmtListResult, StmtResult,
8050                                         std::pair<ExprResult, ExprResult>> {
8051   SourceLocation Loc;
8052   unsigned ArrayDepth = 0;
8053 
8054 public:
8055   using Base = DefaultedComparisonVisitor;
8056   using ExprPair = std::pair<ExprResult, ExprResult>;
8057 
8058   friend Base;
8059 
8060   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8061                                  DefaultedComparisonKind DCK,
8062                                  SourceLocation BodyLoc)
8063       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8064 
8065   /// Build a suitable function body for this defaulted comparison operator.
8066   StmtResult build() {
8067     Sema::CompoundScopeRAII CompoundScope(S);
8068 
8069     StmtListResult Stmts = visit();
8070     if (Stmts.IsInvalid)
8071       return StmtError();
8072 
8073     ExprResult RetVal;
8074     switch (DCK) {
8075     case DefaultedComparisonKind::None:
8076       llvm_unreachable("not a defaulted comparison");
8077 
8078     case DefaultedComparisonKind::Equal: {
8079       // C++2a [class.eq]p3:
8080       //   [...] compar[e] the corresponding elements [...] until the first
8081       //   index i where xi == yi yields [...] false. If no such index exists,
8082       //   V is true. Otherwise, V is false.
8083       //
8084       // Join the comparisons with '&&'s and return the result. Use a right
8085       // fold (traversing the conditions right-to-left), because that
8086       // short-circuits more naturally.
8087       auto OldStmts = std::move(Stmts.Stmts);
8088       Stmts.Stmts.clear();
8089       ExprResult CmpSoFar;
8090       // Finish a particular comparison chain.
8091       auto FinishCmp = [&] {
8092         if (Expr *Prior = CmpSoFar.get()) {
8093           // Convert the last expression to 'return ...;'
8094           if (RetVal.isUnset() && Stmts.Stmts.empty())
8095             RetVal = CmpSoFar;
8096           // Convert any prior comparison to 'if (!(...)) return false;'
8097           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8098             return true;
8099           CmpSoFar = ExprResult();
8100         }
8101         return false;
8102       };
8103       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8104         Expr *E = dyn_cast<Expr>(EAsStmt);
8105         if (!E) {
8106           // Found an array comparison.
8107           if (FinishCmp() || Stmts.add(EAsStmt))
8108             return StmtError();
8109           continue;
8110         }
8111 
8112         if (CmpSoFar.isUnset()) {
8113           CmpSoFar = E;
8114           continue;
8115         }
8116         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8117         if (CmpSoFar.isInvalid())
8118           return StmtError();
8119       }
8120       if (FinishCmp())
8121         return StmtError();
8122       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8123       //   If no such index exists, V is true.
8124       if (RetVal.isUnset())
8125         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8126       break;
8127     }
8128 
8129     case DefaultedComparisonKind::ThreeWay: {
8130       // Per C++2a [class.spaceship]p3, as a fallback add:
8131       // return static_cast<R>(std::strong_ordering::equal);
8132       QualType StrongOrdering = S.CheckComparisonCategoryType(
8133           ComparisonCategoryType::StrongOrdering, Loc,
8134           Sema::ComparisonCategoryUsage::DefaultedOperator);
8135       if (StrongOrdering.isNull())
8136         return StmtError();
8137       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8138                              .getValueInfo(ComparisonCategoryResult::Equal)
8139                              ->VD;
8140       RetVal = getDecl(EqualVD);
8141       if (RetVal.isInvalid())
8142         return StmtError();
8143       RetVal = buildStaticCastToR(RetVal.get());
8144       break;
8145     }
8146 
8147     case DefaultedComparisonKind::NotEqual:
8148     case DefaultedComparisonKind::Relational:
8149       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8150       break;
8151     }
8152 
8153     // Build the final return statement.
8154     if (RetVal.isInvalid())
8155       return StmtError();
8156     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8157     if (ReturnStmt.isInvalid())
8158       return StmtError();
8159     Stmts.Stmts.push_back(ReturnStmt.get());
8160 
8161     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8162   }
8163 
8164 private:
8165   ExprResult getDecl(ValueDecl *VD) {
8166     return S.BuildDeclarationNameExpr(
8167         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8168   }
8169 
8170   ExprResult getParam(unsigned I) {
8171     ParmVarDecl *PD = FD->getParamDecl(I);
8172     return getDecl(PD);
8173   }
8174 
8175   ExprPair getCompleteObject() {
8176     unsigned Param = 0;
8177     ExprResult LHS;
8178     if (isa<CXXMethodDecl>(FD)) {
8179       // LHS is '*this'.
8180       LHS = S.ActOnCXXThis(Loc);
8181       if (!LHS.isInvalid())
8182         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8183     } else {
8184       LHS = getParam(Param++);
8185     }
8186     ExprResult RHS = getParam(Param++);
8187     assert(Param == FD->getNumParams());
8188     return {LHS, RHS};
8189   }
8190 
8191   ExprPair getBase(CXXBaseSpecifier *Base) {
8192     ExprPair Obj = getCompleteObject();
8193     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8194       return {ExprError(), ExprError()};
8195     CXXCastPath Path = {Base};
8196     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8197                                 CK_DerivedToBase, VK_LValue, &Path),
8198             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8199                                 CK_DerivedToBase, VK_LValue, &Path)};
8200   }
8201 
8202   ExprPair getField(FieldDecl *Field) {
8203     ExprPair Obj = getCompleteObject();
8204     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8205       return {ExprError(), ExprError()};
8206 
8207     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8208     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8209     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8210                                       CXXScopeSpec(), Field, Found, NameInfo),
8211             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8212                                       CXXScopeSpec(), Field, Found, NameInfo)};
8213   }
8214 
8215   // FIXME: When expanding a subobject, register a note in the code synthesis
8216   // stack to say which subobject we're comparing.
8217 
8218   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8219     if (Cond.isInvalid())
8220       return StmtError();
8221 
8222     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8223     if (NotCond.isInvalid())
8224       return StmtError();
8225 
8226     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8227     assert(!False.isInvalid() && "should never fail");
8228     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8229     if (ReturnFalse.isInvalid())
8230       return StmtError();
8231 
8232     return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8233                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8234                                           Sema::ConditionKind::Boolean),
8235                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8236   }
8237 
8238   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8239                                  ExprPair Subobj) {
8240     QualType SizeType = S.Context.getSizeType();
8241     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8242 
8243     // Build 'size_t i$n = 0'.
8244     IdentifierInfo *IterationVarName = nullptr;
8245     {
8246       SmallString<8> Str;
8247       llvm::raw_svector_ostream OS(Str);
8248       OS << "i" << ArrayDepth;
8249       IterationVarName = &S.Context.Idents.get(OS.str());
8250     }
8251     VarDecl *IterationVar = VarDecl::Create(
8252         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8253         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8254     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8255     IterationVar->setInit(
8256         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8257     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8258 
8259     auto IterRef = [&] {
8260       ExprResult Ref = S.BuildDeclarationNameExpr(
8261           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8262           IterationVar);
8263       assert(!Ref.isInvalid() && "can't reference our own variable?");
8264       return Ref.get();
8265     };
8266 
8267     // Build 'i$n != Size'.
8268     ExprResult Cond = S.CreateBuiltinBinOp(
8269         Loc, BO_NE, IterRef(),
8270         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8271     assert(!Cond.isInvalid() && "should never fail");
8272 
8273     // Build '++i$n'.
8274     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8275     assert(!Inc.isInvalid() && "should never fail");
8276 
8277     // Build 'a[i$n]' and 'b[i$n]'.
8278     auto Index = [&](ExprResult E) {
8279       if (E.isInvalid())
8280         return ExprError();
8281       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8282     };
8283     Subobj.first = Index(Subobj.first);
8284     Subobj.second = Index(Subobj.second);
8285 
8286     // Compare the array elements.
8287     ++ArrayDepth;
8288     StmtResult Substmt = visitSubobject(Type, Subobj);
8289     --ArrayDepth;
8290 
8291     if (Substmt.isInvalid())
8292       return StmtError();
8293 
8294     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8295     // For outer levels or for an 'operator<=>' we already have a suitable
8296     // statement that returns as necessary.
8297     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8298       assert(DCK == DefaultedComparisonKind::Equal &&
8299              "should have non-expression statement");
8300       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8301       if (Substmt.isInvalid())
8302         return StmtError();
8303     }
8304 
8305     // Build 'for (...) ...'
8306     return S.ActOnForStmt(Loc, Loc, Init,
8307                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8308                                            Sema::ConditionKind::Boolean),
8309                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8310                           Substmt.get());
8311   }
8312 
8313   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8314     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8315       return StmtError();
8316 
8317     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8318     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8319     ExprResult Op;
8320     if (Type->isOverloadableType())
8321       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8322                                    Obj.second.get(), /*PerformADL=*/true,
8323                                    /*AllowRewrittenCandidates=*/true, FD);
8324     else
8325       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8326     if (Op.isInvalid())
8327       return StmtError();
8328 
8329     switch (DCK) {
8330     case DefaultedComparisonKind::None:
8331       llvm_unreachable("not a defaulted comparison");
8332 
8333     case DefaultedComparisonKind::Equal:
8334       // Per C++2a [class.eq]p2, each comparison is individually contextually
8335       // converted to bool.
8336       Op = S.PerformContextuallyConvertToBool(Op.get());
8337       if (Op.isInvalid())
8338         return StmtError();
8339       return Op.get();
8340 
8341     case DefaultedComparisonKind::ThreeWay: {
8342       // Per C++2a [class.spaceship]p3, form:
8343       //   if (R cmp = static_cast<R>(op); cmp != 0)
8344       //     return cmp;
8345       QualType R = FD->getReturnType();
8346       Op = buildStaticCastToR(Op.get());
8347       if (Op.isInvalid())
8348         return StmtError();
8349 
8350       // R cmp = ...;
8351       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8352       VarDecl *VD =
8353           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8354                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8355       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8356       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8357 
8358       // cmp != 0
8359       ExprResult VDRef = getDecl(VD);
8360       if (VDRef.isInvalid())
8361         return StmtError();
8362       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8363       Expr *Zero =
8364           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8365       ExprResult Comp;
8366       if (VDRef.get()->getType()->isOverloadableType())
8367         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8368                                        true, FD);
8369       else
8370         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8371       if (Comp.isInvalid())
8372         return StmtError();
8373       Sema::ConditionResult Cond = S.ActOnCondition(
8374           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8375       if (Cond.isInvalid())
8376         return StmtError();
8377 
8378       // return cmp;
8379       VDRef = getDecl(VD);
8380       if (VDRef.isInvalid())
8381         return StmtError();
8382       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8383       if (ReturnStmt.isInvalid())
8384         return StmtError();
8385 
8386       // if (...)
8387       return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8388                            Loc, ReturnStmt.get(),
8389                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8390     }
8391 
8392     case DefaultedComparisonKind::NotEqual:
8393     case DefaultedComparisonKind::Relational:
8394       // C++2a [class.compare.secondary]p2:
8395       //   Otherwise, the operator function yields x @ y.
8396       return Op.get();
8397     }
8398     llvm_unreachable("");
8399   }
8400 
8401   /// Build "static_cast<R>(E)".
8402   ExprResult buildStaticCastToR(Expr *E) {
8403     QualType R = FD->getReturnType();
8404     assert(!R->isUndeducedType() && "type should have been deduced already");
8405 
8406     // Don't bother forming a no-op cast in the common case.
8407     if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8408       return E;
8409     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8410                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8411                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8412   }
8413 };
8414 }
8415 
8416 /// Perform the unqualified lookups that might be needed to form a defaulted
8417 /// comparison function for the given operator.
8418 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8419                                                   UnresolvedSetImpl &Operators,
8420                                                   OverloadedOperatorKind Op) {
8421   auto Lookup = [&](OverloadedOperatorKind OO) {
8422     Self.LookupOverloadedOperatorName(OO, S, Operators);
8423   };
8424 
8425   // Every defaulted operator looks up itself.
8426   Lookup(Op);
8427   // ... and the rewritten form of itself, if any.
8428   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8429     Lookup(ExtraOp);
8430 
8431   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8432   // synthesize a three-way comparison from '<' and '=='. In a dependent
8433   // context, we also need to look up '==' in case we implicitly declare a
8434   // defaulted 'operator=='.
8435   if (Op == OO_Spaceship) {
8436     Lookup(OO_ExclaimEqual);
8437     Lookup(OO_Less);
8438     Lookup(OO_EqualEqual);
8439   }
8440 }
8441 
8442 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8443                                               DefaultedComparisonKind DCK) {
8444   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8445 
8446   // Perform any unqualified lookups we're going to need to default this
8447   // function.
8448   if (S) {
8449     UnresolvedSet<32> Operators;
8450     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8451                                           FD->getOverloadedOperator());
8452     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8453         Context, Operators.pairs()));
8454   }
8455 
8456   // C++2a [class.compare.default]p1:
8457   //   A defaulted comparison operator function for some class C shall be a
8458   //   non-template function declared in the member-specification of C that is
8459   //    -- a non-static const member of C having one parameter of type
8460   //       const C&, or
8461   //    -- a friend of C having two parameters of type const C& or two
8462   //       parameters of type C.
8463 
8464   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8465   bool IsMethod = isa<CXXMethodDecl>(FD);
8466   if (IsMethod) {
8467     auto *MD = cast<CXXMethodDecl>(FD);
8468     assert(!MD->isStatic() && "comparison function cannot be a static member");
8469 
8470     // If we're out-of-class, this is the class we're comparing.
8471     if (!RD)
8472       RD = MD->getParent();
8473 
8474     if (!MD->isConst()) {
8475       SourceLocation InsertLoc;
8476       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8477         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8478       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8479       // corresponding defaulted 'operator<=>' already.
8480       if (!MD->isImplicit()) {
8481         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8482             << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8483       }
8484 
8485       // Add the 'const' to the type to recover.
8486       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8487       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8488       EPI.TypeQuals.addConst();
8489       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8490                                           FPT->getParamTypes(), EPI));
8491     }
8492   }
8493 
8494   if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8495     // Let's not worry about using a variadic template pack here -- who would do
8496     // such a thing?
8497     Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8498         << int(IsMethod) << int(DCK);
8499     return true;
8500   }
8501 
8502   const ParmVarDecl *KnownParm = nullptr;
8503   for (const ParmVarDecl *Param : FD->parameters()) {
8504     QualType ParmTy = Param->getType();
8505     if (ParmTy->isDependentType())
8506       continue;
8507     if (!KnownParm) {
8508       auto CTy = ParmTy;
8509       // Is it `T const &`?
8510       bool Ok = !IsMethod;
8511       QualType ExpectedTy;
8512       if (RD)
8513         ExpectedTy = Context.getRecordType(RD);
8514       if (auto *Ref = CTy->getAs<ReferenceType>()) {
8515         CTy = Ref->getPointeeType();
8516         if (RD)
8517           ExpectedTy.addConst();
8518         Ok = true;
8519       }
8520 
8521       // Is T a class?
8522       if (!Ok) {
8523       } else if (RD) {
8524         if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8525           Ok = false;
8526       } else if (auto *CRD = CTy->getAsRecordDecl()) {
8527         RD = cast<CXXRecordDecl>(CRD);
8528       } else {
8529         Ok = false;
8530       }
8531 
8532       if (Ok) {
8533         KnownParm = Param;
8534       } else {
8535         // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8536         // corresponding defaulted 'operator<=>' already.
8537         if (!FD->isImplicit()) {
8538           if (RD) {
8539             QualType PlainTy = Context.getRecordType(RD);
8540             QualType RefTy =
8541                 Context.getLValueReferenceType(PlainTy.withConst());
8542             Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8543                 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8544                 << Param->getSourceRange();
8545           } else {
8546             assert(!IsMethod && "should know expected type for method");
8547             Diag(FD->getLocation(),
8548                  diag::err_defaulted_comparison_param_unknown)
8549                 << int(DCK) << ParmTy << Param->getSourceRange();
8550           }
8551         }
8552         return true;
8553       }
8554     } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8555       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8556           << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8557           << ParmTy << Param->getSourceRange();
8558       return true;
8559     }
8560   }
8561 
8562   assert(RD && "must have determined class");
8563   if (IsMethod) {
8564   } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8565     // In-class, must be a friend decl.
8566     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8567   } else {
8568     // Out of class, require the defaulted comparison to be a friend (of a
8569     // complete type).
8570     if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8571                             diag::err_defaulted_comparison_not_friend, int(DCK),
8572                             int(1)))
8573       return true;
8574 
8575     if (llvm::find_if(RD->friends(), [&](const FriendDecl *F) {
8576           return FD->getCanonicalDecl() ==
8577                  F->getFriendDecl()->getCanonicalDecl();
8578         }) == RD->friends().end()) {
8579       Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8580           << int(DCK) << int(0) << RD;
8581       Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8582       return true;
8583     }
8584   }
8585 
8586   // C++2a [class.eq]p1, [class.rel]p1:
8587   //   A [defaulted comparison other than <=>] shall have a declared return
8588   //   type bool.
8589   if (DCK != DefaultedComparisonKind::ThreeWay &&
8590       !FD->getDeclaredReturnType()->isDependentType() &&
8591       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8592     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8593         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8594         << FD->getReturnTypeSourceRange();
8595     return true;
8596   }
8597   // C++2a [class.spaceship]p2 [P2002R0]:
8598   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8599   //   R shall not contain a placeholder type.
8600   if (DCK == DefaultedComparisonKind::ThreeWay &&
8601       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8602       !Context.hasSameType(FD->getDeclaredReturnType(),
8603                            Context.getAutoDeductType())) {
8604     Diag(FD->getLocation(),
8605          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8606         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8607         << FD->getReturnTypeSourceRange();
8608     return true;
8609   }
8610 
8611   // For a defaulted function in a dependent class, defer all remaining checks
8612   // until instantiation.
8613   if (RD->isDependentType())
8614     return false;
8615 
8616   // Determine whether the function should be defined as deleted.
8617   DefaultedComparisonInfo Info =
8618       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8619 
8620   bool First = FD == FD->getCanonicalDecl();
8621 
8622   // If we want to delete the function, then do so; there's nothing else to
8623   // check in that case.
8624   if (Info.Deleted) {
8625     if (!First) {
8626       // C++11 [dcl.fct.def.default]p4:
8627       //   [For a] user-provided explicitly-defaulted function [...] if such a
8628       //   function is implicitly defined as deleted, the program is ill-formed.
8629       //
8630       // This is really just a consequence of the general rule that you can
8631       // only delete a function on its first declaration.
8632       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8633           << FD->isImplicit() << (int)DCK;
8634       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8635                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8636           .visit();
8637       return true;
8638     }
8639 
8640     SetDeclDeleted(FD, FD->getLocation());
8641     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8642       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8643           << (int)DCK;
8644       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8645                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8646           .visit();
8647     }
8648     return false;
8649   }
8650 
8651   // C++2a [class.spaceship]p2:
8652   //   The return type is deduced as the common comparison type of R0, R1, ...
8653   if (DCK == DefaultedComparisonKind::ThreeWay &&
8654       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8655     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8656     if (RetLoc.isInvalid())
8657       RetLoc = FD->getBeginLoc();
8658     // FIXME: Should we really care whether we have the complete type and the
8659     // 'enumerator' constants here? A forward declaration seems sufficient.
8660     QualType Cat = CheckComparisonCategoryType(
8661         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8662     if (Cat.isNull())
8663       return true;
8664     Context.adjustDeducedFunctionResultType(
8665         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8666   }
8667 
8668   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8669   //   An explicitly-defaulted function that is not defined as deleted may be
8670   //   declared constexpr or consteval only if it is constexpr-compatible.
8671   // C++2a [class.compare.default]p3 [P2002R0]:
8672   //   A defaulted comparison function is constexpr-compatible if it satisfies
8673   //   the requirements for a constexpr function [...]
8674   // The only relevant requirements are that the parameter and return types are
8675   // literal types. The remaining conditions are checked by the analyzer.
8676   if (FD->isConstexpr()) {
8677     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8678         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8679         !Info.Constexpr) {
8680       Diag(FD->getBeginLoc(),
8681            diag::err_incorrect_defaulted_comparison_constexpr)
8682           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8683       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8684                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8685           .visit();
8686     }
8687   }
8688 
8689   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8690   //   If a constexpr-compatible function is explicitly defaulted on its first
8691   //   declaration, it is implicitly considered to be constexpr.
8692   // FIXME: Only applying this to the first declaration seems problematic, as
8693   // simple reorderings can affect the meaning of the program.
8694   if (First && !FD->isConstexpr() && Info.Constexpr)
8695     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8696 
8697   // C++2a [except.spec]p3:
8698   //   If a declaration of a function does not have a noexcept-specifier
8699   //   [and] is defaulted on its first declaration, [...] the exception
8700   //   specification is as specified below
8701   if (FD->getExceptionSpecType() == EST_None) {
8702     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8703     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8704     EPI.ExceptionSpec.Type = EST_Unevaluated;
8705     EPI.ExceptionSpec.SourceDecl = FD;
8706     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8707                                         FPT->getParamTypes(), EPI));
8708   }
8709 
8710   return false;
8711 }
8712 
8713 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8714                                              FunctionDecl *Spaceship) {
8715   Sema::CodeSynthesisContext Ctx;
8716   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8717   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8718   Ctx.Entity = Spaceship;
8719   pushCodeSynthesisContext(Ctx);
8720 
8721   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8722     EqualEqual->setImplicit();
8723 
8724   popCodeSynthesisContext();
8725 }
8726 
8727 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8728                                      DefaultedComparisonKind DCK) {
8729   assert(FD->isDefaulted() && !FD->isDeleted() &&
8730          !FD->doesThisDeclarationHaveABody());
8731   if (FD->willHaveBody() || FD->isInvalidDecl())
8732     return;
8733 
8734   SynthesizedFunctionScope Scope(*this, FD);
8735 
8736   // Add a context note for diagnostics produced after this point.
8737   Scope.addContextNote(UseLoc);
8738 
8739   {
8740     // Build and set up the function body.
8741     // The first parameter has type maybe-ref-to maybe-const T, use that to get
8742     // the type of the class being compared.
8743     auto PT = FD->getParamDecl(0)->getType();
8744     CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
8745     SourceLocation BodyLoc =
8746         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8747     StmtResult Body =
8748         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8749     if (Body.isInvalid()) {
8750       FD->setInvalidDecl();
8751       return;
8752     }
8753     FD->setBody(Body.get());
8754     FD->markUsed(Context);
8755   }
8756 
8757   // The exception specification is needed because we are defining the
8758   // function. Note that this will reuse the body we just built.
8759   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8760 
8761   if (ASTMutationListener *L = getASTMutationListener())
8762     L->CompletedImplicitDefinition(FD);
8763 }
8764 
8765 static Sema::ImplicitExceptionSpecification
8766 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8767                                         FunctionDecl *FD,
8768                                         Sema::DefaultedComparisonKind DCK) {
8769   ComputingExceptionSpec CES(S, FD, Loc);
8770   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8771 
8772   if (FD->isInvalidDecl())
8773     return ExceptSpec;
8774 
8775   // The common case is that we just defined the comparison function. In that
8776   // case, just look at whether the body can throw.
8777   if (FD->hasBody()) {
8778     ExceptSpec.CalledStmt(FD->getBody());
8779   } else {
8780     // Otherwise, build a body so we can check it. This should ideally only
8781     // happen when we're not actually marking the function referenced. (This is
8782     // only really important for efficiency: we don't want to build and throw
8783     // away bodies for comparison functions more than we strictly need to.)
8784 
8785     // Pretend to synthesize the function body in an unevaluated context.
8786     // Note that we can't actually just go ahead and define the function here:
8787     // we are not permitted to mark its callees as referenced.
8788     Sema::SynthesizedFunctionScope Scope(S, FD);
8789     EnterExpressionEvaluationContext Context(
8790         S, Sema::ExpressionEvaluationContext::Unevaluated);
8791 
8792     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8793     SourceLocation BodyLoc =
8794         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8795     StmtResult Body =
8796         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8797     if (!Body.isInvalid())
8798       ExceptSpec.CalledStmt(Body.get());
8799 
8800     // FIXME: Can we hold onto this body and just transform it to potentially
8801     // evaluated when we're asked to define the function rather than rebuilding
8802     // it? Either that, or we should only build the bits of the body that we
8803     // need (the expressions, not the statements).
8804   }
8805 
8806   return ExceptSpec;
8807 }
8808 
8809 void Sema::CheckDelayedMemberExceptionSpecs() {
8810   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8811   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8812 
8813   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8814   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8815 
8816   // Perform any deferred checking of exception specifications for virtual
8817   // destructors.
8818   for (auto &Check : Overriding)
8819     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8820 
8821   // Perform any deferred checking of exception specifications for befriended
8822   // special members.
8823   for (auto &Check : Equivalent)
8824     CheckEquivalentExceptionSpec(Check.second, Check.first);
8825 }
8826 
8827 namespace {
8828 /// CRTP base class for visiting operations performed by a special member
8829 /// function (or inherited constructor).
8830 template<typename Derived>
8831 struct SpecialMemberVisitor {
8832   Sema &S;
8833   CXXMethodDecl *MD;
8834   Sema::CXXSpecialMember CSM;
8835   Sema::InheritedConstructorInfo *ICI;
8836 
8837   // Properties of the special member, computed for convenience.
8838   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8839 
8840   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8841                        Sema::InheritedConstructorInfo *ICI)
8842       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8843     switch (CSM) {
8844     case Sema::CXXDefaultConstructor:
8845     case Sema::CXXCopyConstructor:
8846     case Sema::CXXMoveConstructor:
8847       IsConstructor = true;
8848       break;
8849     case Sema::CXXCopyAssignment:
8850     case Sema::CXXMoveAssignment:
8851       IsAssignment = true;
8852       break;
8853     case Sema::CXXDestructor:
8854       break;
8855     case Sema::CXXInvalid:
8856       llvm_unreachable("invalid special member kind");
8857     }
8858 
8859     if (MD->getNumParams()) {
8860       if (const ReferenceType *RT =
8861               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8862         ConstArg = RT->getPointeeType().isConstQualified();
8863     }
8864   }
8865 
8866   Derived &getDerived() { return static_cast<Derived&>(*this); }
8867 
8868   /// Is this a "move" special member?
8869   bool isMove() const {
8870     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8871   }
8872 
8873   /// Look up the corresponding special member in the given class.
8874   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8875                                              unsigned Quals, bool IsMutable) {
8876     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8877                                        ConstArg && !IsMutable);
8878   }
8879 
8880   /// Look up the constructor for the specified base class to see if it's
8881   /// overridden due to this being an inherited constructor.
8882   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8883     if (!ICI)
8884       return {};
8885     assert(CSM == Sema::CXXDefaultConstructor);
8886     auto *BaseCtor =
8887       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8888     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8889       return MD;
8890     return {};
8891   }
8892 
8893   /// A base or member subobject.
8894   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8895 
8896   /// Get the location to use for a subobject in diagnostics.
8897   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8898     // FIXME: For an indirect virtual base, the direct base leading to
8899     // the indirect virtual base would be a more useful choice.
8900     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8901       return B->getBaseTypeLoc();
8902     else
8903       return Subobj.get<FieldDecl*>()->getLocation();
8904   }
8905 
8906   enum BasesToVisit {
8907     /// Visit all non-virtual (direct) bases.
8908     VisitNonVirtualBases,
8909     /// Visit all direct bases, virtual or not.
8910     VisitDirectBases,
8911     /// Visit all non-virtual bases, and all virtual bases if the class
8912     /// is not abstract.
8913     VisitPotentiallyConstructedBases,
8914     /// Visit all direct or virtual bases.
8915     VisitAllBases
8916   };
8917 
8918   // Visit the bases and members of the class.
8919   bool visit(BasesToVisit Bases) {
8920     CXXRecordDecl *RD = MD->getParent();
8921 
8922     if (Bases == VisitPotentiallyConstructedBases)
8923       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8924 
8925     for (auto &B : RD->bases())
8926       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8927           getDerived().visitBase(&B))
8928         return true;
8929 
8930     if (Bases == VisitAllBases)
8931       for (auto &B : RD->vbases())
8932         if (getDerived().visitBase(&B))
8933           return true;
8934 
8935     for (auto *F : RD->fields())
8936       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8937           getDerived().visitField(F))
8938         return true;
8939 
8940     return false;
8941   }
8942 };
8943 }
8944 
8945 namespace {
8946 struct SpecialMemberDeletionInfo
8947     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8948   bool Diagnose;
8949 
8950   SourceLocation Loc;
8951 
8952   bool AllFieldsAreConst;
8953 
8954   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8955                             Sema::CXXSpecialMember CSM,
8956                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8957       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8958         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8959 
8960   bool inUnion() const { return MD->getParent()->isUnion(); }
8961 
8962   Sema::CXXSpecialMember getEffectiveCSM() {
8963     return ICI ? Sema::CXXInvalid : CSM;
8964   }
8965 
8966   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8967 
8968   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8969   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8970 
8971   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8972   bool shouldDeleteForField(FieldDecl *FD);
8973   bool shouldDeleteForAllConstMembers();
8974 
8975   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8976                                      unsigned Quals);
8977   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8978                                     Sema::SpecialMemberOverloadResult SMOR,
8979                                     bool IsDtorCallInCtor);
8980 
8981   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8982 };
8983 }
8984 
8985 /// Is the given special member inaccessible when used on the given
8986 /// sub-object.
8987 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8988                                              CXXMethodDecl *target) {
8989   /// If we're operating on a base class, the object type is the
8990   /// type of this special member.
8991   QualType objectTy;
8992   AccessSpecifier access = target->getAccess();
8993   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8994     objectTy = S.Context.getTypeDeclType(MD->getParent());
8995     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8996 
8997   // If we're operating on a field, the object type is the type of the field.
8998   } else {
8999     objectTy = S.Context.getTypeDeclType(target->getParent());
9000   }
9001 
9002   return S.isMemberAccessibleForDeletion(
9003       target->getParent(), DeclAccessPair::make(target, access), objectTy);
9004 }
9005 
9006 /// Check whether we should delete a special member due to the implicit
9007 /// definition containing a call to a special member of a subobject.
9008 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9009     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9010     bool IsDtorCallInCtor) {
9011   CXXMethodDecl *Decl = SMOR.getMethod();
9012   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9013 
9014   int DiagKind = -1;
9015 
9016   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9017     DiagKind = !Decl ? 0 : 1;
9018   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9019     DiagKind = 2;
9020   else if (!isAccessible(Subobj, Decl))
9021     DiagKind = 3;
9022   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9023            !Decl->isTrivial()) {
9024     // A member of a union must have a trivial corresponding special member.
9025     // As a weird special case, a destructor call from a union's constructor
9026     // must be accessible and non-deleted, but need not be trivial. Such a
9027     // destructor is never actually called, but is semantically checked as
9028     // if it were.
9029     DiagKind = 4;
9030   }
9031 
9032   if (DiagKind == -1)
9033     return false;
9034 
9035   if (Diagnose) {
9036     if (Field) {
9037       S.Diag(Field->getLocation(),
9038              diag::note_deleted_special_member_class_subobject)
9039         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9040         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9041     } else {
9042       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9043       S.Diag(Base->getBeginLoc(),
9044              diag::note_deleted_special_member_class_subobject)
9045           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9046           << Base->getType() << DiagKind << IsDtorCallInCtor
9047           << /*IsObjCPtr*/false;
9048     }
9049 
9050     if (DiagKind == 1)
9051       S.NoteDeletedFunction(Decl);
9052     // FIXME: Explain inaccessibility if DiagKind == 3.
9053   }
9054 
9055   return true;
9056 }
9057 
9058 /// Check whether we should delete a special member function due to having a
9059 /// direct or virtual base class or non-static data member of class type M.
9060 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9061     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9062   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9063   bool IsMutable = Field && Field->isMutable();
9064 
9065   // C++11 [class.ctor]p5:
9066   // -- any direct or virtual base class, or non-static data member with no
9067   //    brace-or-equal-initializer, has class type M (or array thereof) and
9068   //    either M has no default constructor or overload resolution as applied
9069   //    to M's default constructor results in an ambiguity or in a function
9070   //    that is deleted or inaccessible
9071   // C++11 [class.copy]p11, C++11 [class.copy]p23:
9072   // -- a direct or virtual base class B that cannot be copied/moved because
9073   //    overload resolution, as applied to B's corresponding special member,
9074   //    results in an ambiguity or a function that is deleted or inaccessible
9075   //    from the defaulted special member
9076   // C++11 [class.dtor]p5:
9077   // -- any direct or virtual base class [...] has a type with a destructor
9078   //    that is deleted or inaccessible
9079   if (!(CSM == Sema::CXXDefaultConstructor &&
9080         Field && Field->hasInClassInitializer()) &&
9081       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9082                                    false))
9083     return true;
9084 
9085   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9086   // -- any direct or virtual base class or non-static data member has a
9087   //    type with a destructor that is deleted or inaccessible
9088   if (IsConstructor) {
9089     Sema::SpecialMemberOverloadResult SMOR =
9090         S.LookupSpecialMember(Class, Sema::CXXDestructor,
9091                               false, false, false, false, false);
9092     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9093       return true;
9094   }
9095 
9096   return false;
9097 }
9098 
9099 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9100     FieldDecl *FD, QualType FieldType) {
9101   // The defaulted special functions are defined as deleted if this is a variant
9102   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9103   // type under ARC.
9104   if (!FieldType.hasNonTrivialObjCLifetime())
9105     return false;
9106 
9107   // Don't make the defaulted default constructor defined as deleted if the
9108   // member has an in-class initializer.
9109   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9110     return false;
9111 
9112   if (Diagnose) {
9113     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9114     S.Diag(FD->getLocation(),
9115            diag::note_deleted_special_member_class_subobject)
9116         << getEffectiveCSM() << ParentClass << /*IsField*/true
9117         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9118   }
9119 
9120   return true;
9121 }
9122 
9123 /// Check whether we should delete a special member function due to the class
9124 /// having a particular direct or virtual base class.
9125 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9126   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9127   // If program is correct, BaseClass cannot be null, but if it is, the error
9128   // must be reported elsewhere.
9129   if (!BaseClass)
9130     return false;
9131   // If we have an inheriting constructor, check whether we're calling an
9132   // inherited constructor instead of a default constructor.
9133   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9134   if (auto *BaseCtor = SMOR.getMethod()) {
9135     // Note that we do not check access along this path; other than that,
9136     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9137     // FIXME: Check that the base has a usable destructor! Sink this into
9138     // shouldDeleteForClassSubobject.
9139     if (BaseCtor->isDeleted() && Diagnose) {
9140       S.Diag(Base->getBeginLoc(),
9141              diag::note_deleted_special_member_class_subobject)
9142           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9143           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9144           << /*IsObjCPtr*/false;
9145       S.NoteDeletedFunction(BaseCtor);
9146     }
9147     return BaseCtor->isDeleted();
9148   }
9149   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9150 }
9151 
9152 /// Check whether we should delete a special member function due to the class
9153 /// having a particular non-static data member.
9154 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9155   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9156   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9157 
9158   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9159     return true;
9160 
9161   if (CSM == Sema::CXXDefaultConstructor) {
9162     // For a default constructor, all references must be initialized in-class
9163     // and, if a union, it must have a non-const member.
9164     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9165       if (Diagnose)
9166         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9167           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9168       return true;
9169     }
9170     // C++11 [class.ctor]p5: any non-variant non-static data member of
9171     // const-qualified type (or array thereof) with no
9172     // brace-or-equal-initializer does not have a user-provided default
9173     // constructor.
9174     if (!inUnion() && FieldType.isConstQualified() &&
9175         !FD->hasInClassInitializer() &&
9176         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
9177       if (Diagnose)
9178         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9179           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9180       return true;
9181     }
9182 
9183     if (inUnion() && !FieldType.isConstQualified())
9184       AllFieldsAreConst = false;
9185   } else if (CSM == Sema::CXXCopyConstructor) {
9186     // For a copy constructor, data members must not be of rvalue reference
9187     // type.
9188     if (FieldType->isRValueReferenceType()) {
9189       if (Diagnose)
9190         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9191           << MD->getParent() << FD << FieldType;
9192       return true;
9193     }
9194   } else if (IsAssignment) {
9195     // For an assignment operator, data members must not be of reference type.
9196     if (FieldType->isReferenceType()) {
9197       if (Diagnose)
9198         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9199           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9200       return true;
9201     }
9202     if (!FieldRecord && FieldType.isConstQualified()) {
9203       // C++11 [class.copy]p23:
9204       // -- a non-static data member of const non-class type (or array thereof)
9205       if (Diagnose)
9206         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9207           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9208       return true;
9209     }
9210   }
9211 
9212   if (FieldRecord) {
9213     // Some additional restrictions exist on the variant members.
9214     if (!inUnion() && FieldRecord->isUnion() &&
9215         FieldRecord->isAnonymousStructOrUnion()) {
9216       bool AllVariantFieldsAreConst = true;
9217 
9218       // FIXME: Handle anonymous unions declared within anonymous unions.
9219       for (auto *UI : FieldRecord->fields()) {
9220         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9221 
9222         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9223           return true;
9224 
9225         if (!UnionFieldType.isConstQualified())
9226           AllVariantFieldsAreConst = false;
9227 
9228         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9229         if (UnionFieldRecord &&
9230             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9231                                           UnionFieldType.getCVRQualifiers()))
9232           return true;
9233       }
9234 
9235       // At least one member in each anonymous union must be non-const
9236       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9237           !FieldRecord->field_empty()) {
9238         if (Diagnose)
9239           S.Diag(FieldRecord->getLocation(),
9240                  diag::note_deleted_default_ctor_all_const)
9241             << !!ICI << MD->getParent() << /*anonymous union*/1;
9242         return true;
9243       }
9244 
9245       // Don't check the implicit member of the anonymous union type.
9246       // This is technically non-conformant but supported, and we have a
9247       // diagnostic for this elsewhere.
9248       return false;
9249     }
9250 
9251     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9252                                       FieldType.getCVRQualifiers()))
9253       return true;
9254   }
9255 
9256   return false;
9257 }
9258 
9259 /// C++11 [class.ctor] p5:
9260 ///   A defaulted default constructor for a class X is defined as deleted if
9261 /// X is a union and all of its variant members are of const-qualified type.
9262 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9263   // This is a silly definition, because it gives an empty union a deleted
9264   // default constructor. Don't do that.
9265   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9266     bool AnyFields = false;
9267     for (auto *F : MD->getParent()->fields())
9268       if ((AnyFields = !F->isUnnamedBitfield()))
9269         break;
9270     if (!AnyFields)
9271       return false;
9272     if (Diagnose)
9273       S.Diag(MD->getParent()->getLocation(),
9274              diag::note_deleted_default_ctor_all_const)
9275         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9276     return true;
9277   }
9278   return false;
9279 }
9280 
9281 /// Determine whether a defaulted special member function should be defined as
9282 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9283 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9284 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9285                                      InheritedConstructorInfo *ICI,
9286                                      bool Diagnose) {
9287   if (MD->isInvalidDecl())
9288     return false;
9289   CXXRecordDecl *RD = MD->getParent();
9290   assert(!RD->isDependentType() && "do deletion after instantiation");
9291   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9292     return false;
9293 
9294   // C++11 [expr.lambda.prim]p19:
9295   //   The closure type associated with a lambda-expression has a
9296   //   deleted (8.4.3) default constructor and a deleted copy
9297   //   assignment operator.
9298   // C++2a adds back these operators if the lambda has no lambda-capture.
9299   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9300       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9301     if (Diagnose)
9302       Diag(RD->getLocation(), diag::note_lambda_decl);
9303     return true;
9304   }
9305 
9306   // For an anonymous struct or union, the copy and assignment special members
9307   // will never be used, so skip the check. For an anonymous union declared at
9308   // namespace scope, the constructor and destructor are used.
9309   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9310       RD->isAnonymousStructOrUnion())
9311     return false;
9312 
9313   // C++11 [class.copy]p7, p18:
9314   //   If the class definition declares a move constructor or move assignment
9315   //   operator, an implicitly declared copy constructor or copy assignment
9316   //   operator is defined as deleted.
9317   if (MD->isImplicit() &&
9318       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9319     CXXMethodDecl *UserDeclaredMove = nullptr;
9320 
9321     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9322     // deletion of the corresponding copy operation, not both copy operations.
9323     // MSVC 2015 has adopted the standards conforming behavior.
9324     bool DeletesOnlyMatchingCopy =
9325         getLangOpts().MSVCCompat &&
9326         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9327 
9328     if (RD->hasUserDeclaredMoveConstructor() &&
9329         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9330       if (!Diagnose) return true;
9331 
9332       // Find any user-declared move constructor.
9333       for (auto *I : RD->ctors()) {
9334         if (I->isMoveConstructor()) {
9335           UserDeclaredMove = I;
9336           break;
9337         }
9338       }
9339       assert(UserDeclaredMove);
9340     } else if (RD->hasUserDeclaredMoveAssignment() &&
9341                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9342       if (!Diagnose) return true;
9343 
9344       // Find any user-declared move assignment operator.
9345       for (auto *I : RD->methods()) {
9346         if (I->isMoveAssignmentOperator()) {
9347           UserDeclaredMove = I;
9348           break;
9349         }
9350       }
9351       assert(UserDeclaredMove);
9352     }
9353 
9354     if (UserDeclaredMove) {
9355       Diag(UserDeclaredMove->getLocation(),
9356            diag::note_deleted_copy_user_declared_move)
9357         << (CSM == CXXCopyAssignment) << RD
9358         << UserDeclaredMove->isMoveAssignmentOperator();
9359       return true;
9360     }
9361   }
9362 
9363   // Do access control from the special member function
9364   ContextRAII MethodContext(*this, MD);
9365 
9366   // C++11 [class.dtor]p5:
9367   // -- for a virtual destructor, lookup of the non-array deallocation function
9368   //    results in an ambiguity or in a function that is deleted or inaccessible
9369   if (CSM == CXXDestructor && MD->isVirtual()) {
9370     FunctionDecl *OperatorDelete = nullptr;
9371     DeclarationName Name =
9372       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9373     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9374                                  OperatorDelete, /*Diagnose*/false)) {
9375       if (Diagnose)
9376         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9377       return true;
9378     }
9379   }
9380 
9381   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9382 
9383   // Per DR1611, do not consider virtual bases of constructors of abstract
9384   // classes, since we are not going to construct them.
9385   // Per DR1658, do not consider virtual bases of destructors of abstract
9386   // classes either.
9387   // Per DR2180, for assignment operators we only assign (and thus only
9388   // consider) direct bases.
9389   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9390                                  : SMI.VisitPotentiallyConstructedBases))
9391     return true;
9392 
9393   if (SMI.shouldDeleteForAllConstMembers())
9394     return true;
9395 
9396   if (getLangOpts().CUDA) {
9397     // We should delete the special member in CUDA mode if target inference
9398     // failed.
9399     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9400     // is treated as certain special member, which may not reflect what special
9401     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9402     // expects CSM to match MD, therefore recalculate CSM.
9403     assert(ICI || CSM == getSpecialMember(MD));
9404     auto RealCSM = CSM;
9405     if (ICI)
9406       RealCSM = getSpecialMember(MD);
9407 
9408     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9409                                                    SMI.ConstArg, Diagnose);
9410   }
9411 
9412   return false;
9413 }
9414 
9415 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9416   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9417   assert(DFK && "not a defaultable function");
9418   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9419 
9420   if (DFK.isSpecialMember()) {
9421     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9422                               nullptr, /*Diagnose=*/true);
9423   } else {
9424     DefaultedComparisonAnalyzer(
9425         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9426         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9427         .visit();
9428   }
9429 }
9430 
9431 /// Perform lookup for a special member of the specified kind, and determine
9432 /// whether it is trivial. If the triviality can be determined without the
9433 /// lookup, skip it. This is intended for use when determining whether a
9434 /// special member of a containing object is trivial, and thus does not ever
9435 /// perform overload resolution for default constructors.
9436 ///
9437 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9438 /// member that was most likely to be intended to be trivial, if any.
9439 ///
9440 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9441 /// determine whether the special member is trivial.
9442 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9443                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9444                                      bool ConstRHS,
9445                                      Sema::TrivialABIHandling TAH,
9446                                      CXXMethodDecl **Selected) {
9447   if (Selected)
9448     *Selected = nullptr;
9449 
9450   switch (CSM) {
9451   case Sema::CXXInvalid:
9452     llvm_unreachable("not a special member");
9453 
9454   case Sema::CXXDefaultConstructor:
9455     // C++11 [class.ctor]p5:
9456     //   A default constructor is trivial if:
9457     //    - all the [direct subobjects] have trivial default constructors
9458     //
9459     // Note, no overload resolution is performed in this case.
9460     if (RD->hasTrivialDefaultConstructor())
9461       return true;
9462 
9463     if (Selected) {
9464       // If there's a default constructor which could have been trivial, dig it
9465       // out. Otherwise, if there's any user-provided default constructor, point
9466       // to that as an example of why there's not a trivial one.
9467       CXXConstructorDecl *DefCtor = nullptr;
9468       if (RD->needsImplicitDefaultConstructor())
9469         S.DeclareImplicitDefaultConstructor(RD);
9470       for (auto *CI : RD->ctors()) {
9471         if (!CI->isDefaultConstructor())
9472           continue;
9473         DefCtor = CI;
9474         if (!DefCtor->isUserProvided())
9475           break;
9476       }
9477 
9478       *Selected = DefCtor;
9479     }
9480 
9481     return false;
9482 
9483   case Sema::CXXDestructor:
9484     // C++11 [class.dtor]p5:
9485     //   A destructor is trivial if:
9486     //    - all the direct [subobjects] have trivial destructors
9487     if (RD->hasTrivialDestructor() ||
9488         (TAH == Sema::TAH_ConsiderTrivialABI &&
9489          RD->hasTrivialDestructorForCall()))
9490       return true;
9491 
9492     if (Selected) {
9493       if (RD->needsImplicitDestructor())
9494         S.DeclareImplicitDestructor(RD);
9495       *Selected = RD->getDestructor();
9496     }
9497 
9498     return false;
9499 
9500   case Sema::CXXCopyConstructor:
9501     // C++11 [class.copy]p12:
9502     //   A copy constructor is trivial if:
9503     //    - the constructor selected to copy each direct [subobject] is trivial
9504     if (RD->hasTrivialCopyConstructor() ||
9505         (TAH == Sema::TAH_ConsiderTrivialABI &&
9506          RD->hasTrivialCopyConstructorForCall())) {
9507       if (Quals == Qualifiers::Const)
9508         // We must either select the trivial copy constructor or reach an
9509         // ambiguity; no need to actually perform overload resolution.
9510         return true;
9511     } else if (!Selected) {
9512       return false;
9513     }
9514     // In C++98, we are not supposed to perform overload resolution here, but we
9515     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9516     // cases like B as having a non-trivial copy constructor:
9517     //   struct A { template<typename T> A(T&); };
9518     //   struct B { mutable A a; };
9519     goto NeedOverloadResolution;
9520 
9521   case Sema::CXXCopyAssignment:
9522     // C++11 [class.copy]p25:
9523     //   A copy assignment operator is trivial if:
9524     //    - the assignment operator selected to copy each direct [subobject] is
9525     //      trivial
9526     if (RD->hasTrivialCopyAssignment()) {
9527       if (Quals == Qualifiers::Const)
9528         return true;
9529     } else if (!Selected) {
9530       return false;
9531     }
9532     // In C++98, we are not supposed to perform overload resolution here, but we
9533     // treat that as a language defect.
9534     goto NeedOverloadResolution;
9535 
9536   case Sema::CXXMoveConstructor:
9537   case Sema::CXXMoveAssignment:
9538   NeedOverloadResolution:
9539     Sema::SpecialMemberOverloadResult SMOR =
9540         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9541 
9542     // The standard doesn't describe how to behave if the lookup is ambiguous.
9543     // We treat it as not making the member non-trivial, just like the standard
9544     // mandates for the default constructor. This should rarely matter, because
9545     // the member will also be deleted.
9546     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9547       return true;
9548 
9549     if (!SMOR.getMethod()) {
9550       assert(SMOR.getKind() ==
9551              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9552       return false;
9553     }
9554 
9555     // We deliberately don't check if we found a deleted special member. We're
9556     // not supposed to!
9557     if (Selected)
9558       *Selected = SMOR.getMethod();
9559 
9560     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9561         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9562       return SMOR.getMethod()->isTrivialForCall();
9563     return SMOR.getMethod()->isTrivial();
9564   }
9565 
9566   llvm_unreachable("unknown special method kind");
9567 }
9568 
9569 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9570   for (auto *CI : RD->ctors())
9571     if (!CI->isImplicit())
9572       return CI;
9573 
9574   // Look for constructor templates.
9575   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9576   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9577     if (CXXConstructorDecl *CD =
9578           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9579       return CD;
9580   }
9581 
9582   return nullptr;
9583 }
9584 
9585 /// The kind of subobject we are checking for triviality. The values of this
9586 /// enumeration are used in diagnostics.
9587 enum TrivialSubobjectKind {
9588   /// The subobject is a base class.
9589   TSK_BaseClass,
9590   /// The subobject is a non-static data member.
9591   TSK_Field,
9592   /// The object is actually the complete object.
9593   TSK_CompleteObject
9594 };
9595 
9596 /// Check whether the special member selected for a given type would be trivial.
9597 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9598                                       QualType SubType, bool ConstRHS,
9599                                       Sema::CXXSpecialMember CSM,
9600                                       TrivialSubobjectKind Kind,
9601                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9602   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9603   if (!SubRD)
9604     return true;
9605 
9606   CXXMethodDecl *Selected;
9607   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9608                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9609     return true;
9610 
9611   if (Diagnose) {
9612     if (ConstRHS)
9613       SubType.addConst();
9614 
9615     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9616       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9617         << Kind << SubType.getUnqualifiedType();
9618       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9619         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9620     } else if (!Selected)
9621       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9622         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9623     else if (Selected->isUserProvided()) {
9624       if (Kind == TSK_CompleteObject)
9625         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9626           << Kind << SubType.getUnqualifiedType() << CSM;
9627       else {
9628         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9629           << Kind << SubType.getUnqualifiedType() << CSM;
9630         S.Diag(Selected->getLocation(), diag::note_declared_at);
9631       }
9632     } else {
9633       if (Kind != TSK_CompleteObject)
9634         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9635           << Kind << SubType.getUnqualifiedType() << CSM;
9636 
9637       // Explain why the defaulted or deleted special member isn't trivial.
9638       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9639                                Diagnose);
9640     }
9641   }
9642 
9643   return false;
9644 }
9645 
9646 /// Check whether the members of a class type allow a special member to be
9647 /// trivial.
9648 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9649                                      Sema::CXXSpecialMember CSM,
9650                                      bool ConstArg,
9651                                      Sema::TrivialABIHandling TAH,
9652                                      bool Diagnose) {
9653   for (const auto *FI : RD->fields()) {
9654     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9655       continue;
9656 
9657     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9658 
9659     // Pretend anonymous struct or union members are members of this class.
9660     if (FI->isAnonymousStructOrUnion()) {
9661       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9662                                     CSM, ConstArg, TAH, Diagnose))
9663         return false;
9664       continue;
9665     }
9666 
9667     // C++11 [class.ctor]p5:
9668     //   A default constructor is trivial if [...]
9669     //    -- no non-static data member of its class has a
9670     //       brace-or-equal-initializer
9671     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9672       if (Diagnose)
9673         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9674             << FI;
9675       return false;
9676     }
9677 
9678     // Objective C ARC 4.3.5:
9679     //   [...] nontrivally ownership-qualified types are [...] not trivially
9680     //   default constructible, copy constructible, move constructible, copy
9681     //   assignable, move assignable, or destructible [...]
9682     if (FieldType.hasNonTrivialObjCLifetime()) {
9683       if (Diagnose)
9684         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9685           << RD << FieldType.getObjCLifetime();
9686       return false;
9687     }
9688 
9689     bool ConstRHS = ConstArg && !FI->isMutable();
9690     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9691                                    CSM, TSK_Field, TAH, Diagnose))
9692       return false;
9693   }
9694 
9695   return true;
9696 }
9697 
9698 /// Diagnose why the specified class does not have a trivial special member of
9699 /// the given kind.
9700 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9701   QualType Ty = Context.getRecordType(RD);
9702 
9703   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9704   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9705                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9706                             /*Diagnose*/true);
9707 }
9708 
9709 /// Determine whether a defaulted or deleted special member function is trivial,
9710 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9711 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9712 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9713                                   TrivialABIHandling TAH, bool Diagnose) {
9714   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9715 
9716   CXXRecordDecl *RD = MD->getParent();
9717 
9718   bool ConstArg = false;
9719 
9720   // C++11 [class.copy]p12, p25: [DR1593]
9721   //   A [special member] is trivial if [...] its parameter-type-list is
9722   //   equivalent to the parameter-type-list of an implicit declaration [...]
9723   switch (CSM) {
9724   case CXXDefaultConstructor:
9725   case CXXDestructor:
9726     // Trivial default constructors and destructors cannot have parameters.
9727     break;
9728 
9729   case CXXCopyConstructor:
9730   case CXXCopyAssignment: {
9731     // Trivial copy operations always have const, non-volatile parameter types.
9732     ConstArg = true;
9733     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9734     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9735     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9736       if (Diagnose)
9737         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9738           << Param0->getSourceRange() << Param0->getType()
9739           << Context.getLValueReferenceType(
9740                Context.getRecordType(RD).withConst());
9741       return false;
9742     }
9743     break;
9744   }
9745 
9746   case CXXMoveConstructor:
9747   case CXXMoveAssignment: {
9748     // Trivial move operations always have non-cv-qualified parameters.
9749     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9750     const RValueReferenceType *RT =
9751       Param0->getType()->getAs<RValueReferenceType>();
9752     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9753       if (Diagnose)
9754         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9755           << Param0->getSourceRange() << Param0->getType()
9756           << Context.getRValueReferenceType(Context.getRecordType(RD));
9757       return false;
9758     }
9759     break;
9760   }
9761 
9762   case CXXInvalid:
9763     llvm_unreachable("not a special member");
9764   }
9765 
9766   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9767     if (Diagnose)
9768       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9769            diag::note_nontrivial_default_arg)
9770         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9771     return false;
9772   }
9773   if (MD->isVariadic()) {
9774     if (Diagnose)
9775       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9776     return false;
9777   }
9778 
9779   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9780   //   A copy/move [constructor or assignment operator] is trivial if
9781   //    -- the [member] selected to copy/move each direct base class subobject
9782   //       is trivial
9783   //
9784   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9785   //   A [default constructor or destructor] is trivial if
9786   //    -- all the direct base classes have trivial [default constructors or
9787   //       destructors]
9788   for (const auto &BI : RD->bases())
9789     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9790                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9791       return false;
9792 
9793   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9794   //   A copy/move [constructor or assignment operator] for a class X is
9795   //   trivial if
9796   //    -- for each non-static data member of X that is of class type (or array
9797   //       thereof), the constructor selected to copy/move that member is
9798   //       trivial
9799   //
9800   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9801   //   A [default constructor or destructor] is trivial if
9802   //    -- for all of the non-static data members of its class that are of class
9803   //       type (or array thereof), each such class has a trivial [default
9804   //       constructor or destructor]
9805   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9806     return false;
9807 
9808   // C++11 [class.dtor]p5:
9809   //   A destructor is trivial if [...]
9810   //    -- the destructor is not virtual
9811   if (CSM == CXXDestructor && MD->isVirtual()) {
9812     if (Diagnose)
9813       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9814     return false;
9815   }
9816 
9817   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9818   //   A [special member] for class X is trivial if [...]
9819   //    -- class X has no virtual functions and no virtual base classes
9820   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9821     if (!Diagnose)
9822       return false;
9823 
9824     if (RD->getNumVBases()) {
9825       // Check for virtual bases. We already know that the corresponding
9826       // member in all bases is trivial, so vbases must all be direct.
9827       CXXBaseSpecifier &BS = *RD->vbases_begin();
9828       assert(BS.isVirtual());
9829       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9830       return false;
9831     }
9832 
9833     // Must have a virtual method.
9834     for (const auto *MI : RD->methods()) {
9835       if (MI->isVirtual()) {
9836         SourceLocation MLoc = MI->getBeginLoc();
9837         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9838         return false;
9839       }
9840     }
9841 
9842     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9843   }
9844 
9845   // Looks like it's trivial!
9846   return true;
9847 }
9848 
9849 namespace {
9850 struct FindHiddenVirtualMethod {
9851   Sema *S;
9852   CXXMethodDecl *Method;
9853   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9854   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9855 
9856 private:
9857   /// Check whether any most overridden method from MD in Methods
9858   static bool CheckMostOverridenMethods(
9859       const CXXMethodDecl *MD,
9860       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9861     if (MD->size_overridden_methods() == 0)
9862       return Methods.count(MD->getCanonicalDecl());
9863     for (const CXXMethodDecl *O : MD->overridden_methods())
9864       if (CheckMostOverridenMethods(O, Methods))
9865         return true;
9866     return false;
9867   }
9868 
9869 public:
9870   /// Member lookup function that determines whether a given C++
9871   /// method overloads virtual methods in a base class without overriding any,
9872   /// to be used with CXXRecordDecl::lookupInBases().
9873   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9874     RecordDecl *BaseRecord =
9875         Specifier->getType()->castAs<RecordType>()->getDecl();
9876 
9877     DeclarationName Name = Method->getDeclName();
9878     assert(Name.getNameKind() == DeclarationName::Identifier);
9879 
9880     bool foundSameNameMethod = false;
9881     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9882     for (Path.Decls = BaseRecord->lookup(Name).begin();
9883          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9884       NamedDecl *D = *Path.Decls;
9885       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9886         MD = MD->getCanonicalDecl();
9887         foundSameNameMethod = true;
9888         // Interested only in hidden virtual methods.
9889         if (!MD->isVirtual())
9890           continue;
9891         // If the method we are checking overrides a method from its base
9892         // don't warn about the other overloaded methods. Clang deviates from
9893         // GCC by only diagnosing overloads of inherited virtual functions that
9894         // do not override any other virtual functions in the base. GCC's
9895         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9896         // function from a base class. These cases may be better served by a
9897         // warning (not specific to virtual functions) on call sites when the
9898         // call would select a different function from the base class, were it
9899         // visible.
9900         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9901         if (!S->IsOverload(Method, MD, false))
9902           return true;
9903         // Collect the overload only if its hidden.
9904         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9905           overloadedMethods.push_back(MD);
9906       }
9907     }
9908 
9909     if (foundSameNameMethod)
9910       OverloadedMethods.append(overloadedMethods.begin(),
9911                                overloadedMethods.end());
9912     return foundSameNameMethod;
9913   }
9914 };
9915 } // end anonymous namespace
9916 
9917 /// Add the most overridden methods from MD to Methods
9918 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9919                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9920   if (MD->size_overridden_methods() == 0)
9921     Methods.insert(MD->getCanonicalDecl());
9922   else
9923     for (const CXXMethodDecl *O : MD->overridden_methods())
9924       AddMostOverridenMethods(O, Methods);
9925 }
9926 
9927 /// Check if a method overloads virtual methods in a base class without
9928 /// overriding any.
9929 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9930                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9931   if (!MD->getDeclName().isIdentifier())
9932     return;
9933 
9934   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9935                      /*bool RecordPaths=*/false,
9936                      /*bool DetectVirtual=*/false);
9937   FindHiddenVirtualMethod FHVM;
9938   FHVM.Method = MD;
9939   FHVM.S = this;
9940 
9941   // Keep the base methods that were overridden or introduced in the subclass
9942   // by 'using' in a set. A base method not in this set is hidden.
9943   CXXRecordDecl *DC = MD->getParent();
9944   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9945   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9946     NamedDecl *ND = *I;
9947     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9948       ND = shad->getTargetDecl();
9949     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9950       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9951   }
9952 
9953   if (DC->lookupInBases(FHVM, Paths))
9954     OverloadedMethods = FHVM.OverloadedMethods;
9955 }
9956 
9957 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9958                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9959   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9960     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9961     PartialDiagnostic PD = PDiag(
9962          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9963     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9964     Diag(overloadedMD->getLocation(), PD);
9965   }
9966 }
9967 
9968 /// Diagnose methods which overload virtual methods in a base class
9969 /// without overriding any.
9970 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9971   if (MD->isInvalidDecl())
9972     return;
9973 
9974   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9975     return;
9976 
9977   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9978   FindHiddenVirtualMethods(MD, OverloadedMethods);
9979   if (!OverloadedMethods.empty()) {
9980     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9981       << MD << (OverloadedMethods.size() > 1);
9982 
9983     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9984   }
9985 }
9986 
9987 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9988   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9989     // No diagnostics if this is a template instantiation.
9990     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9991       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9992            diag::ext_cannot_use_trivial_abi) << &RD;
9993       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9994            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9995     }
9996     RD.dropAttr<TrivialABIAttr>();
9997   };
9998 
9999   // Ill-formed if the copy and move constructors are deleted.
10000   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10001     // If the type is dependent, then assume it might have
10002     // implicit copy or move ctor because we won't know yet at this point.
10003     if (RD.isDependentType())
10004       return true;
10005     if (RD.needsImplicitCopyConstructor() &&
10006         !RD.defaultedCopyConstructorIsDeleted())
10007       return true;
10008     if (RD.needsImplicitMoveConstructor() &&
10009         !RD.defaultedMoveConstructorIsDeleted())
10010       return true;
10011     for (const CXXConstructorDecl *CD : RD.ctors())
10012       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10013         return true;
10014     return false;
10015   };
10016 
10017   if (!HasNonDeletedCopyOrMoveConstructor()) {
10018     PrintDiagAndRemoveAttr(0);
10019     return;
10020   }
10021 
10022   // Ill-formed if the struct has virtual functions.
10023   if (RD.isPolymorphic()) {
10024     PrintDiagAndRemoveAttr(1);
10025     return;
10026   }
10027 
10028   for (const auto &B : RD.bases()) {
10029     // Ill-formed if the base class is non-trivial for the purpose of calls or a
10030     // virtual base.
10031     if (!B.getType()->isDependentType() &&
10032         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10033       PrintDiagAndRemoveAttr(2);
10034       return;
10035     }
10036 
10037     if (B.isVirtual()) {
10038       PrintDiagAndRemoveAttr(3);
10039       return;
10040     }
10041   }
10042 
10043   for (const auto *FD : RD.fields()) {
10044     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10045     // non-trivial for the purpose of calls.
10046     QualType FT = FD->getType();
10047     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10048       PrintDiagAndRemoveAttr(4);
10049       return;
10050     }
10051 
10052     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10053       if (!RT->isDependentType() &&
10054           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10055         PrintDiagAndRemoveAttr(5);
10056         return;
10057       }
10058   }
10059 }
10060 
10061 void Sema::ActOnFinishCXXMemberSpecification(
10062     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10063     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10064   if (!TagDecl)
10065     return;
10066 
10067   AdjustDeclIfTemplate(TagDecl);
10068 
10069   for (const ParsedAttr &AL : AttrList) {
10070     if (AL.getKind() != ParsedAttr::AT_Visibility)
10071       continue;
10072     AL.setInvalid();
10073     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10074   }
10075 
10076   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
10077               // strict aliasing violation!
10078               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
10079               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
10080 
10081   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10082 }
10083 
10084 /// Find the equality comparison functions that should be implicitly declared
10085 /// in a given class definition, per C++2a [class.compare.default]p3.
10086 static void findImplicitlyDeclaredEqualityComparisons(
10087     ASTContext &Ctx, CXXRecordDecl *RD,
10088     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10089   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10090   if (!RD->lookup(EqEq).empty())
10091     // Member operator== explicitly declared: no implicit operator==s.
10092     return;
10093 
10094   // Traverse friends looking for an '==' or a '<=>'.
10095   for (FriendDecl *Friend : RD->friends()) {
10096     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10097     if (!FD) continue;
10098 
10099     if (FD->getOverloadedOperator() == OO_EqualEqual) {
10100       // Friend operator== explicitly declared: no implicit operator==s.
10101       Spaceships.clear();
10102       return;
10103     }
10104 
10105     if (FD->getOverloadedOperator() == OO_Spaceship &&
10106         FD->isExplicitlyDefaulted())
10107       Spaceships.push_back(FD);
10108   }
10109 
10110   // Look for members named 'operator<=>'.
10111   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10112   for (NamedDecl *ND : RD->lookup(Cmp)) {
10113     // Note that we could find a non-function here (either a function template
10114     // or a using-declaration). Neither case results in an implicit
10115     // 'operator=='.
10116     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10117       if (FD->isExplicitlyDefaulted())
10118         Spaceships.push_back(FD);
10119   }
10120 }
10121 
10122 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10123 /// special functions, such as the default constructor, copy
10124 /// constructor, or destructor, to the given C++ class (C++
10125 /// [special]p1).  This routine can only be executed just before the
10126 /// definition of the class is complete.
10127 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10128   // Don't add implicit special members to templated classes.
10129   // FIXME: This means unqualified lookups for 'operator=' within a class
10130   // template don't work properly.
10131   if (!ClassDecl->isDependentType()) {
10132     if (ClassDecl->needsImplicitDefaultConstructor()) {
10133       ++getASTContext().NumImplicitDefaultConstructors;
10134 
10135       if (ClassDecl->hasInheritedConstructor())
10136         DeclareImplicitDefaultConstructor(ClassDecl);
10137     }
10138 
10139     if (ClassDecl->needsImplicitCopyConstructor()) {
10140       ++getASTContext().NumImplicitCopyConstructors;
10141 
10142       // If the properties or semantics of the copy constructor couldn't be
10143       // determined while the class was being declared, force a declaration
10144       // of it now.
10145       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10146           ClassDecl->hasInheritedConstructor())
10147         DeclareImplicitCopyConstructor(ClassDecl);
10148       // For the MS ABI we need to know whether the copy ctor is deleted. A
10149       // prerequisite for deleting the implicit copy ctor is that the class has
10150       // a move ctor or move assignment that is either user-declared or whose
10151       // semantics are inherited from a subobject. FIXME: We should provide a
10152       // more direct way for CodeGen to ask whether the constructor was deleted.
10153       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10154                (ClassDecl->hasUserDeclaredMoveConstructor() ||
10155                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10156                 ClassDecl->hasUserDeclaredMoveAssignment() ||
10157                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10158         DeclareImplicitCopyConstructor(ClassDecl);
10159     }
10160 
10161     if (getLangOpts().CPlusPlus11 &&
10162         ClassDecl->needsImplicitMoveConstructor()) {
10163       ++getASTContext().NumImplicitMoveConstructors;
10164 
10165       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10166           ClassDecl->hasInheritedConstructor())
10167         DeclareImplicitMoveConstructor(ClassDecl);
10168     }
10169 
10170     if (ClassDecl->needsImplicitCopyAssignment()) {
10171       ++getASTContext().NumImplicitCopyAssignmentOperators;
10172 
10173       // If we have a dynamic class, then the copy assignment operator may be
10174       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10175       // it shows up in the right place in the vtable and that we diagnose
10176       // problems with the implicit exception specification.
10177       if (ClassDecl->isDynamicClass() ||
10178           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10179           ClassDecl->hasInheritedAssignment())
10180         DeclareImplicitCopyAssignment(ClassDecl);
10181     }
10182 
10183     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10184       ++getASTContext().NumImplicitMoveAssignmentOperators;
10185 
10186       // Likewise for the move assignment operator.
10187       if (ClassDecl->isDynamicClass() ||
10188           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10189           ClassDecl->hasInheritedAssignment())
10190         DeclareImplicitMoveAssignment(ClassDecl);
10191     }
10192 
10193     if (ClassDecl->needsImplicitDestructor()) {
10194       ++getASTContext().NumImplicitDestructors;
10195 
10196       // If we have a dynamic class, then the destructor may be virtual, so we
10197       // have to declare the destructor immediately. This ensures that, e.g., it
10198       // shows up in the right place in the vtable and that we diagnose problems
10199       // with the implicit exception specification.
10200       if (ClassDecl->isDynamicClass() ||
10201           ClassDecl->needsOverloadResolutionForDestructor())
10202         DeclareImplicitDestructor(ClassDecl);
10203     }
10204   }
10205 
10206   // C++2a [class.compare.default]p3:
10207   //   If the member-specification does not explicitly declare any member or
10208   //   friend named operator==, an == operator function is declared implicitly
10209   //   for each defaulted three-way comparison operator function defined in
10210   //   the member-specification
10211   // FIXME: Consider doing this lazily.
10212   // We do this during the initial parse for a class template, not during
10213   // instantiation, so that we can handle unqualified lookups for 'operator=='
10214   // when parsing the template.
10215   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10216     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10217     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10218                                               DefaultedSpaceships);
10219     for (auto *FD : DefaultedSpaceships)
10220       DeclareImplicitEqualityComparison(ClassDecl, FD);
10221   }
10222 }
10223 
10224 unsigned
10225 Sema::ActOnReenterTemplateScope(Decl *D,
10226                                 llvm::function_ref<Scope *()> EnterScope) {
10227   if (!D)
10228     return 0;
10229   AdjustDeclIfTemplate(D);
10230 
10231   // In order to get name lookup right, reenter template scopes in order from
10232   // outermost to innermost.
10233   SmallVector<TemplateParameterList *, 4> ParameterLists;
10234   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10235 
10236   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10237     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10238       ParameterLists.push_back(DD->getTemplateParameterList(i));
10239 
10240     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10241       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10242         ParameterLists.push_back(FTD->getTemplateParameters());
10243     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10244       LookupDC = VD->getDeclContext();
10245 
10246       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10247         ParameterLists.push_back(VTD->getTemplateParameters());
10248       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10249         ParameterLists.push_back(PSD->getTemplateParameters());
10250     }
10251   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10252     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10253       ParameterLists.push_back(TD->getTemplateParameterList(i));
10254 
10255     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10256       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10257         ParameterLists.push_back(CTD->getTemplateParameters());
10258       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10259         ParameterLists.push_back(PSD->getTemplateParameters());
10260     }
10261   }
10262   // FIXME: Alias declarations and concepts.
10263 
10264   unsigned Count = 0;
10265   Scope *InnermostTemplateScope = nullptr;
10266   for (TemplateParameterList *Params : ParameterLists) {
10267     // Ignore explicit specializations; they don't contribute to the template
10268     // depth.
10269     if (Params->size() == 0)
10270       continue;
10271 
10272     InnermostTemplateScope = EnterScope();
10273     for (NamedDecl *Param : *Params) {
10274       if (Param->getDeclName()) {
10275         InnermostTemplateScope->AddDecl(Param);
10276         IdResolver.AddDecl(Param);
10277       }
10278     }
10279     ++Count;
10280   }
10281 
10282   // Associate the new template scopes with the corresponding entities.
10283   if (InnermostTemplateScope) {
10284     assert(LookupDC && "no enclosing DeclContext for template lookup");
10285     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10286   }
10287 
10288   return Count;
10289 }
10290 
10291 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10292   if (!RecordD) return;
10293   AdjustDeclIfTemplate(RecordD);
10294   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10295   PushDeclContext(S, Record);
10296 }
10297 
10298 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10299   if (!RecordD) return;
10300   PopDeclContext();
10301 }
10302 
10303 /// This is used to implement the constant expression evaluation part of the
10304 /// attribute enable_if extension. There is nothing in standard C++ which would
10305 /// require reentering parameters.
10306 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10307   if (!Param)
10308     return;
10309 
10310   S->AddDecl(Param);
10311   if (Param->getDeclName())
10312     IdResolver.AddDecl(Param);
10313 }
10314 
10315 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10316 /// parsing a top-level (non-nested) C++ class, and we are now
10317 /// parsing those parts of the given Method declaration that could
10318 /// not be parsed earlier (C++ [class.mem]p2), such as default
10319 /// arguments. This action should enter the scope of the given
10320 /// Method declaration as if we had just parsed the qualified method
10321 /// name. However, it should not bring the parameters into scope;
10322 /// that will be performed by ActOnDelayedCXXMethodParameter.
10323 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10324 }
10325 
10326 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10327 /// C++ method declaration. We're (re-)introducing the given
10328 /// function parameter into scope for use in parsing later parts of
10329 /// the method declaration. For example, we could see an
10330 /// ActOnParamDefaultArgument event for this parameter.
10331 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10332   if (!ParamD)
10333     return;
10334 
10335   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10336 
10337   S->AddDecl(Param);
10338   if (Param->getDeclName())
10339     IdResolver.AddDecl(Param);
10340 }
10341 
10342 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10343 /// processing the delayed method declaration for Method. The method
10344 /// declaration is now considered finished. There may be a separate
10345 /// ActOnStartOfFunctionDef action later (not necessarily
10346 /// immediately!) for this method, if it was also defined inside the
10347 /// class body.
10348 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10349   if (!MethodD)
10350     return;
10351 
10352   AdjustDeclIfTemplate(MethodD);
10353 
10354   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10355 
10356   // Now that we have our default arguments, check the constructor
10357   // again. It could produce additional diagnostics or affect whether
10358   // the class has implicitly-declared destructors, among other
10359   // things.
10360   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10361     CheckConstructor(Constructor);
10362 
10363   // Check the default arguments, which we may have added.
10364   if (!Method->isInvalidDecl())
10365     CheckCXXDefaultArguments(Method);
10366 }
10367 
10368 // Emit the given diagnostic for each non-address-space qualifier.
10369 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10370 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10371   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10372   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10373     bool DiagOccured = false;
10374     FTI.MethodQualifiers->forEachQualifier(
10375         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10376                                    SourceLocation SL) {
10377           // This diagnostic should be emitted on any qualifier except an addr
10378           // space qualifier. However, forEachQualifier currently doesn't visit
10379           // addr space qualifiers, so there's no way to write this condition
10380           // right now; we just diagnose on everything.
10381           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10382           DiagOccured = true;
10383         });
10384     if (DiagOccured)
10385       D.setInvalidType();
10386   }
10387 }
10388 
10389 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10390 /// the well-formedness of the constructor declarator @p D with type @p
10391 /// R. If there are any errors in the declarator, this routine will
10392 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10393 /// will be updated to reflect a well-formed type for the constructor and
10394 /// returned.
10395 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10396                                           StorageClass &SC) {
10397   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10398 
10399   // C++ [class.ctor]p3:
10400   //   A constructor shall not be virtual (10.3) or static (9.4). A
10401   //   constructor can be invoked for a const, volatile or const
10402   //   volatile object. A constructor shall not be declared const,
10403   //   volatile, or const volatile (9.3.2).
10404   if (isVirtual) {
10405     if (!D.isInvalidType())
10406       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10407         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10408         << SourceRange(D.getIdentifierLoc());
10409     D.setInvalidType();
10410   }
10411   if (SC == SC_Static) {
10412     if (!D.isInvalidType())
10413       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10414         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10415         << SourceRange(D.getIdentifierLoc());
10416     D.setInvalidType();
10417     SC = SC_None;
10418   }
10419 
10420   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10421     diagnoseIgnoredQualifiers(
10422         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10423         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10424         D.getDeclSpec().getRestrictSpecLoc(),
10425         D.getDeclSpec().getAtomicSpecLoc());
10426     D.setInvalidType();
10427   }
10428 
10429   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10430 
10431   // C++0x [class.ctor]p4:
10432   //   A constructor shall not be declared with a ref-qualifier.
10433   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10434   if (FTI.hasRefQualifier()) {
10435     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10436       << FTI.RefQualifierIsLValueRef
10437       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10438     D.setInvalidType();
10439   }
10440 
10441   // Rebuild the function type "R" without any type qualifiers (in
10442   // case any of the errors above fired) and with "void" as the
10443   // return type, since constructors don't have return types.
10444   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10445   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10446     return R;
10447 
10448   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10449   EPI.TypeQuals = Qualifiers();
10450   EPI.RefQualifier = RQ_None;
10451 
10452   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10453 }
10454 
10455 /// CheckConstructor - Checks a fully-formed constructor for
10456 /// well-formedness, issuing any diagnostics required. Returns true if
10457 /// the constructor declarator is invalid.
10458 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10459   CXXRecordDecl *ClassDecl
10460     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10461   if (!ClassDecl)
10462     return Constructor->setInvalidDecl();
10463 
10464   // C++ [class.copy]p3:
10465   //   A declaration of a constructor for a class X is ill-formed if
10466   //   its first parameter is of type (optionally cv-qualified) X and
10467   //   either there are no other parameters or else all other
10468   //   parameters have default arguments.
10469   if (!Constructor->isInvalidDecl() &&
10470       Constructor->hasOneParamOrDefaultArgs() &&
10471       Constructor->getTemplateSpecializationKind() !=
10472           TSK_ImplicitInstantiation) {
10473     QualType ParamType = Constructor->getParamDecl(0)->getType();
10474     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10475     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10476       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10477       const char *ConstRef
10478         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10479                                                         : " const &";
10480       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10481         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10482 
10483       // FIXME: Rather that making the constructor invalid, we should endeavor
10484       // to fix the type.
10485       Constructor->setInvalidDecl();
10486     }
10487   }
10488 }
10489 
10490 /// CheckDestructor - Checks a fully-formed destructor definition for
10491 /// well-formedness, issuing any diagnostics required.  Returns true
10492 /// on error.
10493 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10494   CXXRecordDecl *RD = Destructor->getParent();
10495 
10496   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10497     SourceLocation Loc;
10498 
10499     if (!Destructor->isImplicit())
10500       Loc = Destructor->getLocation();
10501     else
10502       Loc = RD->getLocation();
10503 
10504     // If we have a virtual destructor, look up the deallocation function
10505     if (FunctionDecl *OperatorDelete =
10506             FindDeallocationFunctionForDestructor(Loc, RD)) {
10507       Expr *ThisArg = nullptr;
10508 
10509       // If the notional 'delete this' expression requires a non-trivial
10510       // conversion from 'this' to the type of a destroying operator delete's
10511       // first parameter, perform that conversion now.
10512       if (OperatorDelete->isDestroyingOperatorDelete()) {
10513         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10514         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10515           // C++ [class.dtor]p13:
10516           //   ... as if for the expression 'delete this' appearing in a
10517           //   non-virtual destructor of the destructor's class.
10518           ContextRAII SwitchContext(*this, Destructor);
10519           ExprResult This =
10520               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10521           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10522           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10523           if (This.isInvalid()) {
10524             // FIXME: Register this as a context note so that it comes out
10525             // in the right order.
10526             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10527             return true;
10528           }
10529           ThisArg = This.get();
10530         }
10531       }
10532 
10533       DiagnoseUseOfDecl(OperatorDelete, Loc);
10534       MarkFunctionReferenced(Loc, OperatorDelete);
10535       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10536     }
10537   }
10538 
10539   return false;
10540 }
10541 
10542 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10543 /// the well-formednes of the destructor declarator @p D with type @p
10544 /// R. If there are any errors in the declarator, this routine will
10545 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10546 /// will be updated to reflect a well-formed type for the destructor and
10547 /// returned.
10548 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10549                                          StorageClass& SC) {
10550   // C++ [class.dtor]p1:
10551   //   [...] A typedef-name that names a class is a class-name
10552   //   (7.1.3); however, a typedef-name that names a class shall not
10553   //   be used as the identifier in the declarator for a destructor
10554   //   declaration.
10555   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10556   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10557     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10558       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10559   else if (const TemplateSpecializationType *TST =
10560              DeclaratorType->getAs<TemplateSpecializationType>())
10561     if (TST->isTypeAlias())
10562       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10563         << DeclaratorType << 1;
10564 
10565   // C++ [class.dtor]p2:
10566   //   A destructor is used to destroy objects of its class type. A
10567   //   destructor takes no parameters, and no return type can be
10568   //   specified for it (not even void). The address of a destructor
10569   //   shall not be taken. A destructor shall not be static. A
10570   //   destructor can be invoked for a const, volatile or const
10571   //   volatile object. A destructor shall not be declared const,
10572   //   volatile or const volatile (9.3.2).
10573   if (SC == SC_Static) {
10574     if (!D.isInvalidType())
10575       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10576         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10577         << SourceRange(D.getIdentifierLoc())
10578         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10579 
10580     SC = SC_None;
10581   }
10582   if (!D.isInvalidType()) {
10583     // Destructors don't have return types, but the parser will
10584     // happily parse something like:
10585     //
10586     //   class X {
10587     //     float ~X();
10588     //   };
10589     //
10590     // The return type will be eliminated later.
10591     if (D.getDeclSpec().hasTypeSpecifier())
10592       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10593         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10594         << SourceRange(D.getIdentifierLoc());
10595     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10596       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10597                                 SourceLocation(),
10598                                 D.getDeclSpec().getConstSpecLoc(),
10599                                 D.getDeclSpec().getVolatileSpecLoc(),
10600                                 D.getDeclSpec().getRestrictSpecLoc(),
10601                                 D.getDeclSpec().getAtomicSpecLoc());
10602       D.setInvalidType();
10603     }
10604   }
10605 
10606   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10607 
10608   // C++0x [class.dtor]p2:
10609   //   A destructor shall not be declared with a ref-qualifier.
10610   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10611   if (FTI.hasRefQualifier()) {
10612     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10613       << FTI.RefQualifierIsLValueRef
10614       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10615     D.setInvalidType();
10616   }
10617 
10618   // Make sure we don't have any parameters.
10619   if (FTIHasNonVoidParameters(FTI)) {
10620     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10621 
10622     // Delete the parameters.
10623     FTI.freeParams();
10624     D.setInvalidType();
10625   }
10626 
10627   // Make sure the destructor isn't variadic.
10628   if (FTI.isVariadic) {
10629     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10630     D.setInvalidType();
10631   }
10632 
10633   // Rebuild the function type "R" without any type qualifiers or
10634   // parameters (in case any of the errors above fired) and with
10635   // "void" as the return type, since destructors don't have return
10636   // types.
10637   if (!D.isInvalidType())
10638     return R;
10639 
10640   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10641   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10642   EPI.Variadic = false;
10643   EPI.TypeQuals = Qualifiers();
10644   EPI.RefQualifier = RQ_None;
10645   return Context.getFunctionType(Context.VoidTy, None, EPI);
10646 }
10647 
10648 static void extendLeft(SourceRange &R, SourceRange Before) {
10649   if (Before.isInvalid())
10650     return;
10651   R.setBegin(Before.getBegin());
10652   if (R.getEnd().isInvalid())
10653     R.setEnd(Before.getEnd());
10654 }
10655 
10656 static void extendRight(SourceRange &R, SourceRange After) {
10657   if (After.isInvalid())
10658     return;
10659   if (R.getBegin().isInvalid())
10660     R.setBegin(After.getBegin());
10661   R.setEnd(After.getEnd());
10662 }
10663 
10664 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10665 /// well-formednes of the conversion function declarator @p D with
10666 /// type @p R. If there are any errors in the declarator, this routine
10667 /// will emit diagnostics and return true. Otherwise, it will return
10668 /// false. Either way, the type @p R will be updated to reflect a
10669 /// well-formed type for the conversion operator.
10670 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10671                                      StorageClass& SC) {
10672   // C++ [class.conv.fct]p1:
10673   //   Neither parameter types nor return type can be specified. The
10674   //   type of a conversion function (8.3.5) is "function taking no
10675   //   parameter returning conversion-type-id."
10676   if (SC == SC_Static) {
10677     if (!D.isInvalidType())
10678       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10679         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10680         << D.getName().getSourceRange();
10681     D.setInvalidType();
10682     SC = SC_None;
10683   }
10684 
10685   TypeSourceInfo *ConvTSI = nullptr;
10686   QualType ConvType =
10687       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10688 
10689   const DeclSpec &DS = D.getDeclSpec();
10690   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10691     // Conversion functions don't have return types, but the parser will
10692     // happily parse something like:
10693     //
10694     //   class X {
10695     //     float operator bool();
10696     //   };
10697     //
10698     // The return type will be changed later anyway.
10699     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10700       << SourceRange(DS.getTypeSpecTypeLoc())
10701       << SourceRange(D.getIdentifierLoc());
10702     D.setInvalidType();
10703   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10704     // It's also plausible that the user writes type qualifiers in the wrong
10705     // place, such as:
10706     //   struct S { const operator int(); };
10707     // FIXME: we could provide a fixit to move the qualifiers onto the
10708     // conversion type.
10709     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10710         << SourceRange(D.getIdentifierLoc()) << 0;
10711     D.setInvalidType();
10712   }
10713 
10714   const auto *Proto = R->castAs<FunctionProtoType>();
10715 
10716   // Make sure we don't have any parameters.
10717   if (Proto->getNumParams() > 0) {
10718     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10719 
10720     // Delete the parameters.
10721     D.getFunctionTypeInfo().freeParams();
10722     D.setInvalidType();
10723   } else if (Proto->isVariadic()) {
10724     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10725     D.setInvalidType();
10726   }
10727 
10728   // Diagnose "&operator bool()" and other such nonsense.  This
10729   // is actually a gcc extension which we don't support.
10730   if (Proto->getReturnType() != ConvType) {
10731     bool NeedsTypedef = false;
10732     SourceRange Before, After;
10733 
10734     // Walk the chunks and extract information on them for our diagnostic.
10735     bool PastFunctionChunk = false;
10736     for (auto &Chunk : D.type_objects()) {
10737       switch (Chunk.Kind) {
10738       case DeclaratorChunk::Function:
10739         if (!PastFunctionChunk) {
10740           if (Chunk.Fun.HasTrailingReturnType) {
10741             TypeSourceInfo *TRT = nullptr;
10742             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10743             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10744           }
10745           PastFunctionChunk = true;
10746           break;
10747         }
10748         LLVM_FALLTHROUGH;
10749       case DeclaratorChunk::Array:
10750         NeedsTypedef = true;
10751         extendRight(After, Chunk.getSourceRange());
10752         break;
10753 
10754       case DeclaratorChunk::Pointer:
10755       case DeclaratorChunk::BlockPointer:
10756       case DeclaratorChunk::Reference:
10757       case DeclaratorChunk::MemberPointer:
10758       case DeclaratorChunk::Pipe:
10759         extendLeft(Before, Chunk.getSourceRange());
10760         break;
10761 
10762       case DeclaratorChunk::Paren:
10763         extendLeft(Before, Chunk.Loc);
10764         extendRight(After, Chunk.EndLoc);
10765         break;
10766       }
10767     }
10768 
10769     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10770                          After.isValid()  ? After.getBegin() :
10771                                             D.getIdentifierLoc();
10772     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10773     DB << Before << After;
10774 
10775     if (!NeedsTypedef) {
10776       DB << /*don't need a typedef*/0;
10777 
10778       // If we can provide a correct fix-it hint, do so.
10779       if (After.isInvalid() && ConvTSI) {
10780         SourceLocation InsertLoc =
10781             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10782         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10783            << FixItHint::CreateInsertionFromRange(
10784                   InsertLoc, CharSourceRange::getTokenRange(Before))
10785            << FixItHint::CreateRemoval(Before);
10786       }
10787     } else if (!Proto->getReturnType()->isDependentType()) {
10788       DB << /*typedef*/1 << Proto->getReturnType();
10789     } else if (getLangOpts().CPlusPlus11) {
10790       DB << /*alias template*/2 << Proto->getReturnType();
10791     } else {
10792       DB << /*might not be fixable*/3;
10793     }
10794 
10795     // Recover by incorporating the other type chunks into the result type.
10796     // Note, this does *not* change the name of the function. This is compatible
10797     // with the GCC extension:
10798     //   struct S { &operator int(); } s;
10799     //   int &r = s.operator int(); // ok in GCC
10800     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10801     ConvType = Proto->getReturnType();
10802   }
10803 
10804   // C++ [class.conv.fct]p4:
10805   //   The conversion-type-id shall not represent a function type nor
10806   //   an array type.
10807   if (ConvType->isArrayType()) {
10808     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10809     ConvType = Context.getPointerType(ConvType);
10810     D.setInvalidType();
10811   } else if (ConvType->isFunctionType()) {
10812     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10813     ConvType = Context.getPointerType(ConvType);
10814     D.setInvalidType();
10815   }
10816 
10817   // Rebuild the function type "R" without any parameters (in case any
10818   // of the errors above fired) and with the conversion type as the
10819   // return type.
10820   if (D.isInvalidType())
10821     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10822 
10823   // C++0x explicit conversion operators.
10824   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10825     Diag(DS.getExplicitSpecLoc(),
10826          getLangOpts().CPlusPlus11
10827              ? diag::warn_cxx98_compat_explicit_conversion_functions
10828              : diag::ext_explicit_conversion_functions)
10829         << SourceRange(DS.getExplicitSpecRange());
10830 }
10831 
10832 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10833 /// the declaration of the given C++ conversion function. This routine
10834 /// is responsible for recording the conversion function in the C++
10835 /// class, if possible.
10836 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10837   assert(Conversion && "Expected to receive a conversion function declaration");
10838 
10839   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10840 
10841   // Make sure we aren't redeclaring the conversion function.
10842   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10843   // C++ [class.conv.fct]p1:
10844   //   [...] A conversion function is never used to convert a
10845   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10846   //   same object type (or a reference to it), to a (possibly
10847   //   cv-qualified) base class of that type (or a reference to it),
10848   //   or to (possibly cv-qualified) void.
10849   QualType ClassType
10850     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10851   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10852     ConvType = ConvTypeRef->getPointeeType();
10853   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10854       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10855     /* Suppress diagnostics for instantiations. */;
10856   else if (Conversion->size_overridden_methods() != 0)
10857     /* Suppress diagnostics for overriding virtual function in a base class. */;
10858   else if (ConvType->isRecordType()) {
10859     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10860     if (ConvType == ClassType)
10861       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10862         << ClassType;
10863     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10864       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10865         <<  ClassType << ConvType;
10866   } else if (ConvType->isVoidType()) {
10867     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10868       << ClassType << ConvType;
10869   }
10870 
10871   if (FunctionTemplateDecl *ConversionTemplate
10872                                 = Conversion->getDescribedFunctionTemplate())
10873     return ConversionTemplate;
10874 
10875   return Conversion;
10876 }
10877 
10878 namespace {
10879 /// Utility class to accumulate and print a diagnostic listing the invalid
10880 /// specifier(s) on a declaration.
10881 struct BadSpecifierDiagnoser {
10882   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10883       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10884   ~BadSpecifierDiagnoser() {
10885     Diagnostic << Specifiers;
10886   }
10887 
10888   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10889     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10890   }
10891   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10892     return check(SpecLoc,
10893                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10894   }
10895   void check(SourceLocation SpecLoc, const char *Spec) {
10896     if (SpecLoc.isInvalid()) return;
10897     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10898     if (!Specifiers.empty()) Specifiers += " ";
10899     Specifiers += Spec;
10900   }
10901 
10902   Sema &S;
10903   Sema::SemaDiagnosticBuilder Diagnostic;
10904   std::string Specifiers;
10905 };
10906 }
10907 
10908 /// Check the validity of a declarator that we parsed for a deduction-guide.
10909 /// These aren't actually declarators in the grammar, so we need to check that
10910 /// the user didn't specify any pieces that are not part of the deduction-guide
10911 /// grammar.
10912 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10913                                          StorageClass &SC) {
10914   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10915   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10916   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10917 
10918   // C++ [temp.deduct.guide]p3:
10919   //   A deduction-gide shall be declared in the same scope as the
10920   //   corresponding class template.
10921   if (!CurContext->getRedeclContext()->Equals(
10922           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10923     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10924       << GuidedTemplateDecl;
10925     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10926   }
10927 
10928   auto &DS = D.getMutableDeclSpec();
10929   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10930   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10931       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10932       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10933     BadSpecifierDiagnoser Diagnoser(
10934         *this, D.getIdentifierLoc(),
10935         diag::err_deduction_guide_invalid_specifier);
10936 
10937     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10938     DS.ClearStorageClassSpecs();
10939     SC = SC_None;
10940 
10941     // 'explicit' is permitted.
10942     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10943     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10944     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10945     DS.ClearConstexprSpec();
10946 
10947     Diagnoser.check(DS.getConstSpecLoc(), "const");
10948     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10949     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10950     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10951     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10952     DS.ClearTypeQualifiers();
10953 
10954     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10955     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10956     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10957     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10958     DS.ClearTypeSpecType();
10959   }
10960 
10961   if (D.isInvalidType())
10962     return;
10963 
10964   // Check the declarator is simple enough.
10965   bool FoundFunction = false;
10966   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10967     if (Chunk.Kind == DeclaratorChunk::Paren)
10968       continue;
10969     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10970       Diag(D.getDeclSpec().getBeginLoc(),
10971            diag::err_deduction_guide_with_complex_decl)
10972           << D.getSourceRange();
10973       break;
10974     }
10975     if (!Chunk.Fun.hasTrailingReturnType()) {
10976       Diag(D.getName().getBeginLoc(),
10977            diag::err_deduction_guide_no_trailing_return_type);
10978       break;
10979     }
10980 
10981     // Check that the return type is written as a specialization of
10982     // the template specified as the deduction-guide's name.
10983     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10984     TypeSourceInfo *TSI = nullptr;
10985     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10986     assert(TSI && "deduction guide has valid type but invalid return type?");
10987     bool AcceptableReturnType = false;
10988     bool MightInstantiateToSpecialization = false;
10989     if (auto RetTST =
10990             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10991       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10992       bool TemplateMatches =
10993           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10994       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10995         AcceptableReturnType = true;
10996       else {
10997         // This could still instantiate to the right type, unless we know it
10998         // names the wrong class template.
10999         auto *TD = SpecifiedName.getAsTemplateDecl();
11000         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11001                                              !TemplateMatches);
11002       }
11003     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11004       MightInstantiateToSpecialization = true;
11005     }
11006 
11007     if (!AcceptableReturnType) {
11008       Diag(TSI->getTypeLoc().getBeginLoc(),
11009            diag::err_deduction_guide_bad_trailing_return_type)
11010           << GuidedTemplate << TSI->getType()
11011           << MightInstantiateToSpecialization
11012           << TSI->getTypeLoc().getSourceRange();
11013     }
11014 
11015     // Keep going to check that we don't have any inner declarator pieces (we
11016     // could still have a function returning a pointer to a function).
11017     FoundFunction = true;
11018   }
11019 
11020   if (D.isFunctionDefinition())
11021     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11022 }
11023 
11024 //===----------------------------------------------------------------------===//
11025 // Namespace Handling
11026 //===----------------------------------------------------------------------===//
11027 
11028 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11029 /// reopened.
11030 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11031                                             SourceLocation Loc,
11032                                             IdentifierInfo *II, bool *IsInline,
11033                                             NamespaceDecl *PrevNS) {
11034   assert(*IsInline != PrevNS->isInline());
11035 
11036   if (PrevNS->isInline())
11037     // The user probably just forgot the 'inline', so suggest that it
11038     // be added back.
11039     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11040       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11041   else
11042     S.Diag(Loc, diag::err_inline_namespace_mismatch);
11043 
11044   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11045   *IsInline = PrevNS->isInline();
11046 }
11047 
11048 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11049 /// definition.
11050 Decl *Sema::ActOnStartNamespaceDef(
11051     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
11052     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
11053     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
11054   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11055   // For anonymous namespace, take the location of the left brace.
11056   SourceLocation Loc = II ? IdentLoc : LBrace;
11057   bool IsInline = InlineLoc.isValid();
11058   bool IsInvalid = false;
11059   bool IsStd = false;
11060   bool AddToKnown = false;
11061   Scope *DeclRegionScope = NamespcScope->getParent();
11062 
11063   NamespaceDecl *PrevNS = nullptr;
11064   if (II) {
11065     // C++ [namespace.def]p2:
11066     //   The identifier in an original-namespace-definition shall not
11067     //   have been previously defined in the declarative region in
11068     //   which the original-namespace-definition appears. The
11069     //   identifier in an original-namespace-definition is the name of
11070     //   the namespace. Subsequently in that declarative region, it is
11071     //   treated as an original-namespace-name.
11072     //
11073     // Since namespace names are unique in their scope, and we don't
11074     // look through using directives, just look for any ordinary names
11075     // as if by qualified name lookup.
11076     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11077                    ForExternalRedeclaration);
11078     LookupQualifiedName(R, CurContext->getRedeclContext());
11079     NamedDecl *PrevDecl =
11080         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11081     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11082 
11083     if (PrevNS) {
11084       // This is an extended namespace definition.
11085       if (IsInline != PrevNS->isInline())
11086         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11087                                         &IsInline, PrevNS);
11088     } else if (PrevDecl) {
11089       // This is an invalid name redefinition.
11090       Diag(Loc, diag::err_redefinition_different_kind)
11091         << II;
11092       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11093       IsInvalid = true;
11094       // Continue on to push Namespc as current DeclContext and return it.
11095     } else if (II->isStr("std") &&
11096                CurContext->getRedeclContext()->isTranslationUnit()) {
11097       // This is the first "real" definition of the namespace "std", so update
11098       // our cache of the "std" namespace to point at this definition.
11099       PrevNS = getStdNamespace();
11100       IsStd = true;
11101       AddToKnown = !IsInline;
11102     } else {
11103       // We've seen this namespace for the first time.
11104       AddToKnown = !IsInline;
11105     }
11106   } else {
11107     // Anonymous namespaces.
11108 
11109     // Determine whether the parent already has an anonymous namespace.
11110     DeclContext *Parent = CurContext->getRedeclContext();
11111     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11112       PrevNS = TU->getAnonymousNamespace();
11113     } else {
11114       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11115       PrevNS = ND->getAnonymousNamespace();
11116     }
11117 
11118     if (PrevNS && IsInline != PrevNS->isInline())
11119       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11120                                       &IsInline, PrevNS);
11121   }
11122 
11123   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
11124                                                  StartLoc, Loc, II, PrevNS);
11125   if (IsInvalid)
11126     Namespc->setInvalidDecl();
11127 
11128   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11129   AddPragmaAttributes(DeclRegionScope, Namespc);
11130 
11131   // FIXME: Should we be merging attributes?
11132   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11133     PushNamespaceVisibilityAttr(Attr, Loc);
11134 
11135   if (IsStd)
11136     StdNamespace = Namespc;
11137   if (AddToKnown)
11138     KnownNamespaces[Namespc] = false;
11139 
11140   if (II) {
11141     PushOnScopeChains(Namespc, DeclRegionScope);
11142   } else {
11143     // Link the anonymous namespace into its parent.
11144     DeclContext *Parent = CurContext->getRedeclContext();
11145     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11146       TU->setAnonymousNamespace(Namespc);
11147     } else {
11148       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11149     }
11150 
11151     CurContext->addDecl(Namespc);
11152 
11153     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11154     //   behaves as if it were replaced by
11155     //     namespace unique { /* empty body */ }
11156     //     using namespace unique;
11157     //     namespace unique { namespace-body }
11158     //   where all occurrences of 'unique' in a translation unit are
11159     //   replaced by the same identifier and this identifier differs
11160     //   from all other identifiers in the entire program.
11161 
11162     // We just create the namespace with an empty name and then add an
11163     // implicit using declaration, just like the standard suggests.
11164     //
11165     // CodeGen enforces the "universally unique" aspect by giving all
11166     // declarations semantically contained within an anonymous
11167     // namespace internal linkage.
11168 
11169     if (!PrevNS) {
11170       UD = UsingDirectiveDecl::Create(Context, Parent,
11171                                       /* 'using' */ LBrace,
11172                                       /* 'namespace' */ SourceLocation(),
11173                                       /* qualifier */ NestedNameSpecifierLoc(),
11174                                       /* identifier */ SourceLocation(),
11175                                       Namespc,
11176                                       /* Ancestor */ Parent);
11177       UD->setImplicit();
11178       Parent->addDecl(UD);
11179     }
11180   }
11181 
11182   ActOnDocumentableDecl(Namespc);
11183 
11184   // Although we could have an invalid decl (i.e. the namespace name is a
11185   // redefinition), push it as current DeclContext and try to continue parsing.
11186   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11187   // for the namespace has the declarations that showed up in that particular
11188   // namespace definition.
11189   PushDeclContext(NamespcScope, Namespc);
11190   return Namespc;
11191 }
11192 
11193 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11194 /// is a namespace alias, returns the namespace it points to.
11195 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11196   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11197     return AD->getNamespace();
11198   return dyn_cast_or_null<NamespaceDecl>(D);
11199 }
11200 
11201 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11202 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11203 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11204   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11205   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11206   Namespc->setRBraceLoc(RBrace);
11207   PopDeclContext();
11208   if (Namespc->hasAttr<VisibilityAttr>())
11209     PopPragmaVisibility(true, RBrace);
11210   // If this namespace contains an export-declaration, export it now.
11211   if (DeferredExportedNamespaces.erase(Namespc))
11212     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11213 }
11214 
11215 CXXRecordDecl *Sema::getStdBadAlloc() const {
11216   return cast_or_null<CXXRecordDecl>(
11217                                   StdBadAlloc.get(Context.getExternalSource()));
11218 }
11219 
11220 EnumDecl *Sema::getStdAlignValT() const {
11221   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11222 }
11223 
11224 NamespaceDecl *Sema::getStdNamespace() const {
11225   return cast_or_null<NamespaceDecl>(
11226                                  StdNamespace.get(Context.getExternalSource()));
11227 }
11228 
11229 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11230   if (!StdExperimentalNamespaceCache) {
11231     if (auto Std = getStdNamespace()) {
11232       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11233                           SourceLocation(), LookupNamespaceName);
11234       if (!LookupQualifiedName(Result, Std) ||
11235           !(StdExperimentalNamespaceCache =
11236                 Result.getAsSingle<NamespaceDecl>()))
11237         Result.suppressDiagnostics();
11238     }
11239   }
11240   return StdExperimentalNamespaceCache;
11241 }
11242 
11243 namespace {
11244 
11245 enum UnsupportedSTLSelect {
11246   USS_InvalidMember,
11247   USS_MissingMember,
11248   USS_NonTrivial,
11249   USS_Other
11250 };
11251 
11252 struct InvalidSTLDiagnoser {
11253   Sema &S;
11254   SourceLocation Loc;
11255   QualType TyForDiags;
11256 
11257   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11258                       const VarDecl *VD = nullptr) {
11259     {
11260       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11261                << TyForDiags << ((int)Sel);
11262       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11263         assert(!Name.empty());
11264         D << Name;
11265       }
11266     }
11267     if (Sel == USS_InvalidMember) {
11268       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11269           << VD << VD->getSourceRange();
11270     }
11271     return QualType();
11272   }
11273 };
11274 } // namespace
11275 
11276 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11277                                            SourceLocation Loc,
11278                                            ComparisonCategoryUsage Usage) {
11279   assert(getLangOpts().CPlusPlus &&
11280          "Looking for comparison category type outside of C++.");
11281 
11282   // Use an elaborated type for diagnostics which has a name containing the
11283   // prepended 'std' namespace but not any inline namespace names.
11284   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11285     auto *NNS =
11286         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11287     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11288   };
11289 
11290   // Check if we've already successfully checked the comparison category type
11291   // before. If so, skip checking it again.
11292   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11293   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11294     // The only thing we need to check is that the type has a reachable
11295     // definition in the current context.
11296     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11297       return QualType();
11298 
11299     return Info->getType();
11300   }
11301 
11302   // If lookup failed
11303   if (!Info) {
11304     std::string NameForDiags = "std::";
11305     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11306     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11307         << NameForDiags << (int)Usage;
11308     return QualType();
11309   }
11310 
11311   assert(Info->Kind == Kind);
11312   assert(Info->Record);
11313 
11314   // Update the Record decl in case we encountered a forward declaration on our
11315   // first pass. FIXME: This is a bit of a hack.
11316   if (Info->Record->hasDefinition())
11317     Info->Record = Info->Record->getDefinition();
11318 
11319   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11320     return QualType();
11321 
11322   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11323 
11324   if (!Info->Record->isTriviallyCopyable())
11325     return UnsupportedSTLError(USS_NonTrivial);
11326 
11327   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11328     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11329     // Tolerate empty base classes.
11330     if (Base->isEmpty())
11331       continue;
11332     // Reject STL implementations which have at least one non-empty base.
11333     return UnsupportedSTLError();
11334   }
11335 
11336   // Check that the STL has implemented the types using a single integer field.
11337   // This expectation allows better codegen for builtin operators. We require:
11338   //   (1) The class has exactly one field.
11339   //   (2) The field is an integral or enumeration type.
11340   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11341   if (std::distance(FIt, FEnd) != 1 ||
11342       !FIt->getType()->isIntegralOrEnumerationType()) {
11343     return UnsupportedSTLError();
11344   }
11345 
11346   // Build each of the require values and store them in Info.
11347   for (ComparisonCategoryResult CCR :
11348        ComparisonCategories::getPossibleResultsForType(Kind)) {
11349     StringRef MemName = ComparisonCategories::getResultString(CCR);
11350     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11351 
11352     if (!ValInfo)
11353       return UnsupportedSTLError(USS_MissingMember, MemName);
11354 
11355     VarDecl *VD = ValInfo->VD;
11356     assert(VD && "should not be null!");
11357 
11358     // Attempt to diagnose reasons why the STL definition of this type
11359     // might be foobar, including it failing to be a constant expression.
11360     // TODO Handle more ways the lookup or result can be invalid.
11361     if (!VD->isStaticDataMember() ||
11362         !VD->isUsableInConstantExpressions(Context))
11363       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11364 
11365     // Attempt to evaluate the var decl as a constant expression and extract
11366     // the value of its first field as a ICE. If this fails, the STL
11367     // implementation is not supported.
11368     if (!ValInfo->hasValidIntValue())
11369       return UnsupportedSTLError();
11370 
11371     MarkVariableReferenced(Loc, VD);
11372   }
11373 
11374   // We've successfully built the required types and expressions. Update
11375   // the cache and return the newly cached value.
11376   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11377   return Info->getType();
11378 }
11379 
11380 /// Retrieve the special "std" namespace, which may require us to
11381 /// implicitly define the namespace.
11382 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11383   if (!StdNamespace) {
11384     // The "std" namespace has not yet been defined, so build one implicitly.
11385     StdNamespace = NamespaceDecl::Create(Context,
11386                                          Context.getTranslationUnitDecl(),
11387                                          /*Inline=*/false,
11388                                          SourceLocation(), SourceLocation(),
11389                                          &PP.getIdentifierTable().get("std"),
11390                                          /*PrevDecl=*/nullptr);
11391     getStdNamespace()->setImplicit(true);
11392   }
11393 
11394   return getStdNamespace();
11395 }
11396 
11397 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11398   assert(getLangOpts().CPlusPlus &&
11399          "Looking for std::initializer_list outside of C++.");
11400 
11401   // We're looking for implicit instantiations of
11402   // template <typename E> class std::initializer_list.
11403 
11404   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11405     return false;
11406 
11407   ClassTemplateDecl *Template = nullptr;
11408   const TemplateArgument *Arguments = nullptr;
11409 
11410   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11411 
11412     ClassTemplateSpecializationDecl *Specialization =
11413         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11414     if (!Specialization)
11415       return false;
11416 
11417     Template = Specialization->getSpecializedTemplate();
11418     Arguments = Specialization->getTemplateArgs().data();
11419   } else if (const TemplateSpecializationType *TST =
11420                  Ty->getAs<TemplateSpecializationType>()) {
11421     Template = dyn_cast_or_null<ClassTemplateDecl>(
11422         TST->getTemplateName().getAsTemplateDecl());
11423     Arguments = TST->getArgs();
11424   }
11425   if (!Template)
11426     return false;
11427 
11428   if (!StdInitializerList) {
11429     // Haven't recognized std::initializer_list yet, maybe this is it.
11430     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11431     if (TemplateClass->getIdentifier() !=
11432             &PP.getIdentifierTable().get("initializer_list") ||
11433         !getStdNamespace()->InEnclosingNamespaceSetOf(
11434             TemplateClass->getDeclContext()))
11435       return false;
11436     // This is a template called std::initializer_list, but is it the right
11437     // template?
11438     TemplateParameterList *Params = Template->getTemplateParameters();
11439     if (Params->getMinRequiredArguments() != 1)
11440       return false;
11441     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11442       return false;
11443 
11444     // It's the right template.
11445     StdInitializerList = Template;
11446   }
11447 
11448   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11449     return false;
11450 
11451   // This is an instance of std::initializer_list. Find the argument type.
11452   if (Element)
11453     *Element = Arguments[0].getAsType();
11454   return true;
11455 }
11456 
11457 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11458   NamespaceDecl *Std = S.getStdNamespace();
11459   if (!Std) {
11460     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11461     return nullptr;
11462   }
11463 
11464   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11465                       Loc, Sema::LookupOrdinaryName);
11466   if (!S.LookupQualifiedName(Result, Std)) {
11467     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11468     return nullptr;
11469   }
11470   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11471   if (!Template) {
11472     Result.suppressDiagnostics();
11473     // We found something weird. Complain about the first thing we found.
11474     NamedDecl *Found = *Result.begin();
11475     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11476     return nullptr;
11477   }
11478 
11479   // We found some template called std::initializer_list. Now verify that it's
11480   // correct.
11481   TemplateParameterList *Params = Template->getTemplateParameters();
11482   if (Params->getMinRequiredArguments() != 1 ||
11483       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11484     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11485     return nullptr;
11486   }
11487 
11488   return Template;
11489 }
11490 
11491 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11492   if (!StdInitializerList) {
11493     StdInitializerList = LookupStdInitializerList(*this, Loc);
11494     if (!StdInitializerList)
11495       return QualType();
11496   }
11497 
11498   TemplateArgumentListInfo Args(Loc, Loc);
11499   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11500                                        Context.getTrivialTypeSourceInfo(Element,
11501                                                                         Loc)));
11502   return Context.getCanonicalType(
11503       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11504 }
11505 
11506 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11507   // C++ [dcl.init.list]p2:
11508   //   A constructor is an initializer-list constructor if its first parameter
11509   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11510   //   std::initializer_list<E> for some type E, and either there are no other
11511   //   parameters or else all other parameters have default arguments.
11512   if (!Ctor->hasOneParamOrDefaultArgs())
11513     return false;
11514 
11515   QualType ArgType = Ctor->getParamDecl(0)->getType();
11516   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11517     ArgType = RT->getPointeeType().getUnqualifiedType();
11518 
11519   return isStdInitializerList(ArgType, nullptr);
11520 }
11521 
11522 /// Determine whether a using statement is in a context where it will be
11523 /// apply in all contexts.
11524 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11525   switch (CurContext->getDeclKind()) {
11526     case Decl::TranslationUnit:
11527       return true;
11528     case Decl::LinkageSpec:
11529       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11530     default:
11531       return false;
11532   }
11533 }
11534 
11535 namespace {
11536 
11537 // Callback to only accept typo corrections that are namespaces.
11538 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11539 public:
11540   bool ValidateCandidate(const TypoCorrection &candidate) override {
11541     if (NamedDecl *ND = candidate.getCorrectionDecl())
11542       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11543     return false;
11544   }
11545 
11546   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11547     return std::make_unique<NamespaceValidatorCCC>(*this);
11548   }
11549 };
11550 
11551 }
11552 
11553 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11554                                        CXXScopeSpec &SS,
11555                                        SourceLocation IdentLoc,
11556                                        IdentifierInfo *Ident) {
11557   R.clear();
11558   NamespaceValidatorCCC CCC{};
11559   if (TypoCorrection Corrected =
11560           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11561                         Sema::CTK_ErrorRecovery)) {
11562     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11563       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11564       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11565                               Ident->getName().equals(CorrectedStr);
11566       S.diagnoseTypo(Corrected,
11567                      S.PDiag(diag::err_using_directive_member_suggest)
11568                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11569                      S.PDiag(diag::note_namespace_defined_here));
11570     } else {
11571       S.diagnoseTypo(Corrected,
11572                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11573                      S.PDiag(diag::note_namespace_defined_here));
11574     }
11575     R.addDecl(Corrected.getFoundDecl());
11576     return true;
11577   }
11578   return false;
11579 }
11580 
11581 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11582                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11583                                 SourceLocation IdentLoc,
11584                                 IdentifierInfo *NamespcName,
11585                                 const ParsedAttributesView &AttrList) {
11586   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11587   assert(NamespcName && "Invalid NamespcName.");
11588   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11589 
11590   // This can only happen along a recovery path.
11591   while (S->isTemplateParamScope())
11592     S = S->getParent();
11593   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11594 
11595   UsingDirectiveDecl *UDir = nullptr;
11596   NestedNameSpecifier *Qualifier = nullptr;
11597   if (SS.isSet())
11598     Qualifier = SS.getScopeRep();
11599 
11600   // Lookup namespace name.
11601   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11602   LookupParsedName(R, S, &SS);
11603   if (R.isAmbiguous())
11604     return nullptr;
11605 
11606   if (R.empty()) {
11607     R.clear();
11608     // Allow "using namespace std;" or "using namespace ::std;" even if
11609     // "std" hasn't been defined yet, for GCC compatibility.
11610     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11611         NamespcName->isStr("std")) {
11612       Diag(IdentLoc, diag::ext_using_undefined_std);
11613       R.addDecl(getOrCreateStdNamespace());
11614       R.resolveKind();
11615     }
11616     // Otherwise, attempt typo correction.
11617     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11618   }
11619 
11620   if (!R.empty()) {
11621     NamedDecl *Named = R.getRepresentativeDecl();
11622     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11623     assert(NS && "expected namespace decl");
11624 
11625     // The use of a nested name specifier may trigger deprecation warnings.
11626     DiagnoseUseOfDecl(Named, IdentLoc);
11627 
11628     // C++ [namespace.udir]p1:
11629     //   A using-directive specifies that the names in the nominated
11630     //   namespace can be used in the scope in which the
11631     //   using-directive appears after the using-directive. During
11632     //   unqualified name lookup (3.4.1), the names appear as if they
11633     //   were declared in the nearest enclosing namespace which
11634     //   contains both the using-directive and the nominated
11635     //   namespace. [Note: in this context, "contains" means "contains
11636     //   directly or indirectly". ]
11637 
11638     // Find enclosing context containing both using-directive and
11639     // nominated namespace.
11640     DeclContext *CommonAncestor = NS;
11641     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11642       CommonAncestor = CommonAncestor->getParent();
11643 
11644     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11645                                       SS.getWithLocInContext(Context),
11646                                       IdentLoc, Named, CommonAncestor);
11647 
11648     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11649         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11650       Diag(IdentLoc, diag::warn_using_directive_in_header);
11651     }
11652 
11653     PushUsingDirective(S, UDir);
11654   } else {
11655     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11656   }
11657 
11658   if (UDir)
11659     ProcessDeclAttributeList(S, UDir, AttrList);
11660 
11661   return UDir;
11662 }
11663 
11664 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11665   // If the scope has an associated entity and the using directive is at
11666   // namespace or translation unit scope, add the UsingDirectiveDecl into
11667   // its lookup structure so qualified name lookup can find it.
11668   DeclContext *Ctx = S->getEntity();
11669   if (Ctx && !Ctx->isFunctionOrMethod())
11670     Ctx->addDecl(UDir);
11671   else
11672     // Otherwise, it is at block scope. The using-directives will affect lookup
11673     // only to the end of the scope.
11674     S->PushUsingDirective(UDir);
11675 }
11676 
11677 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11678                                   SourceLocation UsingLoc,
11679                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11680                                   UnqualifiedId &Name,
11681                                   SourceLocation EllipsisLoc,
11682                                   const ParsedAttributesView &AttrList) {
11683   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11684 
11685   if (SS.isEmpty()) {
11686     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11687     return nullptr;
11688   }
11689 
11690   switch (Name.getKind()) {
11691   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11692   case UnqualifiedIdKind::IK_Identifier:
11693   case UnqualifiedIdKind::IK_OperatorFunctionId:
11694   case UnqualifiedIdKind::IK_LiteralOperatorId:
11695   case UnqualifiedIdKind::IK_ConversionFunctionId:
11696     break;
11697 
11698   case UnqualifiedIdKind::IK_ConstructorName:
11699   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11700     // C++11 inheriting constructors.
11701     Diag(Name.getBeginLoc(),
11702          getLangOpts().CPlusPlus11
11703              ? diag::warn_cxx98_compat_using_decl_constructor
11704              : diag::err_using_decl_constructor)
11705         << SS.getRange();
11706 
11707     if (getLangOpts().CPlusPlus11) break;
11708 
11709     return nullptr;
11710 
11711   case UnqualifiedIdKind::IK_DestructorName:
11712     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11713     return nullptr;
11714 
11715   case UnqualifiedIdKind::IK_TemplateId:
11716     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11717         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11718     return nullptr;
11719 
11720   case UnqualifiedIdKind::IK_DeductionGuideName:
11721     llvm_unreachable("cannot parse qualified deduction guide name");
11722   }
11723 
11724   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11725   DeclarationName TargetName = TargetNameInfo.getName();
11726   if (!TargetName)
11727     return nullptr;
11728 
11729   // Warn about access declarations.
11730   if (UsingLoc.isInvalid()) {
11731     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11732                                  ? diag::err_access_decl
11733                                  : diag::warn_access_decl_deprecated)
11734         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11735   }
11736 
11737   if (EllipsisLoc.isInvalid()) {
11738     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11739         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11740       return nullptr;
11741   } else {
11742     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11743         !TargetNameInfo.containsUnexpandedParameterPack()) {
11744       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11745         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11746       EllipsisLoc = SourceLocation();
11747     }
11748   }
11749 
11750   NamedDecl *UD =
11751       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11752                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11753                             /*IsInstantiation*/ false,
11754                             AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11755   if (UD)
11756     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11757 
11758   return UD;
11759 }
11760 
11761 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
11762                                       SourceLocation UsingLoc,
11763                                       SourceLocation EnumLoc,
11764                                       const DeclSpec &DS) {
11765   switch (DS.getTypeSpecType()) {
11766   case DeclSpec::TST_error:
11767     // This will already have been diagnosed
11768     return nullptr;
11769 
11770   case DeclSpec::TST_enum:
11771     break;
11772 
11773   case DeclSpec::TST_typename:
11774     Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
11775     return nullptr;
11776 
11777   default:
11778     llvm_unreachable("unexpected DeclSpec type");
11779   }
11780 
11781   // As with enum-decls, we ignore attributes for now.
11782   auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
11783   if (auto *Def = Enum->getDefinition())
11784     Enum = Def;
11785 
11786   auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
11787                                        DS.getTypeSpecTypeNameLoc(), Enum);
11788   if (UD)
11789     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11790 
11791   return UD;
11792 }
11793 
11794 /// Determine whether a using declaration considers the given
11795 /// declarations as "equivalent", e.g., if they are redeclarations of
11796 /// the same entity or are both typedefs of the same type.
11797 static bool
11798 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11799   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11800     return true;
11801 
11802   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11803     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11804       return Context.hasSameType(TD1->getUnderlyingType(),
11805                                  TD2->getUnderlyingType());
11806 
11807   // Two using_if_exists using-declarations are equivalent if both are
11808   // unresolved.
11809   if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11810       isa<UnresolvedUsingIfExistsDecl>(D2))
11811     return true;
11812 
11813   return false;
11814 }
11815 
11816 
11817 /// Determines whether to create a using shadow decl for a particular
11818 /// decl, given the set of decls existing prior to this using lookup.
11819 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
11820                                 const LookupResult &Previous,
11821                                 UsingShadowDecl *&PrevShadow) {
11822   // Diagnose finding a decl which is not from a base class of the
11823   // current class.  We do this now because there are cases where this
11824   // function will silently decide not to build a shadow decl, which
11825   // will pre-empt further diagnostics.
11826   //
11827   // We don't need to do this in C++11 because we do the check once on
11828   // the qualifier.
11829   //
11830   // FIXME: diagnose the following if we care enough:
11831   //   struct A { int foo; };
11832   //   struct B : A { using A::foo; };
11833   //   template <class T> struct C : A {};
11834   //   template <class T> struct D : C<T> { using B::foo; } // <---
11835   // This is invalid (during instantiation) in C++03 because B::foo
11836   // resolves to the using decl in B, which is not a base class of D<T>.
11837   // We can't diagnose it immediately because C<T> is an unknown
11838   // specialization. The UsingShadowDecl in D<T> then points directly
11839   // to A::foo, which will look well-formed when we instantiate.
11840   // The right solution is to not collapse the shadow-decl chain.
11841   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
11842     if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
11843       DeclContext *OrigDC = Orig->getDeclContext();
11844 
11845       // Handle enums and anonymous structs.
11846       if (isa<EnumDecl>(OrigDC))
11847         OrigDC = OrigDC->getParent();
11848       CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11849       while (OrigRec->isAnonymousStructOrUnion())
11850         OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11851 
11852       if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11853         if (OrigDC == CurContext) {
11854           Diag(Using->getLocation(),
11855                diag::err_using_decl_nested_name_specifier_is_current_class)
11856               << Using->getQualifierLoc().getSourceRange();
11857           Diag(Orig->getLocation(), diag::note_using_decl_target);
11858           Using->setInvalidDecl();
11859           return true;
11860         }
11861 
11862         Diag(Using->getQualifierLoc().getBeginLoc(),
11863              diag::err_using_decl_nested_name_specifier_is_not_base_class)
11864             << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
11865             << Using->getQualifierLoc().getSourceRange();
11866         Diag(Orig->getLocation(), diag::note_using_decl_target);
11867         Using->setInvalidDecl();
11868         return true;
11869       }
11870     }
11871 
11872   if (Previous.empty()) return false;
11873 
11874   NamedDecl *Target = Orig;
11875   if (isa<UsingShadowDecl>(Target))
11876     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11877 
11878   // If the target happens to be one of the previous declarations, we
11879   // don't have a conflict.
11880   //
11881   // FIXME: but we might be increasing its access, in which case we
11882   // should redeclare it.
11883   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11884   bool FoundEquivalentDecl = false;
11885   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11886          I != E; ++I) {
11887     NamedDecl *D = (*I)->getUnderlyingDecl();
11888     // We can have UsingDecls in our Previous results because we use the same
11889     // LookupResult for checking whether the UsingDecl itself is a valid
11890     // redeclaration.
11891     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
11892       continue;
11893 
11894     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11895       // C++ [class.mem]p19:
11896       //   If T is the name of a class, then [every named member other than
11897       //   a non-static data member] shall have a name different from T
11898       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11899           !isa<IndirectFieldDecl>(Target) &&
11900           !isa<UnresolvedUsingValueDecl>(Target) &&
11901           DiagnoseClassNameShadow(
11902               CurContext,
11903               DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
11904         return true;
11905     }
11906 
11907     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11908       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11909         PrevShadow = Shadow;
11910       FoundEquivalentDecl = true;
11911     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11912       // We don't conflict with an existing using shadow decl of an equivalent
11913       // declaration, but we're not a redeclaration of it.
11914       FoundEquivalentDecl = true;
11915     }
11916 
11917     if (isVisible(D))
11918       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11919   }
11920 
11921   if (FoundEquivalentDecl)
11922     return false;
11923 
11924   // Always emit a diagnostic for a mismatch between an unresolved
11925   // using_if_exists and a resolved using declaration in either direction.
11926   if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
11927       (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
11928     if (!NonTag && !Tag)
11929       return false;
11930     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11931     Diag(Target->getLocation(), diag::note_using_decl_target);
11932     Diag((NonTag ? NonTag : Tag)->getLocation(),
11933          diag::note_using_decl_conflict);
11934     BUD->setInvalidDecl();
11935     return true;
11936   }
11937 
11938   if (FunctionDecl *FD = Target->getAsFunction()) {
11939     NamedDecl *OldDecl = nullptr;
11940     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11941                           /*IsForUsingDecl*/ true)) {
11942     case Ovl_Overload:
11943       return false;
11944 
11945     case Ovl_NonFunction:
11946       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11947       break;
11948 
11949     // We found a decl with the exact signature.
11950     case Ovl_Match:
11951       // If we're in a record, we want to hide the target, so we
11952       // return true (without a diagnostic) to tell the caller not to
11953       // build a shadow decl.
11954       if (CurContext->isRecord())
11955         return true;
11956 
11957       // If we're not in a record, this is an error.
11958       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11959       break;
11960     }
11961 
11962     Diag(Target->getLocation(), diag::note_using_decl_target);
11963     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11964     BUD->setInvalidDecl();
11965     return true;
11966   }
11967 
11968   // Target is not a function.
11969 
11970   if (isa<TagDecl>(Target)) {
11971     // No conflict between a tag and a non-tag.
11972     if (!Tag) return false;
11973 
11974     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11975     Diag(Target->getLocation(), diag::note_using_decl_target);
11976     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11977     BUD->setInvalidDecl();
11978     return true;
11979   }
11980 
11981   // No conflict between a tag and a non-tag.
11982   if (!NonTag) return false;
11983 
11984   Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11985   Diag(Target->getLocation(), diag::note_using_decl_target);
11986   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11987   BUD->setInvalidDecl();
11988   return true;
11989 }
11990 
11991 /// Determine whether a direct base class is a virtual base class.
11992 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11993   if (!Derived->getNumVBases())
11994     return false;
11995   for (auto &B : Derived->bases())
11996     if (B.getType()->getAsCXXRecordDecl() == Base)
11997       return B.isVirtual();
11998   llvm_unreachable("not a direct base class");
11999 }
12000 
12001 /// Builds a shadow declaration corresponding to a 'using' declaration.
12002 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12003                                             NamedDecl *Orig,
12004                                             UsingShadowDecl *PrevDecl) {
12005   // If we resolved to another shadow declaration, just coalesce them.
12006   NamedDecl *Target = Orig;
12007   if (isa<UsingShadowDecl>(Target)) {
12008     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12009     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12010   }
12011 
12012   NamedDecl *NonTemplateTarget = Target;
12013   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12014     NonTemplateTarget = TargetTD->getTemplatedDecl();
12015 
12016   UsingShadowDecl *Shadow;
12017   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12018     UsingDecl *Using = cast<UsingDecl>(BUD);
12019     bool IsVirtualBase =
12020         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12021                             Using->getQualifier()->getAsRecordDecl());
12022     Shadow = ConstructorUsingShadowDecl::Create(
12023         Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12024   } else {
12025     Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12026                                      Target->getDeclName(), BUD, Target);
12027   }
12028   BUD->addShadowDecl(Shadow);
12029 
12030   Shadow->setAccess(BUD->getAccess());
12031   if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12032     Shadow->setInvalidDecl();
12033 
12034   Shadow->setPreviousDecl(PrevDecl);
12035 
12036   if (S)
12037     PushOnScopeChains(Shadow, S);
12038   else
12039     CurContext->addDecl(Shadow);
12040 
12041 
12042   return Shadow;
12043 }
12044 
12045 /// Hides a using shadow declaration.  This is required by the current
12046 /// using-decl implementation when a resolvable using declaration in a
12047 /// class is followed by a declaration which would hide or override
12048 /// one or more of the using decl's targets; for example:
12049 ///
12050 ///   struct Base { void foo(int); };
12051 ///   struct Derived : Base {
12052 ///     using Base::foo;
12053 ///     void foo(int);
12054 ///   };
12055 ///
12056 /// The governing language is C++03 [namespace.udecl]p12:
12057 ///
12058 ///   When a using-declaration brings names from a base class into a
12059 ///   derived class scope, member functions in the derived class
12060 ///   override and/or hide member functions with the same name and
12061 ///   parameter types in a base class (rather than conflicting).
12062 ///
12063 /// There are two ways to implement this:
12064 ///   (1) optimistically create shadow decls when they're not hidden
12065 ///       by existing declarations, or
12066 ///   (2) don't create any shadow decls (or at least don't make them
12067 ///       visible) until we've fully parsed/instantiated the class.
12068 /// The problem with (1) is that we might have to retroactively remove
12069 /// a shadow decl, which requires several O(n) operations because the
12070 /// decl structures are (very reasonably) not designed for removal.
12071 /// (2) avoids this but is very fiddly and phase-dependent.
12072 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12073   if (Shadow->getDeclName().getNameKind() ==
12074         DeclarationName::CXXConversionFunctionName)
12075     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12076 
12077   // Remove it from the DeclContext...
12078   Shadow->getDeclContext()->removeDecl(Shadow);
12079 
12080   // ...and the scope, if applicable...
12081   if (S) {
12082     S->RemoveDecl(Shadow);
12083     IdResolver.RemoveDecl(Shadow);
12084   }
12085 
12086   // ...and the using decl.
12087   Shadow->getIntroducer()->removeShadowDecl(Shadow);
12088 
12089   // TODO: complain somehow if Shadow was used.  It shouldn't
12090   // be possible for this to happen, because...?
12091 }
12092 
12093 /// Find the base specifier for a base class with the given type.
12094 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12095                                                 QualType DesiredBase,
12096                                                 bool &AnyDependentBases) {
12097   // Check whether the named type is a direct base class.
12098   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12099     .getUnqualifiedType();
12100   for (auto &Base : Derived->bases()) {
12101     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12102     if (CanonicalDesiredBase == BaseType)
12103       return &Base;
12104     if (BaseType->isDependentType())
12105       AnyDependentBases = true;
12106   }
12107   return nullptr;
12108 }
12109 
12110 namespace {
12111 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12112 public:
12113   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12114                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12115       : HasTypenameKeyword(HasTypenameKeyword),
12116         IsInstantiation(IsInstantiation), OldNNS(NNS),
12117         RequireMemberOf(RequireMemberOf) {}
12118 
12119   bool ValidateCandidate(const TypoCorrection &Candidate) override {
12120     NamedDecl *ND = Candidate.getCorrectionDecl();
12121 
12122     // Keywords are not valid here.
12123     if (!ND || isa<NamespaceDecl>(ND))
12124       return false;
12125 
12126     // Completely unqualified names are invalid for a 'using' declaration.
12127     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12128       return false;
12129 
12130     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12131     // reject.
12132 
12133     if (RequireMemberOf) {
12134       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12135       if (FoundRecord && FoundRecord->isInjectedClassName()) {
12136         // No-one ever wants a using-declaration to name an injected-class-name
12137         // of a base class, unless they're declaring an inheriting constructor.
12138         ASTContext &Ctx = ND->getASTContext();
12139         if (!Ctx.getLangOpts().CPlusPlus11)
12140           return false;
12141         QualType FoundType = Ctx.getRecordType(FoundRecord);
12142 
12143         // Check that the injected-class-name is named as a member of its own
12144         // type; we don't want to suggest 'using Derived::Base;', since that
12145         // means something else.
12146         NestedNameSpecifier *Specifier =
12147             Candidate.WillReplaceSpecifier()
12148                 ? Candidate.getCorrectionSpecifier()
12149                 : OldNNS;
12150         if (!Specifier->getAsType() ||
12151             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12152           return false;
12153 
12154         // Check that this inheriting constructor declaration actually names a
12155         // direct base class of the current class.
12156         bool AnyDependentBases = false;
12157         if (!findDirectBaseWithType(RequireMemberOf,
12158                                     Ctx.getRecordType(FoundRecord),
12159                                     AnyDependentBases) &&
12160             !AnyDependentBases)
12161           return false;
12162       } else {
12163         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12164         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12165           return false;
12166 
12167         // FIXME: Check that the base class member is accessible?
12168       }
12169     } else {
12170       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12171       if (FoundRecord && FoundRecord->isInjectedClassName())
12172         return false;
12173     }
12174 
12175     if (isa<TypeDecl>(ND))
12176       return HasTypenameKeyword || !IsInstantiation;
12177 
12178     return !HasTypenameKeyword;
12179   }
12180 
12181   std::unique_ptr<CorrectionCandidateCallback> clone() override {
12182     return std::make_unique<UsingValidatorCCC>(*this);
12183   }
12184 
12185 private:
12186   bool HasTypenameKeyword;
12187   bool IsInstantiation;
12188   NestedNameSpecifier *OldNNS;
12189   CXXRecordDecl *RequireMemberOf;
12190 };
12191 } // end anonymous namespace
12192 
12193 /// Remove decls we can't actually see from a lookup being used to declare
12194 /// shadow using decls.
12195 ///
12196 /// \param S - The scope of the potential shadow decl
12197 /// \param Previous - The lookup of a potential shadow decl's name.
12198 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12199   // It is really dumb that we have to do this.
12200   LookupResult::Filter F = Previous.makeFilter();
12201   while (F.hasNext()) {
12202     NamedDecl *D = F.next();
12203     if (!isDeclInScope(D, CurContext, S))
12204       F.erase();
12205     // If we found a local extern declaration that's not ordinarily visible,
12206     // and this declaration is being added to a non-block scope, ignore it.
12207     // We're only checking for scope conflicts here, not also for violations
12208     // of the linkage rules.
12209     else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12210              !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12211       F.erase();
12212   }
12213   F.done();
12214 }
12215 
12216 /// Builds a using declaration.
12217 ///
12218 /// \param IsInstantiation - Whether this call arises from an
12219 ///   instantiation of an unresolved using declaration.  We treat
12220 ///   the lookup differently for these declarations.
12221 NamedDecl *Sema::BuildUsingDeclaration(
12222     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12223     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12224     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12225     const ParsedAttributesView &AttrList, bool IsInstantiation,
12226     bool IsUsingIfExists) {
12227   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12228   SourceLocation IdentLoc = NameInfo.getLoc();
12229   assert(IdentLoc.isValid() && "Invalid TargetName location.");
12230 
12231   // FIXME: We ignore attributes for now.
12232 
12233   // For an inheriting constructor declaration, the name of the using
12234   // declaration is the name of a constructor in this class, not in the
12235   // base class.
12236   DeclarationNameInfo UsingName = NameInfo;
12237   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12238     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12239       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12240           Context.getCanonicalType(Context.getRecordType(RD))));
12241 
12242   // Do the redeclaration lookup in the current scope.
12243   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12244                         ForVisibleRedeclaration);
12245   Previous.setHideTags(false);
12246   if (S) {
12247     LookupName(Previous, S);
12248 
12249     FilterUsingLookup(S, Previous);
12250   } else {
12251     assert(IsInstantiation && "no scope in non-instantiation");
12252     if (CurContext->isRecord())
12253       LookupQualifiedName(Previous, CurContext);
12254     else {
12255       // No redeclaration check is needed here; in non-member contexts we
12256       // diagnosed all possible conflicts with other using-declarations when
12257       // building the template:
12258       //
12259       // For a dependent non-type using declaration, the only valid case is
12260       // if we instantiate to a single enumerator. We check for conflicts
12261       // between shadow declarations we introduce, and we check in the template
12262       // definition for conflicts between a non-type using declaration and any
12263       // other declaration, which together covers all cases.
12264       //
12265       // A dependent typename using declaration will never successfully
12266       // instantiate, since it will always name a class member, so we reject
12267       // that in the template definition.
12268     }
12269   }
12270 
12271   // Check for invalid redeclarations.
12272   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12273                                   SS, IdentLoc, Previous))
12274     return nullptr;
12275 
12276   // 'using_if_exists' doesn't make sense on an inherited constructor.
12277   if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12278                              DeclarationName::CXXConstructorName) {
12279     Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12280     return nullptr;
12281   }
12282 
12283   DeclContext *LookupContext = computeDeclContext(SS);
12284   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12285   if (!LookupContext || EllipsisLoc.isValid()) {
12286     NamedDecl *D;
12287     // Dependent scope, or an unexpanded pack
12288     if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12289                                                   SS, NameInfo, IdentLoc))
12290       return nullptr;
12291 
12292     if (HasTypenameKeyword) {
12293       // FIXME: not all declaration name kinds are legal here
12294       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12295                                               UsingLoc, TypenameLoc,
12296                                               QualifierLoc,
12297                                               IdentLoc, NameInfo.getName(),
12298                                               EllipsisLoc);
12299     } else {
12300       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12301                                            QualifierLoc, NameInfo, EllipsisLoc);
12302     }
12303     D->setAccess(AS);
12304     CurContext->addDecl(D);
12305     ProcessDeclAttributeList(S, D, AttrList);
12306     return D;
12307   }
12308 
12309   auto Build = [&](bool Invalid) {
12310     UsingDecl *UD =
12311         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12312                           UsingName, HasTypenameKeyword);
12313     UD->setAccess(AS);
12314     CurContext->addDecl(UD);
12315     ProcessDeclAttributeList(S, UD, AttrList);
12316     UD->setInvalidDecl(Invalid);
12317     return UD;
12318   };
12319   auto BuildInvalid = [&]{ return Build(true); };
12320   auto BuildValid = [&]{ return Build(false); };
12321 
12322   if (RequireCompleteDeclContext(SS, LookupContext))
12323     return BuildInvalid();
12324 
12325   // Look up the target name.
12326   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12327 
12328   // Unlike most lookups, we don't always want to hide tag
12329   // declarations: tag names are visible through the using declaration
12330   // even if hidden by ordinary names, *except* in a dependent context
12331   // where they may be used by two-phase lookup.
12332   if (!IsInstantiation)
12333     R.setHideTags(false);
12334 
12335   // For the purposes of this lookup, we have a base object type
12336   // equal to that of the current context.
12337   if (CurContext->isRecord()) {
12338     R.setBaseObjectType(
12339                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12340   }
12341 
12342   LookupQualifiedName(R, LookupContext);
12343 
12344   // Validate the context, now we have a lookup
12345   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12346                               IdentLoc, &R))
12347     return nullptr;
12348 
12349   if (R.empty() && IsUsingIfExists)
12350     R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12351                                                   UsingName.getName()),
12352               AS_public);
12353 
12354   // Try to correct typos if possible. If constructor name lookup finds no
12355   // results, that means the named class has no explicit constructors, and we
12356   // suppressed declaring implicit ones (probably because it's dependent or
12357   // invalid).
12358   if (R.empty() &&
12359       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12360     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12361     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12362     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12363     auto *II = NameInfo.getName().getAsIdentifierInfo();
12364     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12365         CurContext->isStdNamespace() &&
12366         isa<TranslationUnitDecl>(LookupContext) &&
12367         getSourceManager().isInSystemHeader(UsingLoc))
12368       return nullptr;
12369     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12370                           dyn_cast<CXXRecordDecl>(CurContext));
12371     if (TypoCorrection Corrected =
12372             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12373                         CTK_ErrorRecovery)) {
12374       // We reject candidates where DroppedSpecifier == true, hence the
12375       // literal '0' below.
12376       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12377                                 << NameInfo.getName() << LookupContext << 0
12378                                 << SS.getRange());
12379 
12380       // If we picked a correction with no attached Decl we can't do anything
12381       // useful with it, bail out.
12382       NamedDecl *ND = Corrected.getCorrectionDecl();
12383       if (!ND)
12384         return BuildInvalid();
12385 
12386       // If we corrected to an inheriting constructor, handle it as one.
12387       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12388       if (RD && RD->isInjectedClassName()) {
12389         // The parent of the injected class name is the class itself.
12390         RD = cast<CXXRecordDecl>(RD->getParent());
12391 
12392         // Fix up the information we'll use to build the using declaration.
12393         if (Corrected.WillReplaceSpecifier()) {
12394           NestedNameSpecifierLocBuilder Builder;
12395           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12396                               QualifierLoc.getSourceRange());
12397           QualifierLoc = Builder.getWithLocInContext(Context);
12398         }
12399 
12400         // In this case, the name we introduce is the name of a derived class
12401         // constructor.
12402         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12403         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12404             Context.getCanonicalType(Context.getRecordType(CurClass))));
12405         UsingName.setNamedTypeInfo(nullptr);
12406         for (auto *Ctor : LookupConstructors(RD))
12407           R.addDecl(Ctor);
12408         R.resolveKind();
12409       } else {
12410         // FIXME: Pick up all the declarations if we found an overloaded
12411         // function.
12412         UsingName.setName(ND->getDeclName());
12413         R.addDecl(ND);
12414       }
12415     } else {
12416       Diag(IdentLoc, diag::err_no_member)
12417         << NameInfo.getName() << LookupContext << SS.getRange();
12418       return BuildInvalid();
12419     }
12420   }
12421 
12422   if (R.isAmbiguous())
12423     return BuildInvalid();
12424 
12425   if (HasTypenameKeyword) {
12426     // If we asked for a typename and got a non-type decl, error out.
12427     if (!R.getAsSingle<TypeDecl>() &&
12428         !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12429       Diag(IdentLoc, diag::err_using_typename_non_type);
12430       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12431         Diag((*I)->getUnderlyingDecl()->getLocation(),
12432              diag::note_using_decl_target);
12433       return BuildInvalid();
12434     }
12435   } else {
12436     // If we asked for a non-typename and we got a type, error out,
12437     // but only if this is an instantiation of an unresolved using
12438     // decl.  Otherwise just silently find the type name.
12439     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12440       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12441       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12442       return BuildInvalid();
12443     }
12444   }
12445 
12446   // C++14 [namespace.udecl]p6:
12447   // A using-declaration shall not name a namespace.
12448   if (R.getAsSingle<NamespaceDecl>()) {
12449     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12450       << SS.getRange();
12451     return BuildInvalid();
12452   }
12453 
12454   UsingDecl *UD = BuildValid();
12455 
12456   // Some additional rules apply to inheriting constructors.
12457   if (UsingName.getName().getNameKind() ==
12458         DeclarationName::CXXConstructorName) {
12459     // Suppress access diagnostics; the access check is instead performed at the
12460     // point of use for an inheriting constructor.
12461     R.suppressDiagnostics();
12462     if (CheckInheritingConstructorUsingDecl(UD))
12463       return UD;
12464   }
12465 
12466   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12467     UsingShadowDecl *PrevDecl = nullptr;
12468     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12469       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12470   }
12471 
12472   return UD;
12473 }
12474 
12475 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12476                                            SourceLocation UsingLoc,
12477                                            SourceLocation EnumLoc,
12478                                            SourceLocation NameLoc,
12479                                            EnumDecl *ED) {
12480   bool Invalid = false;
12481 
12482   if (CurContext->getRedeclContext()->isRecord()) {
12483     /// In class scope, check if this is a duplicate, for better a diagnostic.
12484     DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12485     LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12486                           ForVisibleRedeclaration);
12487 
12488     LookupName(Previous, S);
12489 
12490     for (NamedDecl *D : Previous)
12491       if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12492         if (UED->getEnumDecl() == ED) {
12493           Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12494               << SourceRange(EnumLoc, NameLoc);
12495           Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12496           Invalid = true;
12497           break;
12498         }
12499   }
12500 
12501   if (RequireCompleteEnumDecl(ED, NameLoc))
12502     Invalid = true;
12503 
12504   UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12505                                             EnumLoc, NameLoc, ED);
12506   UD->setAccess(AS);
12507   CurContext->addDecl(UD);
12508 
12509   if (Invalid) {
12510     UD->setInvalidDecl();
12511     return UD;
12512   }
12513 
12514   // Create the shadow decls for each enumerator
12515   for (EnumConstantDecl *EC : ED->enumerators()) {
12516     UsingShadowDecl *PrevDecl = nullptr;
12517     DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12518     LookupResult Previous(*this, DNI, LookupOrdinaryName,
12519                           ForVisibleRedeclaration);
12520     LookupName(Previous, S);
12521     FilterUsingLookup(S, Previous);
12522 
12523     if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12524       BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12525   }
12526 
12527   return UD;
12528 }
12529 
12530 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12531                                     ArrayRef<NamedDecl *> Expansions) {
12532   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12533          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12534          isa<UsingPackDecl>(InstantiatedFrom));
12535 
12536   auto *UPD =
12537       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12538   UPD->setAccess(InstantiatedFrom->getAccess());
12539   CurContext->addDecl(UPD);
12540   return UPD;
12541 }
12542 
12543 /// Additional checks for a using declaration referring to a constructor name.
12544 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12545   assert(!UD->hasTypename() && "expecting a constructor name");
12546 
12547   const Type *SourceType = UD->getQualifier()->getAsType();
12548   assert(SourceType &&
12549          "Using decl naming constructor doesn't have type in scope spec.");
12550   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12551 
12552   // Check whether the named type is a direct base class.
12553   bool AnyDependentBases = false;
12554   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12555                                       AnyDependentBases);
12556   if (!Base && !AnyDependentBases) {
12557     Diag(UD->getUsingLoc(),
12558          diag::err_using_decl_constructor_not_in_direct_base)
12559       << UD->getNameInfo().getSourceRange()
12560       << QualType(SourceType, 0) << TargetClass;
12561     UD->setInvalidDecl();
12562     return true;
12563   }
12564 
12565   if (Base)
12566     Base->setInheritConstructors();
12567 
12568   return false;
12569 }
12570 
12571 /// Checks that the given using declaration is not an invalid
12572 /// redeclaration.  Note that this is checking only for the using decl
12573 /// itself, not for any ill-formedness among the UsingShadowDecls.
12574 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12575                                        bool HasTypenameKeyword,
12576                                        const CXXScopeSpec &SS,
12577                                        SourceLocation NameLoc,
12578                                        const LookupResult &Prev) {
12579   NestedNameSpecifier *Qual = SS.getScopeRep();
12580 
12581   // C++03 [namespace.udecl]p8:
12582   // C++0x [namespace.udecl]p10:
12583   //   A using-declaration is a declaration and can therefore be used
12584   //   repeatedly where (and only where) multiple declarations are
12585   //   allowed.
12586   //
12587   // That's in non-member contexts.
12588   if (!CurContext->getRedeclContext()->isRecord()) {
12589     // A dependent qualifier outside a class can only ever resolve to an
12590     // enumeration type. Therefore it conflicts with any other non-type
12591     // declaration in the same scope.
12592     // FIXME: How should we check for dependent type-type conflicts at block
12593     // scope?
12594     if (Qual->isDependent() && !HasTypenameKeyword) {
12595       for (auto *D : Prev) {
12596         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12597           bool OldCouldBeEnumerator =
12598               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12599           Diag(NameLoc,
12600                OldCouldBeEnumerator ? diag::err_redefinition
12601                                     : diag::err_redefinition_different_kind)
12602               << Prev.getLookupName();
12603           Diag(D->getLocation(), diag::note_previous_definition);
12604           return true;
12605         }
12606       }
12607     }
12608     return false;
12609   }
12610 
12611   const NestedNameSpecifier *CNNS =
12612       Context.getCanonicalNestedNameSpecifier(Qual);
12613   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12614     NamedDecl *D = *I;
12615 
12616     bool DTypename;
12617     NestedNameSpecifier *DQual;
12618     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12619       DTypename = UD->hasTypename();
12620       DQual = UD->getQualifier();
12621     } else if (UnresolvedUsingValueDecl *UD
12622                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12623       DTypename = false;
12624       DQual = UD->getQualifier();
12625     } else if (UnresolvedUsingTypenameDecl *UD
12626                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12627       DTypename = true;
12628       DQual = UD->getQualifier();
12629     } else continue;
12630 
12631     // using decls differ if one says 'typename' and the other doesn't.
12632     // FIXME: non-dependent using decls?
12633     if (HasTypenameKeyword != DTypename) continue;
12634 
12635     // using decls differ if they name different scopes (but note that
12636     // template instantiation can cause this check to trigger when it
12637     // didn't before instantiation).
12638     if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12639       continue;
12640 
12641     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12642     Diag(D->getLocation(), diag::note_using_decl) << 1;
12643     return true;
12644   }
12645 
12646   return false;
12647 }
12648 
12649 /// Checks that the given nested-name qualifier used in a using decl
12650 /// in the current context is appropriately related to the current
12651 /// scope.  If an error is found, diagnoses it and returns true.
12652 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12653 /// result of that lookup. UD is likewise nullptr, except when we have an
12654 /// already-populated UsingDecl whose shadow decls contain the same information
12655 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12656 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12657                                    const CXXScopeSpec &SS,
12658                                    const DeclarationNameInfo &NameInfo,
12659                                    SourceLocation NameLoc,
12660                                    const LookupResult *R, const UsingDecl *UD) {
12661   DeclContext *NamedContext = computeDeclContext(SS);
12662   assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
12663          "resolvable context must have exactly one set of decls");
12664 
12665   // C++ 20 permits using an enumerator that does not have a class-hierarchy
12666   // relationship.
12667   bool Cxx20Enumerator = false;
12668   if (NamedContext) {
12669     EnumConstantDecl *EC = nullptr;
12670     if (R)
12671       EC = R->getAsSingle<EnumConstantDecl>();
12672     else if (UD && UD->shadow_size() == 1)
12673       EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12674     if (EC)
12675       Cxx20Enumerator = getLangOpts().CPlusPlus20;
12676 
12677     if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12678       // C++14 [namespace.udecl]p7:
12679       // A using-declaration shall not name a scoped enumerator.
12680       // C++20 p1099 permits enumerators.
12681       if (EC && R && ED->isScoped())
12682         Diag(SS.getBeginLoc(),
12683              getLangOpts().CPlusPlus20
12684                  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12685                  : diag::ext_using_decl_scoped_enumerator)
12686             << SS.getRange();
12687 
12688       // We want to consider the scope of the enumerator
12689       NamedContext = ED->getDeclContext();
12690     }
12691   }
12692 
12693   if (!CurContext->isRecord()) {
12694     // C++03 [namespace.udecl]p3:
12695     // C++0x [namespace.udecl]p8:
12696     //   A using-declaration for a class member shall be a member-declaration.
12697     // C++20 [namespace.udecl]p7
12698     //   ... other than an enumerator ...
12699 
12700     // If we weren't able to compute a valid scope, it might validly be a
12701     // dependent class or enumeration scope. If we have a 'typename' keyword,
12702     // the scope must resolve to a class type.
12703     if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12704                      : !HasTypename)
12705       return false; // OK
12706 
12707     Diag(NameLoc,
12708          Cxx20Enumerator
12709              ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12710              : diag::err_using_decl_can_not_refer_to_class_member)
12711         << SS.getRange();
12712 
12713     if (Cxx20Enumerator)
12714       return false; // OK
12715 
12716     auto *RD = NamedContext
12717                    ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12718                    : nullptr;
12719     if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12720       // See if there's a helpful fixit
12721 
12722       if (!R) {
12723         // We will have already diagnosed the problem on the template
12724         // definition,  Maybe we should do so again?
12725       } else if (R->getAsSingle<TypeDecl>()) {
12726         if (getLangOpts().CPlusPlus11) {
12727           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12728           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12729             << 0 // alias declaration
12730             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12731                                           NameInfo.getName().getAsString() +
12732                                               " = ");
12733         } else {
12734           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12735           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12736           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12737             << 1 // typedef declaration
12738             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12739             << FixItHint::CreateInsertion(
12740                    InsertLoc, " " + NameInfo.getName().getAsString());
12741         }
12742       } else if (R->getAsSingle<VarDecl>()) {
12743         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12744         // repeating the type of the static data member here.
12745         FixItHint FixIt;
12746         if (getLangOpts().CPlusPlus11) {
12747           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12748           FixIt = FixItHint::CreateReplacement(
12749               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12750         }
12751 
12752         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12753           << 2 // reference declaration
12754           << FixIt;
12755       } else if (R->getAsSingle<EnumConstantDecl>()) {
12756         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12757         // repeating the type of the enumeration here, and we can't do so if
12758         // the type is anonymous.
12759         FixItHint FixIt;
12760         if (getLangOpts().CPlusPlus11) {
12761           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12762           FixIt = FixItHint::CreateReplacement(
12763               UsingLoc,
12764               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12765         }
12766 
12767         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12768           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12769           << FixIt;
12770       }
12771     }
12772 
12773     return true; // Fail
12774   }
12775 
12776   // If the named context is dependent, we can't decide much.
12777   if (!NamedContext) {
12778     // FIXME: in C++0x, we can diagnose if we can prove that the
12779     // nested-name-specifier does not refer to a base class, which is
12780     // still possible in some cases.
12781 
12782     // Otherwise we have to conservatively report that things might be
12783     // okay.
12784     return false;
12785   }
12786 
12787   // The current scope is a record.
12788   if (!NamedContext->isRecord()) {
12789     // Ideally this would point at the last name in the specifier,
12790     // but we don't have that level of source info.
12791     Diag(SS.getBeginLoc(),
12792          Cxx20Enumerator
12793              ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12794              : diag::err_using_decl_nested_name_specifier_is_not_class)
12795         << SS.getScopeRep() << SS.getRange();
12796 
12797     if (Cxx20Enumerator)
12798       return false; // OK
12799 
12800     return true;
12801   }
12802 
12803   if (!NamedContext->isDependentContext() &&
12804       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12805     return true;
12806 
12807   if (getLangOpts().CPlusPlus11) {
12808     // C++11 [namespace.udecl]p3:
12809     //   In a using-declaration used as a member-declaration, the
12810     //   nested-name-specifier shall name a base class of the class
12811     //   being defined.
12812 
12813     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12814                                  cast<CXXRecordDecl>(NamedContext))) {
12815 
12816       if (Cxx20Enumerator) {
12817         Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12818             << SS.getRange();
12819         return false;
12820       }
12821 
12822       if (CurContext == NamedContext) {
12823         Diag(SS.getBeginLoc(),
12824              diag::err_using_decl_nested_name_specifier_is_current_class)
12825             << SS.getRange();
12826         return !getLangOpts().CPlusPlus20;
12827       }
12828 
12829       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12830         Diag(SS.getBeginLoc(),
12831              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12832             << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12833             << SS.getRange();
12834       }
12835       return true;
12836     }
12837 
12838     return false;
12839   }
12840 
12841   // C++03 [namespace.udecl]p4:
12842   //   A using-declaration used as a member-declaration shall refer
12843   //   to a member of a base class of the class being defined [etc.].
12844 
12845   // Salient point: SS doesn't have to name a base class as long as
12846   // lookup only finds members from base classes.  Therefore we can
12847   // diagnose here only if we can prove that that can't happen,
12848   // i.e. if the class hierarchies provably don't intersect.
12849 
12850   // TODO: it would be nice if "definitely valid" results were cached
12851   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12852   // need to be repeated.
12853 
12854   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12855   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12856     Bases.insert(Base);
12857     return true;
12858   };
12859 
12860   // Collect all bases. Return false if we find a dependent base.
12861   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12862     return false;
12863 
12864   // Returns true if the base is dependent or is one of the accumulated base
12865   // classes.
12866   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12867     return !Bases.count(Base);
12868   };
12869 
12870   // Return false if the class has a dependent base or if it or one
12871   // of its bases is present in the base set of the current context.
12872   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12873       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12874     return false;
12875 
12876   Diag(SS.getRange().getBegin(),
12877        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12878     << SS.getScopeRep()
12879     << cast<CXXRecordDecl>(CurContext)
12880     << SS.getRange();
12881 
12882   return true;
12883 }
12884 
12885 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12886                                   MultiTemplateParamsArg TemplateParamLists,
12887                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12888                                   const ParsedAttributesView &AttrList,
12889                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12890   // Skip up to the relevant declaration scope.
12891   while (S->isTemplateParamScope())
12892     S = S->getParent();
12893   assert((S->getFlags() & Scope::DeclScope) &&
12894          "got alias-declaration outside of declaration scope");
12895 
12896   if (Type.isInvalid())
12897     return nullptr;
12898 
12899   bool Invalid = false;
12900   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12901   TypeSourceInfo *TInfo = nullptr;
12902   GetTypeFromParser(Type.get(), &TInfo);
12903 
12904   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12905     return nullptr;
12906 
12907   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12908                                       UPPC_DeclarationType)) {
12909     Invalid = true;
12910     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12911                                              TInfo->getTypeLoc().getBeginLoc());
12912   }
12913 
12914   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12915                         TemplateParamLists.size()
12916                             ? forRedeclarationInCurContext()
12917                             : ForVisibleRedeclaration);
12918   LookupName(Previous, S);
12919 
12920   // Warn about shadowing the name of a template parameter.
12921   if (Previous.isSingleResult() &&
12922       Previous.getFoundDecl()->isTemplateParameter()) {
12923     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12924     Previous.clear();
12925   }
12926 
12927   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12928          "name in alias declaration must be an identifier");
12929   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12930                                                Name.StartLocation,
12931                                                Name.Identifier, TInfo);
12932 
12933   NewTD->setAccess(AS);
12934 
12935   if (Invalid)
12936     NewTD->setInvalidDecl();
12937 
12938   ProcessDeclAttributeList(S, NewTD, AttrList);
12939   AddPragmaAttributes(S, NewTD);
12940 
12941   CheckTypedefForVariablyModifiedType(S, NewTD);
12942   Invalid |= NewTD->isInvalidDecl();
12943 
12944   bool Redeclaration = false;
12945 
12946   NamedDecl *NewND;
12947   if (TemplateParamLists.size()) {
12948     TypeAliasTemplateDecl *OldDecl = nullptr;
12949     TemplateParameterList *OldTemplateParams = nullptr;
12950 
12951     if (TemplateParamLists.size() != 1) {
12952       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12953         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12954          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12955     }
12956     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12957 
12958     // Check that we can declare a template here.
12959     if (CheckTemplateDeclScope(S, TemplateParams))
12960       return nullptr;
12961 
12962     // Only consider previous declarations in the same scope.
12963     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12964                          /*ExplicitInstantiationOrSpecialization*/false);
12965     if (!Previous.empty()) {
12966       Redeclaration = true;
12967 
12968       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12969       if (!OldDecl && !Invalid) {
12970         Diag(UsingLoc, diag::err_redefinition_different_kind)
12971           << Name.Identifier;
12972 
12973         NamedDecl *OldD = Previous.getRepresentativeDecl();
12974         if (OldD->getLocation().isValid())
12975           Diag(OldD->getLocation(), diag::note_previous_definition);
12976 
12977         Invalid = true;
12978       }
12979 
12980       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12981         if (TemplateParameterListsAreEqual(TemplateParams,
12982                                            OldDecl->getTemplateParameters(),
12983                                            /*Complain=*/true,
12984                                            TPL_TemplateMatch))
12985           OldTemplateParams =
12986               OldDecl->getMostRecentDecl()->getTemplateParameters();
12987         else
12988           Invalid = true;
12989 
12990         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12991         if (!Invalid &&
12992             !Context.hasSameType(OldTD->getUnderlyingType(),
12993                                  NewTD->getUnderlyingType())) {
12994           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12995           // but we can't reasonably accept it.
12996           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12997             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12998           if (OldTD->getLocation().isValid())
12999             Diag(OldTD->getLocation(), diag::note_previous_definition);
13000           Invalid = true;
13001         }
13002       }
13003     }
13004 
13005     // Merge any previous default template arguments into our parameters,
13006     // and check the parameter list.
13007     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13008                                    TPC_TypeAliasTemplate))
13009       return nullptr;
13010 
13011     TypeAliasTemplateDecl *NewDecl =
13012       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13013                                     Name.Identifier, TemplateParams,
13014                                     NewTD);
13015     NewTD->setDescribedAliasTemplate(NewDecl);
13016 
13017     NewDecl->setAccess(AS);
13018 
13019     if (Invalid)
13020       NewDecl->setInvalidDecl();
13021     else if (OldDecl) {
13022       NewDecl->setPreviousDecl(OldDecl);
13023       CheckRedeclarationInModule(NewDecl, OldDecl);
13024     }
13025 
13026     NewND = NewDecl;
13027   } else {
13028     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13029       setTagNameForLinkagePurposes(TD, NewTD);
13030       handleTagNumbering(TD, S);
13031     }
13032     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13033     NewND = NewTD;
13034   }
13035 
13036   PushOnScopeChains(NewND, S);
13037   ActOnDocumentableDecl(NewND);
13038   return NewND;
13039 }
13040 
13041 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13042                                    SourceLocation AliasLoc,
13043                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
13044                                    SourceLocation IdentLoc,
13045                                    IdentifierInfo *Ident) {
13046 
13047   // Lookup the namespace name.
13048   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13049   LookupParsedName(R, S, &SS);
13050 
13051   if (R.isAmbiguous())
13052     return nullptr;
13053 
13054   if (R.empty()) {
13055     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13056       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13057       return nullptr;
13058     }
13059   }
13060   assert(!R.isAmbiguous() && !R.empty());
13061   NamedDecl *ND = R.getRepresentativeDecl();
13062 
13063   // Check if we have a previous declaration with the same name.
13064   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13065                      ForVisibleRedeclaration);
13066   LookupName(PrevR, S);
13067 
13068   // Check we're not shadowing a template parameter.
13069   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13070     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13071     PrevR.clear();
13072   }
13073 
13074   // Filter out any other lookup result from an enclosing scope.
13075   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13076                        /*AllowInlineNamespace*/false);
13077 
13078   // Find the previous declaration and check that we can redeclare it.
13079   NamespaceAliasDecl *Prev = nullptr;
13080   if (PrevR.isSingleResult()) {
13081     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13082     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13083       // We already have an alias with the same name that points to the same
13084       // namespace; check that it matches.
13085       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13086         Prev = AD;
13087       } else if (isVisible(PrevDecl)) {
13088         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13089           << Alias;
13090         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13091           << AD->getNamespace();
13092         return nullptr;
13093       }
13094     } else if (isVisible(PrevDecl)) {
13095       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13096                             ? diag::err_redefinition
13097                             : diag::err_redefinition_different_kind;
13098       Diag(AliasLoc, DiagID) << Alias;
13099       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13100       return nullptr;
13101     }
13102   }
13103 
13104   // The use of a nested name specifier may trigger deprecation warnings.
13105   DiagnoseUseOfDecl(ND, IdentLoc);
13106 
13107   NamespaceAliasDecl *AliasDecl =
13108     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13109                                Alias, SS.getWithLocInContext(Context),
13110                                IdentLoc, ND);
13111   if (Prev)
13112     AliasDecl->setPreviousDecl(Prev);
13113 
13114   PushOnScopeChains(AliasDecl, S);
13115   return AliasDecl;
13116 }
13117 
13118 namespace {
13119 struct SpecialMemberExceptionSpecInfo
13120     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13121   SourceLocation Loc;
13122   Sema::ImplicitExceptionSpecification ExceptSpec;
13123 
13124   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13125                                  Sema::CXXSpecialMember CSM,
13126                                  Sema::InheritedConstructorInfo *ICI,
13127                                  SourceLocation Loc)
13128       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13129 
13130   bool visitBase(CXXBaseSpecifier *Base);
13131   bool visitField(FieldDecl *FD);
13132 
13133   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13134                            unsigned Quals);
13135 
13136   void visitSubobjectCall(Subobject Subobj,
13137                           Sema::SpecialMemberOverloadResult SMOR);
13138 };
13139 }
13140 
13141 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13142   auto *RT = Base->getType()->getAs<RecordType>();
13143   if (!RT)
13144     return false;
13145 
13146   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13147   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13148   if (auto *BaseCtor = SMOR.getMethod()) {
13149     visitSubobjectCall(Base, BaseCtor);
13150     return false;
13151   }
13152 
13153   visitClassSubobject(BaseClass, Base, 0);
13154   return false;
13155 }
13156 
13157 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13158   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13159     Expr *E = FD->getInClassInitializer();
13160     if (!E)
13161       // FIXME: It's a little wasteful to build and throw away a
13162       // CXXDefaultInitExpr here.
13163       // FIXME: We should have a single context note pointing at Loc, and
13164       // this location should be MD->getLocation() instead, since that's
13165       // the location where we actually use the default init expression.
13166       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13167     if (E)
13168       ExceptSpec.CalledExpr(E);
13169   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13170                             ->getAs<RecordType>()) {
13171     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13172                         FD->getType().getCVRQualifiers());
13173   }
13174   return false;
13175 }
13176 
13177 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13178                                                          Subobject Subobj,
13179                                                          unsigned Quals) {
13180   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13181   bool IsMutable = Field && Field->isMutable();
13182   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13183 }
13184 
13185 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13186     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13187   // Note, if lookup fails, it doesn't matter what exception specification we
13188   // choose because the special member will be deleted.
13189   if (CXXMethodDecl *MD = SMOR.getMethod())
13190     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13191 }
13192 
13193 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13194   llvm::APSInt Result;
13195   ExprResult Converted = CheckConvertedConstantExpression(
13196       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13197   ExplicitSpec.setExpr(Converted.get());
13198   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13199     ExplicitSpec.setKind(Result.getBoolValue()
13200                              ? ExplicitSpecKind::ResolvedTrue
13201                              : ExplicitSpecKind::ResolvedFalse);
13202     return true;
13203   }
13204   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13205   return false;
13206 }
13207 
13208 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13209   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13210   if (!ExplicitExpr->isTypeDependent())
13211     tryResolveExplicitSpecifier(ES);
13212   return ES;
13213 }
13214 
13215 static Sema::ImplicitExceptionSpecification
13216 ComputeDefaultedSpecialMemberExceptionSpec(
13217     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13218     Sema::InheritedConstructorInfo *ICI) {
13219   ComputingExceptionSpec CES(S, MD, Loc);
13220 
13221   CXXRecordDecl *ClassDecl = MD->getParent();
13222 
13223   // C++ [except.spec]p14:
13224   //   An implicitly declared special member function (Clause 12) shall have an
13225   //   exception-specification. [...]
13226   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13227   if (ClassDecl->isInvalidDecl())
13228     return Info.ExceptSpec;
13229 
13230   // FIXME: If this diagnostic fires, we're probably missing a check for
13231   // attempting to resolve an exception specification before it's known
13232   // at a higher level.
13233   if (S.RequireCompleteType(MD->getLocation(),
13234                             S.Context.getRecordType(ClassDecl),
13235                             diag::err_exception_spec_incomplete_type))
13236     return Info.ExceptSpec;
13237 
13238   // C++1z [except.spec]p7:
13239   //   [Look for exceptions thrown by] a constructor selected [...] to
13240   //   initialize a potentially constructed subobject,
13241   // C++1z [except.spec]p8:
13242   //   The exception specification for an implicitly-declared destructor, or a
13243   //   destructor without a noexcept-specifier, is potentially-throwing if and
13244   //   only if any of the destructors for any of its potentially constructed
13245   //   subojects is potentially throwing.
13246   // FIXME: We respect the first rule but ignore the "potentially constructed"
13247   // in the second rule to resolve a core issue (no number yet) that would have
13248   // us reject:
13249   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13250   //   struct B : A {};
13251   //   struct C : B { void f(); };
13252   // ... due to giving B::~B() a non-throwing exception specification.
13253   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13254                                 : Info.VisitAllBases);
13255 
13256   return Info.ExceptSpec;
13257 }
13258 
13259 namespace {
13260 /// RAII object to register a special member as being currently declared.
13261 struct DeclaringSpecialMember {
13262   Sema &S;
13263   Sema::SpecialMemberDecl D;
13264   Sema::ContextRAII SavedContext;
13265   bool WasAlreadyBeingDeclared;
13266 
13267   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13268       : S(S), D(RD, CSM), SavedContext(S, RD) {
13269     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13270     if (WasAlreadyBeingDeclared)
13271       // This almost never happens, but if it does, ensure that our cache
13272       // doesn't contain a stale result.
13273       S.SpecialMemberCache.clear();
13274     else {
13275       // Register a note to be produced if we encounter an error while
13276       // declaring the special member.
13277       Sema::CodeSynthesisContext Ctx;
13278       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13279       // FIXME: We don't have a location to use here. Using the class's
13280       // location maintains the fiction that we declare all special members
13281       // with the class, but (1) it's not clear that lying about that helps our
13282       // users understand what's going on, and (2) there may be outer contexts
13283       // on the stack (some of which are relevant) and printing them exposes
13284       // our lies.
13285       Ctx.PointOfInstantiation = RD->getLocation();
13286       Ctx.Entity = RD;
13287       Ctx.SpecialMember = CSM;
13288       S.pushCodeSynthesisContext(Ctx);
13289     }
13290   }
13291   ~DeclaringSpecialMember() {
13292     if (!WasAlreadyBeingDeclared) {
13293       S.SpecialMembersBeingDeclared.erase(D);
13294       S.popCodeSynthesisContext();
13295     }
13296   }
13297 
13298   /// Are we already trying to declare this special member?
13299   bool isAlreadyBeingDeclared() const {
13300     return WasAlreadyBeingDeclared;
13301   }
13302 };
13303 }
13304 
13305 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13306   // Look up any existing declarations, but don't trigger declaration of all
13307   // implicit special members with this name.
13308   DeclarationName Name = FD->getDeclName();
13309   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13310                  ForExternalRedeclaration);
13311   for (auto *D : FD->getParent()->lookup(Name))
13312     if (auto *Acceptable = R.getAcceptableDecl(D))
13313       R.addDecl(Acceptable);
13314   R.resolveKind();
13315   R.suppressDiagnostics();
13316 
13317   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
13318 }
13319 
13320 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13321                                           QualType ResultTy,
13322                                           ArrayRef<QualType> Args) {
13323   // Build an exception specification pointing back at this constructor.
13324   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13325 
13326   LangAS AS = getDefaultCXXMethodAddrSpace();
13327   if (AS != LangAS::Default) {
13328     EPI.TypeQuals.addAddressSpace(AS);
13329   }
13330 
13331   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13332   SpecialMem->setType(QT);
13333 
13334   // During template instantiation of implicit special member functions we need
13335   // a reliable TypeSourceInfo for the function prototype in order to allow
13336   // functions to be substituted.
13337   if (inTemplateInstantiation() &&
13338       cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13339     TypeSourceInfo *TSI =
13340         Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13341     SpecialMem->setTypeSourceInfo(TSI);
13342   }
13343 }
13344 
13345 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13346                                                      CXXRecordDecl *ClassDecl) {
13347   // C++ [class.ctor]p5:
13348   //   A default constructor for a class X is a constructor of class X
13349   //   that can be called without an argument. If there is no
13350   //   user-declared constructor for class X, a default constructor is
13351   //   implicitly declared. An implicitly-declared default constructor
13352   //   is an inline public member of its class.
13353   assert(ClassDecl->needsImplicitDefaultConstructor() &&
13354          "Should not build implicit default constructor!");
13355 
13356   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13357   if (DSM.isAlreadyBeingDeclared())
13358     return nullptr;
13359 
13360   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13361                                                      CXXDefaultConstructor,
13362                                                      false);
13363 
13364   // Create the actual constructor declaration.
13365   CanQualType ClassType
13366     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13367   SourceLocation ClassLoc = ClassDecl->getLocation();
13368   DeclarationName Name
13369     = Context.DeclarationNames.getCXXConstructorName(ClassType);
13370   DeclarationNameInfo NameInfo(Name, ClassLoc);
13371   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13372       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13373       /*TInfo=*/nullptr, ExplicitSpecifier(),
13374       getCurFPFeatures().isFPConstrained(),
13375       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13376       Constexpr ? ConstexprSpecKind::Constexpr
13377                 : ConstexprSpecKind::Unspecified);
13378   DefaultCon->setAccess(AS_public);
13379   DefaultCon->setDefaulted();
13380 
13381   if (getLangOpts().CUDA) {
13382     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13383                                             DefaultCon,
13384                                             /* ConstRHS */ false,
13385                                             /* Diagnose */ false);
13386   }
13387 
13388   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13389 
13390   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13391   // constructors is easy to compute.
13392   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13393 
13394   // Note that we have declared this constructor.
13395   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13396 
13397   Scope *S = getScopeForContext(ClassDecl);
13398   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13399 
13400   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13401     SetDeclDeleted(DefaultCon, ClassLoc);
13402 
13403   if (S)
13404     PushOnScopeChains(DefaultCon, S, false);
13405   ClassDecl->addDecl(DefaultCon);
13406 
13407   return DefaultCon;
13408 }
13409 
13410 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13411                                             CXXConstructorDecl *Constructor) {
13412   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13413           !Constructor->doesThisDeclarationHaveABody() &&
13414           !Constructor->isDeleted()) &&
13415     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13416   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13417     return;
13418 
13419   CXXRecordDecl *ClassDecl = Constructor->getParent();
13420   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13421 
13422   SynthesizedFunctionScope Scope(*this, Constructor);
13423 
13424   // The exception specification is needed because we are defining the
13425   // function.
13426   ResolveExceptionSpec(CurrentLocation,
13427                        Constructor->getType()->castAs<FunctionProtoType>());
13428   MarkVTableUsed(CurrentLocation, ClassDecl);
13429 
13430   // Add a context note for diagnostics produced after this point.
13431   Scope.addContextNote(CurrentLocation);
13432 
13433   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13434     Constructor->setInvalidDecl();
13435     return;
13436   }
13437 
13438   SourceLocation Loc = Constructor->getEndLoc().isValid()
13439                            ? Constructor->getEndLoc()
13440                            : Constructor->getLocation();
13441   Constructor->setBody(new (Context) CompoundStmt(Loc));
13442   Constructor->markUsed(Context);
13443 
13444   if (ASTMutationListener *L = getASTMutationListener()) {
13445     L->CompletedImplicitDefinition(Constructor);
13446   }
13447 
13448   DiagnoseUninitializedFields(*this, Constructor);
13449 }
13450 
13451 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13452   // Perform any delayed checks on exception specifications.
13453   CheckDelayedMemberExceptionSpecs();
13454 }
13455 
13456 /// Find or create the fake constructor we synthesize to model constructing an
13457 /// object of a derived class via a constructor of a base class.
13458 CXXConstructorDecl *
13459 Sema::findInheritingConstructor(SourceLocation Loc,
13460                                 CXXConstructorDecl *BaseCtor,
13461                                 ConstructorUsingShadowDecl *Shadow) {
13462   CXXRecordDecl *Derived = Shadow->getParent();
13463   SourceLocation UsingLoc = Shadow->getLocation();
13464 
13465   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13466   // For now we use the name of the base class constructor as a member of the
13467   // derived class to indicate a (fake) inherited constructor name.
13468   DeclarationName Name = BaseCtor->getDeclName();
13469 
13470   // Check to see if we already have a fake constructor for this inherited
13471   // constructor call.
13472   for (NamedDecl *Ctor : Derived->lookup(Name))
13473     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13474                                ->getInheritedConstructor()
13475                                .getConstructor(),
13476                            BaseCtor))
13477       return cast<CXXConstructorDecl>(Ctor);
13478 
13479   DeclarationNameInfo NameInfo(Name, UsingLoc);
13480   TypeSourceInfo *TInfo =
13481       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13482   FunctionProtoTypeLoc ProtoLoc =
13483       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13484 
13485   // Check the inherited constructor is valid and find the list of base classes
13486   // from which it was inherited.
13487   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13488 
13489   bool Constexpr =
13490       BaseCtor->isConstexpr() &&
13491       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13492                                         false, BaseCtor, &ICI);
13493 
13494   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13495       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13496       BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13497       /*isInline=*/true,
13498       /*isImplicitlyDeclared=*/true,
13499       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13500       InheritedConstructor(Shadow, BaseCtor),
13501       BaseCtor->getTrailingRequiresClause());
13502   if (Shadow->isInvalidDecl())
13503     DerivedCtor->setInvalidDecl();
13504 
13505   // Build an unevaluated exception specification for this fake constructor.
13506   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13507   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13508   EPI.ExceptionSpec.Type = EST_Unevaluated;
13509   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13510   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13511                                                FPT->getParamTypes(), EPI));
13512 
13513   // Build the parameter declarations.
13514   SmallVector<ParmVarDecl *, 16> ParamDecls;
13515   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13516     TypeSourceInfo *TInfo =
13517         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13518     ParmVarDecl *PD = ParmVarDecl::Create(
13519         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13520         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13521     PD->setScopeInfo(0, I);
13522     PD->setImplicit();
13523     // Ensure attributes are propagated onto parameters (this matters for
13524     // format, pass_object_size, ...).
13525     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13526     ParamDecls.push_back(PD);
13527     ProtoLoc.setParam(I, PD);
13528   }
13529 
13530   // Set up the new constructor.
13531   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13532   DerivedCtor->setAccess(BaseCtor->getAccess());
13533   DerivedCtor->setParams(ParamDecls);
13534   Derived->addDecl(DerivedCtor);
13535 
13536   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13537     SetDeclDeleted(DerivedCtor, UsingLoc);
13538 
13539   return DerivedCtor;
13540 }
13541 
13542 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13543   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13544                                Ctor->getInheritedConstructor().getShadowDecl());
13545   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13546                             /*Diagnose*/true);
13547 }
13548 
13549 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13550                                        CXXConstructorDecl *Constructor) {
13551   CXXRecordDecl *ClassDecl = Constructor->getParent();
13552   assert(Constructor->getInheritedConstructor() &&
13553          !Constructor->doesThisDeclarationHaveABody() &&
13554          !Constructor->isDeleted());
13555   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13556     return;
13557 
13558   // Initializations are performed "as if by a defaulted default constructor",
13559   // so enter the appropriate scope.
13560   SynthesizedFunctionScope Scope(*this, Constructor);
13561 
13562   // The exception specification is needed because we are defining the
13563   // function.
13564   ResolveExceptionSpec(CurrentLocation,
13565                        Constructor->getType()->castAs<FunctionProtoType>());
13566   MarkVTableUsed(CurrentLocation, ClassDecl);
13567 
13568   // Add a context note for diagnostics produced after this point.
13569   Scope.addContextNote(CurrentLocation);
13570 
13571   ConstructorUsingShadowDecl *Shadow =
13572       Constructor->getInheritedConstructor().getShadowDecl();
13573   CXXConstructorDecl *InheritedCtor =
13574       Constructor->getInheritedConstructor().getConstructor();
13575 
13576   // [class.inhctor.init]p1:
13577   //   initialization proceeds as if a defaulted default constructor is used to
13578   //   initialize the D object and each base class subobject from which the
13579   //   constructor was inherited
13580 
13581   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13582   CXXRecordDecl *RD = Shadow->getParent();
13583   SourceLocation InitLoc = Shadow->getLocation();
13584 
13585   // Build explicit initializers for all base classes from which the
13586   // constructor was inherited.
13587   SmallVector<CXXCtorInitializer*, 8> Inits;
13588   for (bool VBase : {false, true}) {
13589     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13590       if (B.isVirtual() != VBase)
13591         continue;
13592 
13593       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13594       if (!BaseRD)
13595         continue;
13596 
13597       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13598       if (!BaseCtor.first)
13599         continue;
13600 
13601       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13602       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13603           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13604 
13605       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13606       Inits.push_back(new (Context) CXXCtorInitializer(
13607           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13608           SourceLocation()));
13609     }
13610   }
13611 
13612   // We now proceed as if for a defaulted default constructor, with the relevant
13613   // initializers replaced.
13614 
13615   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13616     Constructor->setInvalidDecl();
13617     return;
13618   }
13619 
13620   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13621   Constructor->markUsed(Context);
13622 
13623   if (ASTMutationListener *L = getASTMutationListener()) {
13624     L->CompletedImplicitDefinition(Constructor);
13625   }
13626 
13627   DiagnoseUninitializedFields(*this, Constructor);
13628 }
13629 
13630 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13631   // C++ [class.dtor]p2:
13632   //   If a class has no user-declared destructor, a destructor is
13633   //   declared implicitly. An implicitly-declared destructor is an
13634   //   inline public member of its class.
13635   assert(ClassDecl->needsImplicitDestructor());
13636 
13637   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13638   if (DSM.isAlreadyBeingDeclared())
13639     return nullptr;
13640 
13641   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13642                                                      CXXDestructor,
13643                                                      false);
13644 
13645   // Create the actual destructor declaration.
13646   CanQualType ClassType
13647     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13648   SourceLocation ClassLoc = ClassDecl->getLocation();
13649   DeclarationName Name
13650     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13651   DeclarationNameInfo NameInfo(Name, ClassLoc);
13652   CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
13653       Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13654       getCurFPFeatures().isFPConstrained(),
13655       /*isInline=*/true,
13656       /*isImplicitlyDeclared=*/true,
13657       Constexpr ? ConstexprSpecKind::Constexpr
13658                 : ConstexprSpecKind::Unspecified);
13659   Destructor->setAccess(AS_public);
13660   Destructor->setDefaulted();
13661 
13662   if (getLangOpts().CUDA) {
13663     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13664                                             Destructor,
13665                                             /* ConstRHS */ false,
13666                                             /* Diagnose */ false);
13667   }
13668 
13669   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13670 
13671   // We don't need to use SpecialMemberIsTrivial here; triviality for
13672   // destructors is easy to compute.
13673   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13674   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13675                                 ClassDecl->hasTrivialDestructorForCall());
13676 
13677   // Note that we have declared this destructor.
13678   ++getASTContext().NumImplicitDestructorsDeclared;
13679 
13680   Scope *S = getScopeForContext(ClassDecl);
13681   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13682 
13683   // We can't check whether an implicit destructor is deleted before we complete
13684   // the definition of the class, because its validity depends on the alignment
13685   // of the class. We'll check this from ActOnFields once the class is complete.
13686   if (ClassDecl->isCompleteDefinition() &&
13687       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13688     SetDeclDeleted(Destructor, ClassLoc);
13689 
13690   // Introduce this destructor into its scope.
13691   if (S)
13692     PushOnScopeChains(Destructor, S, false);
13693   ClassDecl->addDecl(Destructor);
13694 
13695   return Destructor;
13696 }
13697 
13698 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13699                                     CXXDestructorDecl *Destructor) {
13700   assert((Destructor->isDefaulted() &&
13701           !Destructor->doesThisDeclarationHaveABody() &&
13702           !Destructor->isDeleted()) &&
13703          "DefineImplicitDestructor - call it for implicit default dtor");
13704   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13705     return;
13706 
13707   CXXRecordDecl *ClassDecl = Destructor->getParent();
13708   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13709 
13710   SynthesizedFunctionScope Scope(*this, Destructor);
13711 
13712   // The exception specification is needed because we are defining the
13713   // function.
13714   ResolveExceptionSpec(CurrentLocation,
13715                        Destructor->getType()->castAs<FunctionProtoType>());
13716   MarkVTableUsed(CurrentLocation, ClassDecl);
13717 
13718   // Add a context note for diagnostics produced after this point.
13719   Scope.addContextNote(CurrentLocation);
13720 
13721   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13722                                          Destructor->getParent());
13723 
13724   if (CheckDestructor(Destructor)) {
13725     Destructor->setInvalidDecl();
13726     return;
13727   }
13728 
13729   SourceLocation Loc = Destructor->getEndLoc().isValid()
13730                            ? Destructor->getEndLoc()
13731                            : Destructor->getLocation();
13732   Destructor->setBody(new (Context) CompoundStmt(Loc));
13733   Destructor->markUsed(Context);
13734 
13735   if (ASTMutationListener *L = getASTMutationListener()) {
13736     L->CompletedImplicitDefinition(Destructor);
13737   }
13738 }
13739 
13740 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13741                                           CXXDestructorDecl *Destructor) {
13742   if (Destructor->isInvalidDecl())
13743     return;
13744 
13745   CXXRecordDecl *ClassDecl = Destructor->getParent();
13746   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13747          "implicit complete dtors unneeded outside MS ABI");
13748   assert(ClassDecl->getNumVBases() > 0 &&
13749          "complete dtor only exists for classes with vbases");
13750 
13751   SynthesizedFunctionScope Scope(*this, Destructor);
13752 
13753   // Add a context note for diagnostics produced after this point.
13754   Scope.addContextNote(CurrentLocation);
13755 
13756   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13757 }
13758 
13759 /// Perform any semantic analysis which needs to be delayed until all
13760 /// pending class member declarations have been parsed.
13761 void Sema::ActOnFinishCXXMemberDecls() {
13762   // If the context is an invalid C++ class, just suppress these checks.
13763   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13764     if (Record->isInvalidDecl()) {
13765       DelayedOverridingExceptionSpecChecks.clear();
13766       DelayedEquivalentExceptionSpecChecks.clear();
13767       return;
13768     }
13769     checkForMultipleExportedDefaultConstructors(*this, Record);
13770   }
13771 }
13772 
13773 void Sema::ActOnFinishCXXNonNestedClass() {
13774   referenceDLLExportedClassMethods();
13775 
13776   if (!DelayedDllExportMemberFunctions.empty()) {
13777     SmallVector<CXXMethodDecl*, 4> WorkList;
13778     std::swap(DelayedDllExportMemberFunctions, WorkList);
13779     for (CXXMethodDecl *M : WorkList) {
13780       DefineDefaultedFunction(*this, M, M->getLocation());
13781 
13782       // Pass the method to the consumer to get emitted. This is not necessary
13783       // for explicit instantiation definitions, as they will get emitted
13784       // anyway.
13785       if (M->getParent()->getTemplateSpecializationKind() !=
13786           TSK_ExplicitInstantiationDefinition)
13787         ActOnFinishInlineFunctionDef(M);
13788     }
13789   }
13790 }
13791 
13792 void Sema::referenceDLLExportedClassMethods() {
13793   if (!DelayedDllExportClasses.empty()) {
13794     // Calling ReferenceDllExportedMembers might cause the current function to
13795     // be called again, so use a local copy of DelayedDllExportClasses.
13796     SmallVector<CXXRecordDecl *, 4> WorkList;
13797     std::swap(DelayedDllExportClasses, WorkList);
13798     for (CXXRecordDecl *Class : WorkList)
13799       ReferenceDllExportedMembers(*this, Class);
13800   }
13801 }
13802 
13803 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13804   assert(getLangOpts().CPlusPlus11 &&
13805          "adjusting dtor exception specs was introduced in c++11");
13806 
13807   if (Destructor->isDependentContext())
13808     return;
13809 
13810   // C++11 [class.dtor]p3:
13811   //   A declaration of a destructor that does not have an exception-
13812   //   specification is implicitly considered to have the same exception-
13813   //   specification as an implicit declaration.
13814   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13815   if (DtorType->hasExceptionSpec())
13816     return;
13817 
13818   // Replace the destructor's type, building off the existing one. Fortunately,
13819   // the only thing of interest in the destructor type is its extended info.
13820   // The return and arguments are fixed.
13821   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13822   EPI.ExceptionSpec.Type = EST_Unevaluated;
13823   EPI.ExceptionSpec.SourceDecl = Destructor;
13824   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13825 
13826   // FIXME: If the destructor has a body that could throw, and the newly created
13827   // spec doesn't allow exceptions, we should emit a warning, because this
13828   // change in behavior can break conforming C++03 programs at runtime.
13829   // However, we don't have a body or an exception specification yet, so it
13830   // needs to be done somewhere else.
13831 }
13832 
13833 namespace {
13834 /// An abstract base class for all helper classes used in building the
13835 //  copy/move operators. These classes serve as factory functions and help us
13836 //  avoid using the same Expr* in the AST twice.
13837 class ExprBuilder {
13838   ExprBuilder(const ExprBuilder&) = delete;
13839   ExprBuilder &operator=(const ExprBuilder&) = delete;
13840 
13841 protected:
13842   static Expr *assertNotNull(Expr *E) {
13843     assert(E && "Expression construction must not fail.");
13844     return E;
13845   }
13846 
13847 public:
13848   ExprBuilder() {}
13849   virtual ~ExprBuilder() {}
13850 
13851   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13852 };
13853 
13854 class RefBuilder: public ExprBuilder {
13855   VarDecl *Var;
13856   QualType VarType;
13857 
13858 public:
13859   Expr *build(Sema &S, SourceLocation Loc) const override {
13860     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13861   }
13862 
13863   RefBuilder(VarDecl *Var, QualType VarType)
13864       : Var(Var), VarType(VarType) {}
13865 };
13866 
13867 class ThisBuilder: public ExprBuilder {
13868 public:
13869   Expr *build(Sema &S, SourceLocation Loc) const override {
13870     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13871   }
13872 };
13873 
13874 class CastBuilder: public ExprBuilder {
13875   const ExprBuilder &Builder;
13876   QualType Type;
13877   ExprValueKind Kind;
13878   const CXXCastPath &Path;
13879 
13880 public:
13881   Expr *build(Sema &S, SourceLocation Loc) const override {
13882     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13883                                              CK_UncheckedDerivedToBase, Kind,
13884                                              &Path).get());
13885   }
13886 
13887   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13888               const CXXCastPath &Path)
13889       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13890 };
13891 
13892 class DerefBuilder: public ExprBuilder {
13893   const ExprBuilder &Builder;
13894 
13895 public:
13896   Expr *build(Sema &S, SourceLocation Loc) const override {
13897     return assertNotNull(
13898         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13899   }
13900 
13901   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13902 };
13903 
13904 class MemberBuilder: public ExprBuilder {
13905   const ExprBuilder &Builder;
13906   QualType Type;
13907   CXXScopeSpec SS;
13908   bool IsArrow;
13909   LookupResult &MemberLookup;
13910 
13911 public:
13912   Expr *build(Sema &S, SourceLocation Loc) const override {
13913     return assertNotNull(S.BuildMemberReferenceExpr(
13914         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13915         nullptr, MemberLookup, nullptr, nullptr).get());
13916   }
13917 
13918   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13919                 LookupResult &MemberLookup)
13920       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13921         MemberLookup(MemberLookup) {}
13922 };
13923 
13924 class MoveCastBuilder: public ExprBuilder {
13925   const ExprBuilder &Builder;
13926 
13927 public:
13928   Expr *build(Sema &S, SourceLocation Loc) const override {
13929     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13930   }
13931 
13932   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13933 };
13934 
13935 class LvalueConvBuilder: public ExprBuilder {
13936   const ExprBuilder &Builder;
13937 
13938 public:
13939   Expr *build(Sema &S, SourceLocation Loc) const override {
13940     return assertNotNull(
13941         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13942   }
13943 
13944   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13945 };
13946 
13947 class SubscriptBuilder: public ExprBuilder {
13948   const ExprBuilder &Base;
13949   const ExprBuilder &Index;
13950 
13951 public:
13952   Expr *build(Sema &S, SourceLocation Loc) const override {
13953     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13954         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13955   }
13956 
13957   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13958       : Base(Base), Index(Index) {}
13959 };
13960 
13961 } // end anonymous namespace
13962 
13963 /// When generating a defaulted copy or move assignment operator, if a field
13964 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13965 /// do so. This optimization only applies for arrays of scalars, and for arrays
13966 /// of class type where the selected copy/move-assignment operator is trivial.
13967 static StmtResult
13968 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13969                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13970   // Compute the size of the memory buffer to be copied.
13971   QualType SizeType = S.Context.getSizeType();
13972   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13973                    S.Context.getTypeSizeInChars(T).getQuantity());
13974 
13975   // Take the address of the field references for "from" and "to". We
13976   // directly construct UnaryOperators here because semantic analysis
13977   // does not permit us to take the address of an xvalue.
13978   Expr *From = FromB.build(S, Loc);
13979   From = UnaryOperator::Create(
13980       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13981       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13982   Expr *To = ToB.build(S, Loc);
13983   To = UnaryOperator::Create(
13984       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13985       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13986 
13987   const Type *E = T->getBaseElementTypeUnsafe();
13988   bool NeedsCollectableMemCpy =
13989       E->isRecordType() &&
13990       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13991 
13992   // Create a reference to the __builtin_objc_memmove_collectable function
13993   StringRef MemCpyName = NeedsCollectableMemCpy ?
13994     "__builtin_objc_memmove_collectable" :
13995     "__builtin_memcpy";
13996   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13997                  Sema::LookupOrdinaryName);
13998   S.LookupName(R, S.TUScope, true);
13999 
14000   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14001   if (!MemCpy)
14002     // Something went horribly wrong earlier, and we will have complained
14003     // about it.
14004     return StmtError();
14005 
14006   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14007                                             VK_PRValue, Loc, nullptr);
14008   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14009 
14010   Expr *CallArgs[] = {
14011     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14012   };
14013   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14014                                     Loc, CallArgs, Loc);
14015 
14016   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14017   return Call.getAs<Stmt>();
14018 }
14019 
14020 /// Builds a statement that copies/moves the given entity from \p From to
14021 /// \c To.
14022 ///
14023 /// This routine is used to copy/move the members of a class with an
14024 /// implicitly-declared copy/move assignment operator. When the entities being
14025 /// copied are arrays, this routine builds for loops to copy them.
14026 ///
14027 /// \param S The Sema object used for type-checking.
14028 ///
14029 /// \param Loc The location where the implicit copy/move is being generated.
14030 ///
14031 /// \param T The type of the expressions being copied/moved. Both expressions
14032 /// must have this type.
14033 ///
14034 /// \param To The expression we are copying/moving to.
14035 ///
14036 /// \param From The expression we are copying/moving from.
14037 ///
14038 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14039 /// Otherwise, it's a non-static member subobject.
14040 ///
14041 /// \param Copying Whether we're copying or moving.
14042 ///
14043 /// \param Depth Internal parameter recording the depth of the recursion.
14044 ///
14045 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14046 /// if a memcpy should be used instead.
14047 static StmtResult
14048 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14049                                  const ExprBuilder &To, const ExprBuilder &From,
14050                                  bool CopyingBaseSubobject, bool Copying,
14051                                  unsigned Depth = 0) {
14052   // C++11 [class.copy]p28:
14053   //   Each subobject is assigned in the manner appropriate to its type:
14054   //
14055   //     - if the subobject is of class type, as if by a call to operator= with
14056   //       the subobject as the object expression and the corresponding
14057   //       subobject of x as a single function argument (as if by explicit
14058   //       qualification; that is, ignoring any possible virtual overriding
14059   //       functions in more derived classes);
14060   //
14061   // C++03 [class.copy]p13:
14062   //     - if the subobject is of class type, the copy assignment operator for
14063   //       the class is used (as if by explicit qualification; that is,
14064   //       ignoring any possible virtual overriding functions in more derived
14065   //       classes);
14066   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14067     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14068 
14069     // Look for operator=.
14070     DeclarationName Name
14071       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14072     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14073     S.LookupQualifiedName(OpLookup, ClassDecl, false);
14074 
14075     // Prior to C++11, filter out any result that isn't a copy/move-assignment
14076     // operator.
14077     if (!S.getLangOpts().CPlusPlus11) {
14078       LookupResult::Filter F = OpLookup.makeFilter();
14079       while (F.hasNext()) {
14080         NamedDecl *D = F.next();
14081         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14082           if (Method->isCopyAssignmentOperator() ||
14083               (!Copying && Method->isMoveAssignmentOperator()))
14084             continue;
14085 
14086         F.erase();
14087       }
14088       F.done();
14089     }
14090 
14091     // Suppress the protected check (C++ [class.protected]) for each of the
14092     // assignment operators we found. This strange dance is required when
14093     // we're assigning via a base classes's copy-assignment operator. To
14094     // ensure that we're getting the right base class subobject (without
14095     // ambiguities), we need to cast "this" to that subobject type; to
14096     // ensure that we don't go through the virtual call mechanism, we need
14097     // to qualify the operator= name with the base class (see below). However,
14098     // this means that if the base class has a protected copy assignment
14099     // operator, the protected member access check will fail. So, we
14100     // rewrite "protected" access to "public" access in this case, since we
14101     // know by construction that we're calling from a derived class.
14102     if (CopyingBaseSubobject) {
14103       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14104            L != LEnd; ++L) {
14105         if (L.getAccess() == AS_protected)
14106           L.setAccess(AS_public);
14107       }
14108     }
14109 
14110     // Create the nested-name-specifier that will be used to qualify the
14111     // reference to operator=; this is required to suppress the virtual
14112     // call mechanism.
14113     CXXScopeSpec SS;
14114     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14115     SS.MakeTrivial(S.Context,
14116                    NestedNameSpecifier::Create(S.Context, nullptr, false,
14117                                                CanonicalT),
14118                    Loc);
14119 
14120     // Create the reference to operator=.
14121     ExprResult OpEqualRef
14122       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14123                                    SS, /*TemplateKWLoc=*/SourceLocation(),
14124                                    /*FirstQualifierInScope=*/nullptr,
14125                                    OpLookup,
14126                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
14127                                    /*SuppressQualifierCheck=*/true);
14128     if (OpEqualRef.isInvalid())
14129       return StmtError();
14130 
14131     // Build the call to the assignment operator.
14132 
14133     Expr *FromInst = From.build(S, Loc);
14134     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14135                                                   OpEqualRef.getAs<Expr>(),
14136                                                   Loc, FromInst, Loc);
14137     if (Call.isInvalid())
14138       return StmtError();
14139 
14140     // If we built a call to a trivial 'operator=' while copying an array,
14141     // bail out. We'll replace the whole shebang with a memcpy.
14142     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14143     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14144       return StmtResult((Stmt*)nullptr);
14145 
14146     // Convert to an expression-statement, and clean up any produced
14147     // temporaries.
14148     return S.ActOnExprStmt(Call);
14149   }
14150 
14151   //     - if the subobject is of scalar type, the built-in assignment
14152   //       operator is used.
14153   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14154   if (!ArrayTy) {
14155     ExprResult Assignment = S.CreateBuiltinBinOp(
14156         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14157     if (Assignment.isInvalid())
14158       return StmtError();
14159     return S.ActOnExprStmt(Assignment);
14160   }
14161 
14162   //     - if the subobject is an array, each element is assigned, in the
14163   //       manner appropriate to the element type;
14164 
14165   // Construct a loop over the array bounds, e.g.,
14166   //
14167   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14168   //
14169   // that will copy each of the array elements.
14170   QualType SizeType = S.Context.getSizeType();
14171 
14172   // Create the iteration variable.
14173   IdentifierInfo *IterationVarName = nullptr;
14174   {
14175     SmallString<8> Str;
14176     llvm::raw_svector_ostream OS(Str);
14177     OS << "__i" << Depth;
14178     IterationVarName = &S.Context.Idents.get(OS.str());
14179   }
14180   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14181                                           IterationVarName, SizeType,
14182                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14183                                           SC_None);
14184 
14185   // Initialize the iteration variable to zero.
14186   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14187   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14188 
14189   // Creates a reference to the iteration variable.
14190   RefBuilder IterationVarRef(IterationVar, SizeType);
14191   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14192 
14193   // Create the DeclStmt that holds the iteration variable.
14194   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14195 
14196   // Subscript the "from" and "to" expressions with the iteration variable.
14197   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14198   MoveCastBuilder FromIndexMove(FromIndexCopy);
14199   const ExprBuilder *FromIndex;
14200   if (Copying)
14201     FromIndex = &FromIndexCopy;
14202   else
14203     FromIndex = &FromIndexMove;
14204 
14205   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14206 
14207   // Build the copy/move for an individual element of the array.
14208   StmtResult Copy =
14209     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14210                                      ToIndex, *FromIndex, CopyingBaseSubobject,
14211                                      Copying, Depth + 1);
14212   // Bail out if copying fails or if we determined that we should use memcpy.
14213   if (Copy.isInvalid() || !Copy.get())
14214     return Copy;
14215 
14216   // Create the comparison against the array bound.
14217   llvm::APInt Upper
14218     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14219   Expr *Comparison = BinaryOperator::Create(
14220       S.Context, IterationVarRefRVal.build(S, Loc),
14221       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14222       S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14223       S.CurFPFeatureOverrides());
14224 
14225   // Create the pre-increment of the iteration variable. We can determine
14226   // whether the increment will overflow based on the value of the array
14227   // bound.
14228   Expr *Increment = UnaryOperator::Create(
14229       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14230       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14231 
14232   // Construct the loop that copies all elements of this array.
14233   return S.ActOnForStmt(
14234       Loc, Loc, InitStmt,
14235       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14236       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14237 }
14238 
14239 static StmtResult
14240 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14241                       const ExprBuilder &To, const ExprBuilder &From,
14242                       bool CopyingBaseSubobject, bool Copying) {
14243   // Maybe we should use a memcpy?
14244   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14245       T.isTriviallyCopyableType(S.Context))
14246     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14247 
14248   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14249                                                      CopyingBaseSubobject,
14250                                                      Copying, 0));
14251 
14252   // If we ended up picking a trivial assignment operator for an array of a
14253   // non-trivially-copyable class type, just emit a memcpy.
14254   if (!Result.isInvalid() && !Result.get())
14255     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14256 
14257   return Result;
14258 }
14259 
14260 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14261   // Note: The following rules are largely analoguous to the copy
14262   // constructor rules. Note that virtual bases are not taken into account
14263   // for determining the argument type of the operator. Note also that
14264   // operators taking an object instead of a reference are allowed.
14265   assert(ClassDecl->needsImplicitCopyAssignment());
14266 
14267   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14268   if (DSM.isAlreadyBeingDeclared())
14269     return nullptr;
14270 
14271   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14272   LangAS AS = getDefaultCXXMethodAddrSpace();
14273   if (AS != LangAS::Default)
14274     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14275   QualType RetType = Context.getLValueReferenceType(ArgType);
14276   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14277   if (Const)
14278     ArgType = ArgType.withConst();
14279 
14280   ArgType = Context.getLValueReferenceType(ArgType);
14281 
14282   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14283                                                      CXXCopyAssignment,
14284                                                      Const);
14285 
14286   //   An implicitly-declared copy assignment operator is an inline public
14287   //   member of its class.
14288   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14289   SourceLocation ClassLoc = ClassDecl->getLocation();
14290   DeclarationNameInfo NameInfo(Name, ClassLoc);
14291   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14292       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14293       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14294       getCurFPFeatures().isFPConstrained(),
14295       /*isInline=*/true,
14296       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14297       SourceLocation());
14298   CopyAssignment->setAccess(AS_public);
14299   CopyAssignment->setDefaulted();
14300   CopyAssignment->setImplicit();
14301 
14302   if (getLangOpts().CUDA) {
14303     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14304                                             CopyAssignment,
14305                                             /* ConstRHS */ Const,
14306                                             /* Diagnose */ false);
14307   }
14308 
14309   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14310 
14311   // Add the parameter to the operator.
14312   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14313                                                ClassLoc, ClassLoc,
14314                                                /*Id=*/nullptr, ArgType,
14315                                                /*TInfo=*/nullptr, SC_None,
14316                                                nullptr);
14317   CopyAssignment->setParams(FromParam);
14318 
14319   CopyAssignment->setTrivial(
14320     ClassDecl->needsOverloadResolutionForCopyAssignment()
14321       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14322       : ClassDecl->hasTrivialCopyAssignment());
14323 
14324   // Note that we have added this copy-assignment operator.
14325   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14326 
14327   Scope *S = getScopeForContext(ClassDecl);
14328   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14329 
14330   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14331     ClassDecl->setImplicitCopyAssignmentIsDeleted();
14332     SetDeclDeleted(CopyAssignment, ClassLoc);
14333   }
14334 
14335   if (S)
14336     PushOnScopeChains(CopyAssignment, S, false);
14337   ClassDecl->addDecl(CopyAssignment);
14338 
14339   return CopyAssignment;
14340 }
14341 
14342 /// Diagnose an implicit copy operation for a class which is odr-used, but
14343 /// which is deprecated because the class has a user-declared copy constructor,
14344 /// copy assignment operator, or destructor.
14345 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14346   assert(CopyOp->isImplicit());
14347 
14348   CXXRecordDecl *RD = CopyOp->getParent();
14349   CXXMethodDecl *UserDeclaredOperation = nullptr;
14350 
14351   // In Microsoft mode, assignment operations don't affect constructors and
14352   // vice versa.
14353   if (RD->hasUserDeclaredDestructor()) {
14354     UserDeclaredOperation = RD->getDestructor();
14355   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14356              RD->hasUserDeclaredCopyConstructor() &&
14357              !S.getLangOpts().MSVCCompat) {
14358     // Find any user-declared copy constructor.
14359     for (auto *I : RD->ctors()) {
14360       if (I->isCopyConstructor()) {
14361         UserDeclaredOperation = I;
14362         break;
14363       }
14364     }
14365     assert(UserDeclaredOperation);
14366   } else if (isa<CXXConstructorDecl>(CopyOp) &&
14367              RD->hasUserDeclaredCopyAssignment() &&
14368              !S.getLangOpts().MSVCCompat) {
14369     // Find any user-declared move assignment operator.
14370     for (auto *I : RD->methods()) {
14371       if (I->isCopyAssignmentOperator()) {
14372         UserDeclaredOperation = I;
14373         break;
14374       }
14375     }
14376     assert(UserDeclaredOperation);
14377   }
14378 
14379   if (UserDeclaredOperation) {
14380     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14381     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14382     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14383     unsigned DiagID =
14384         (UDOIsUserProvided && UDOIsDestructor)
14385             ? diag::warn_deprecated_copy_with_user_provided_dtor
14386         : (UDOIsUserProvided && !UDOIsDestructor)
14387             ? diag::warn_deprecated_copy_with_user_provided_copy
14388         : (!UDOIsUserProvided && UDOIsDestructor)
14389             ? diag::warn_deprecated_copy_with_dtor
14390             : diag::warn_deprecated_copy;
14391     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14392         << RD << IsCopyAssignment;
14393   }
14394 }
14395 
14396 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14397                                         CXXMethodDecl *CopyAssignOperator) {
14398   assert((CopyAssignOperator->isDefaulted() &&
14399           CopyAssignOperator->isOverloadedOperator() &&
14400           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14401           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14402           !CopyAssignOperator->isDeleted()) &&
14403          "DefineImplicitCopyAssignment called for wrong function");
14404   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14405     return;
14406 
14407   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14408   if (ClassDecl->isInvalidDecl()) {
14409     CopyAssignOperator->setInvalidDecl();
14410     return;
14411   }
14412 
14413   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14414 
14415   // The exception specification is needed because we are defining the
14416   // function.
14417   ResolveExceptionSpec(CurrentLocation,
14418                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14419 
14420   // Add a context note for diagnostics produced after this point.
14421   Scope.addContextNote(CurrentLocation);
14422 
14423   // C++11 [class.copy]p18:
14424   //   The [definition of an implicitly declared copy assignment operator] is
14425   //   deprecated if the class has a user-declared copy constructor or a
14426   //   user-declared destructor.
14427   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14428     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14429 
14430   // C++0x [class.copy]p30:
14431   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14432   //   for a non-union class X performs memberwise copy assignment of its
14433   //   subobjects. The direct base classes of X are assigned first, in the
14434   //   order of their declaration in the base-specifier-list, and then the
14435   //   immediate non-static data members of X are assigned, in the order in
14436   //   which they were declared in the class definition.
14437 
14438   // The statements that form the synthesized function body.
14439   SmallVector<Stmt*, 8> Statements;
14440 
14441   // The parameter for the "other" object, which we are copying from.
14442   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14443   Qualifiers OtherQuals = Other->getType().getQualifiers();
14444   QualType OtherRefType = Other->getType();
14445   if (const LValueReferenceType *OtherRef
14446                                 = OtherRefType->getAs<LValueReferenceType>()) {
14447     OtherRefType = OtherRef->getPointeeType();
14448     OtherQuals = OtherRefType.getQualifiers();
14449   }
14450 
14451   // Our location for everything implicitly-generated.
14452   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14453                            ? CopyAssignOperator->getEndLoc()
14454                            : CopyAssignOperator->getLocation();
14455 
14456   // Builds a DeclRefExpr for the "other" object.
14457   RefBuilder OtherRef(Other, OtherRefType);
14458 
14459   // Builds the "this" pointer.
14460   ThisBuilder This;
14461 
14462   // Assign base classes.
14463   bool Invalid = false;
14464   for (auto &Base : ClassDecl->bases()) {
14465     // Form the assignment:
14466     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14467     QualType BaseType = Base.getType().getUnqualifiedType();
14468     if (!BaseType->isRecordType()) {
14469       Invalid = true;
14470       continue;
14471     }
14472 
14473     CXXCastPath BasePath;
14474     BasePath.push_back(&Base);
14475 
14476     // Construct the "from" expression, which is an implicit cast to the
14477     // appropriately-qualified base type.
14478     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14479                      VK_LValue, BasePath);
14480 
14481     // Dereference "this".
14482     DerefBuilder DerefThis(This);
14483     CastBuilder To(DerefThis,
14484                    Context.getQualifiedType(
14485                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14486                    VK_LValue, BasePath);
14487 
14488     // Build the copy.
14489     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14490                                             To, From,
14491                                             /*CopyingBaseSubobject=*/true,
14492                                             /*Copying=*/true);
14493     if (Copy.isInvalid()) {
14494       CopyAssignOperator->setInvalidDecl();
14495       return;
14496     }
14497 
14498     // Success! Record the copy.
14499     Statements.push_back(Copy.getAs<Expr>());
14500   }
14501 
14502   // Assign non-static members.
14503   for (auto *Field : ClassDecl->fields()) {
14504     // FIXME: We should form some kind of AST representation for the implied
14505     // memcpy in a union copy operation.
14506     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14507       continue;
14508 
14509     if (Field->isInvalidDecl()) {
14510       Invalid = true;
14511       continue;
14512     }
14513 
14514     // Check for members of reference type; we can't copy those.
14515     if (Field->getType()->isReferenceType()) {
14516       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14517         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14518       Diag(Field->getLocation(), diag::note_declared_at);
14519       Invalid = true;
14520       continue;
14521     }
14522 
14523     // Check for members of const-qualified, non-class type.
14524     QualType BaseType = Context.getBaseElementType(Field->getType());
14525     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14526       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14527         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14528       Diag(Field->getLocation(), diag::note_declared_at);
14529       Invalid = true;
14530       continue;
14531     }
14532 
14533     // Suppress assigning zero-width bitfields.
14534     if (Field->isZeroLengthBitField(Context))
14535       continue;
14536 
14537     QualType FieldType = Field->getType().getNonReferenceType();
14538     if (FieldType->isIncompleteArrayType()) {
14539       assert(ClassDecl->hasFlexibleArrayMember() &&
14540              "Incomplete array type is not valid");
14541       continue;
14542     }
14543 
14544     // Build references to the field in the object we're copying from and to.
14545     CXXScopeSpec SS; // Intentionally empty
14546     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14547                               LookupMemberName);
14548     MemberLookup.addDecl(Field);
14549     MemberLookup.resolveKind();
14550 
14551     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14552 
14553     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14554 
14555     // Build the copy of this field.
14556     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14557                                             To, From,
14558                                             /*CopyingBaseSubobject=*/false,
14559                                             /*Copying=*/true);
14560     if (Copy.isInvalid()) {
14561       CopyAssignOperator->setInvalidDecl();
14562       return;
14563     }
14564 
14565     // Success! Record the copy.
14566     Statements.push_back(Copy.getAs<Stmt>());
14567   }
14568 
14569   if (!Invalid) {
14570     // Add a "return *this;"
14571     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14572 
14573     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14574     if (Return.isInvalid())
14575       Invalid = true;
14576     else
14577       Statements.push_back(Return.getAs<Stmt>());
14578   }
14579 
14580   if (Invalid) {
14581     CopyAssignOperator->setInvalidDecl();
14582     return;
14583   }
14584 
14585   StmtResult Body;
14586   {
14587     CompoundScopeRAII CompoundScope(*this);
14588     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14589                              /*isStmtExpr=*/false);
14590     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14591   }
14592   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14593   CopyAssignOperator->markUsed(Context);
14594 
14595   if (ASTMutationListener *L = getASTMutationListener()) {
14596     L->CompletedImplicitDefinition(CopyAssignOperator);
14597   }
14598 }
14599 
14600 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14601   assert(ClassDecl->needsImplicitMoveAssignment());
14602 
14603   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14604   if (DSM.isAlreadyBeingDeclared())
14605     return nullptr;
14606 
14607   // Note: The following rules are largely analoguous to the move
14608   // constructor rules.
14609 
14610   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14611   LangAS AS = getDefaultCXXMethodAddrSpace();
14612   if (AS != LangAS::Default)
14613     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14614   QualType RetType = Context.getLValueReferenceType(ArgType);
14615   ArgType = Context.getRValueReferenceType(ArgType);
14616 
14617   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14618                                                      CXXMoveAssignment,
14619                                                      false);
14620 
14621   //   An implicitly-declared move assignment operator is an inline public
14622   //   member of its class.
14623   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14624   SourceLocation ClassLoc = ClassDecl->getLocation();
14625   DeclarationNameInfo NameInfo(Name, ClassLoc);
14626   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14627       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14628       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14629       getCurFPFeatures().isFPConstrained(),
14630       /*isInline=*/true,
14631       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14632       SourceLocation());
14633   MoveAssignment->setAccess(AS_public);
14634   MoveAssignment->setDefaulted();
14635   MoveAssignment->setImplicit();
14636 
14637   if (getLangOpts().CUDA) {
14638     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14639                                             MoveAssignment,
14640                                             /* ConstRHS */ false,
14641                                             /* Diagnose */ false);
14642   }
14643 
14644   setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14645 
14646   // Add the parameter to the operator.
14647   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14648                                                ClassLoc, ClassLoc,
14649                                                /*Id=*/nullptr, ArgType,
14650                                                /*TInfo=*/nullptr, SC_None,
14651                                                nullptr);
14652   MoveAssignment->setParams(FromParam);
14653 
14654   MoveAssignment->setTrivial(
14655     ClassDecl->needsOverloadResolutionForMoveAssignment()
14656       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14657       : ClassDecl->hasTrivialMoveAssignment());
14658 
14659   // Note that we have added this copy-assignment operator.
14660   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14661 
14662   Scope *S = getScopeForContext(ClassDecl);
14663   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14664 
14665   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14666     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14667     SetDeclDeleted(MoveAssignment, ClassLoc);
14668   }
14669 
14670   if (S)
14671     PushOnScopeChains(MoveAssignment, S, false);
14672   ClassDecl->addDecl(MoveAssignment);
14673 
14674   return MoveAssignment;
14675 }
14676 
14677 /// Check if we're implicitly defining a move assignment operator for a class
14678 /// with virtual bases. Such a move assignment might move-assign the virtual
14679 /// base multiple times.
14680 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14681                                                SourceLocation CurrentLocation) {
14682   assert(!Class->isDependentContext() && "should not define dependent move");
14683 
14684   // Only a virtual base could get implicitly move-assigned multiple times.
14685   // Only a non-trivial move assignment can observe this. We only want to
14686   // diagnose if we implicitly define an assignment operator that assigns
14687   // two base classes, both of which move-assign the same virtual base.
14688   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14689       Class->getNumBases() < 2)
14690     return;
14691 
14692   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14693   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14694   VBaseMap VBases;
14695 
14696   for (auto &BI : Class->bases()) {
14697     Worklist.push_back(&BI);
14698     while (!Worklist.empty()) {
14699       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14700       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14701 
14702       // If the base has no non-trivial move assignment operators,
14703       // we don't care about moves from it.
14704       if (!Base->hasNonTrivialMoveAssignment())
14705         continue;
14706 
14707       // If there's nothing virtual here, skip it.
14708       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14709         continue;
14710 
14711       // If we're not actually going to call a move assignment for this base,
14712       // or the selected move assignment is trivial, skip it.
14713       Sema::SpecialMemberOverloadResult SMOR =
14714         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14715                               /*ConstArg*/false, /*VolatileArg*/false,
14716                               /*RValueThis*/true, /*ConstThis*/false,
14717                               /*VolatileThis*/false);
14718       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14719           !SMOR.getMethod()->isMoveAssignmentOperator())
14720         continue;
14721 
14722       if (BaseSpec->isVirtual()) {
14723         // We're going to move-assign this virtual base, and its move
14724         // assignment operator is not trivial. If this can happen for
14725         // multiple distinct direct bases of Class, diagnose it. (If it
14726         // only happens in one base, we'll diagnose it when synthesizing
14727         // that base class's move assignment operator.)
14728         CXXBaseSpecifier *&Existing =
14729             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14730                 .first->second;
14731         if (Existing && Existing != &BI) {
14732           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14733             << Class << Base;
14734           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14735               << (Base->getCanonicalDecl() ==
14736                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14737               << Base << Existing->getType() << Existing->getSourceRange();
14738           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14739               << (Base->getCanonicalDecl() ==
14740                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14741               << Base << BI.getType() << BaseSpec->getSourceRange();
14742 
14743           // Only diagnose each vbase once.
14744           Existing = nullptr;
14745         }
14746       } else {
14747         // Only walk over bases that have defaulted move assignment operators.
14748         // We assume that any user-provided move assignment operator handles
14749         // the multiple-moves-of-vbase case itself somehow.
14750         if (!SMOR.getMethod()->isDefaulted())
14751           continue;
14752 
14753         // We're going to move the base classes of Base. Add them to the list.
14754         llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
14755       }
14756     }
14757   }
14758 }
14759 
14760 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14761                                         CXXMethodDecl *MoveAssignOperator) {
14762   assert((MoveAssignOperator->isDefaulted() &&
14763           MoveAssignOperator->isOverloadedOperator() &&
14764           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14765           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14766           !MoveAssignOperator->isDeleted()) &&
14767          "DefineImplicitMoveAssignment called for wrong function");
14768   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14769     return;
14770 
14771   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14772   if (ClassDecl->isInvalidDecl()) {
14773     MoveAssignOperator->setInvalidDecl();
14774     return;
14775   }
14776 
14777   // C++0x [class.copy]p28:
14778   //   The implicitly-defined or move assignment operator for a non-union class
14779   //   X performs memberwise move assignment of its subobjects. The direct base
14780   //   classes of X are assigned first, in the order of their declaration in the
14781   //   base-specifier-list, and then the immediate non-static data members of X
14782   //   are assigned, in the order in which they were declared in the class
14783   //   definition.
14784 
14785   // Issue a warning if our implicit move assignment operator will move
14786   // from a virtual base more than once.
14787   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14788 
14789   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14790 
14791   // The exception specification is needed because we are defining the
14792   // function.
14793   ResolveExceptionSpec(CurrentLocation,
14794                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14795 
14796   // Add a context note for diagnostics produced after this point.
14797   Scope.addContextNote(CurrentLocation);
14798 
14799   // The statements that form the synthesized function body.
14800   SmallVector<Stmt*, 8> Statements;
14801 
14802   // The parameter for the "other" object, which we are move from.
14803   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14804   QualType OtherRefType =
14805       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14806 
14807   // Our location for everything implicitly-generated.
14808   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14809                            ? MoveAssignOperator->getEndLoc()
14810                            : MoveAssignOperator->getLocation();
14811 
14812   // Builds a reference to the "other" object.
14813   RefBuilder OtherRef(Other, OtherRefType);
14814   // Cast to rvalue.
14815   MoveCastBuilder MoveOther(OtherRef);
14816 
14817   // Builds the "this" pointer.
14818   ThisBuilder This;
14819 
14820   // Assign base classes.
14821   bool Invalid = false;
14822   for (auto &Base : ClassDecl->bases()) {
14823     // C++11 [class.copy]p28:
14824     //   It is unspecified whether subobjects representing virtual base classes
14825     //   are assigned more than once by the implicitly-defined copy assignment
14826     //   operator.
14827     // FIXME: Do not assign to a vbase that will be assigned by some other base
14828     // class. For a move-assignment, this can result in the vbase being moved
14829     // multiple times.
14830 
14831     // Form the assignment:
14832     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14833     QualType BaseType = Base.getType().getUnqualifiedType();
14834     if (!BaseType->isRecordType()) {
14835       Invalid = true;
14836       continue;
14837     }
14838 
14839     CXXCastPath BasePath;
14840     BasePath.push_back(&Base);
14841 
14842     // Construct the "from" expression, which is an implicit cast to the
14843     // appropriately-qualified base type.
14844     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14845 
14846     // Dereference "this".
14847     DerefBuilder DerefThis(This);
14848 
14849     // Implicitly cast "this" to the appropriately-qualified base type.
14850     CastBuilder To(DerefThis,
14851                    Context.getQualifiedType(
14852                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14853                    VK_LValue, BasePath);
14854 
14855     // Build the move.
14856     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14857                                             To, From,
14858                                             /*CopyingBaseSubobject=*/true,
14859                                             /*Copying=*/false);
14860     if (Move.isInvalid()) {
14861       MoveAssignOperator->setInvalidDecl();
14862       return;
14863     }
14864 
14865     // Success! Record the move.
14866     Statements.push_back(Move.getAs<Expr>());
14867   }
14868 
14869   // Assign non-static members.
14870   for (auto *Field : ClassDecl->fields()) {
14871     // FIXME: We should form some kind of AST representation for the implied
14872     // memcpy in a union copy operation.
14873     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14874       continue;
14875 
14876     if (Field->isInvalidDecl()) {
14877       Invalid = true;
14878       continue;
14879     }
14880 
14881     // Check for members of reference type; we can't move those.
14882     if (Field->getType()->isReferenceType()) {
14883       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14884         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14885       Diag(Field->getLocation(), diag::note_declared_at);
14886       Invalid = true;
14887       continue;
14888     }
14889 
14890     // Check for members of const-qualified, non-class type.
14891     QualType BaseType = Context.getBaseElementType(Field->getType());
14892     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14893       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14894         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14895       Diag(Field->getLocation(), diag::note_declared_at);
14896       Invalid = true;
14897       continue;
14898     }
14899 
14900     // Suppress assigning zero-width bitfields.
14901     if (Field->isZeroLengthBitField(Context))
14902       continue;
14903 
14904     QualType FieldType = Field->getType().getNonReferenceType();
14905     if (FieldType->isIncompleteArrayType()) {
14906       assert(ClassDecl->hasFlexibleArrayMember() &&
14907              "Incomplete array type is not valid");
14908       continue;
14909     }
14910 
14911     // Build references to the field in the object we're copying from and to.
14912     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14913                               LookupMemberName);
14914     MemberLookup.addDecl(Field);
14915     MemberLookup.resolveKind();
14916     MemberBuilder From(MoveOther, OtherRefType,
14917                        /*IsArrow=*/false, MemberLookup);
14918     MemberBuilder To(This, getCurrentThisType(),
14919                      /*IsArrow=*/true, MemberLookup);
14920 
14921     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14922         "Member reference with rvalue base must be rvalue except for reference "
14923         "members, which aren't allowed for move assignment.");
14924 
14925     // Build the move of this field.
14926     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14927                                             To, From,
14928                                             /*CopyingBaseSubobject=*/false,
14929                                             /*Copying=*/false);
14930     if (Move.isInvalid()) {
14931       MoveAssignOperator->setInvalidDecl();
14932       return;
14933     }
14934 
14935     // Success! Record the copy.
14936     Statements.push_back(Move.getAs<Stmt>());
14937   }
14938 
14939   if (!Invalid) {
14940     // Add a "return *this;"
14941     ExprResult ThisObj =
14942         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14943 
14944     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14945     if (Return.isInvalid())
14946       Invalid = true;
14947     else
14948       Statements.push_back(Return.getAs<Stmt>());
14949   }
14950 
14951   if (Invalid) {
14952     MoveAssignOperator->setInvalidDecl();
14953     return;
14954   }
14955 
14956   StmtResult Body;
14957   {
14958     CompoundScopeRAII CompoundScope(*this);
14959     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14960                              /*isStmtExpr=*/false);
14961     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14962   }
14963   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14964   MoveAssignOperator->markUsed(Context);
14965 
14966   if (ASTMutationListener *L = getASTMutationListener()) {
14967     L->CompletedImplicitDefinition(MoveAssignOperator);
14968   }
14969 }
14970 
14971 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14972                                                     CXXRecordDecl *ClassDecl) {
14973   // C++ [class.copy]p4:
14974   //   If the class definition does not explicitly declare a copy
14975   //   constructor, one is declared implicitly.
14976   assert(ClassDecl->needsImplicitCopyConstructor());
14977 
14978   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14979   if (DSM.isAlreadyBeingDeclared())
14980     return nullptr;
14981 
14982   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14983   QualType ArgType = ClassType;
14984   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14985   if (Const)
14986     ArgType = ArgType.withConst();
14987 
14988   LangAS AS = getDefaultCXXMethodAddrSpace();
14989   if (AS != LangAS::Default)
14990     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14991 
14992   ArgType = Context.getLValueReferenceType(ArgType);
14993 
14994   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14995                                                      CXXCopyConstructor,
14996                                                      Const);
14997 
14998   DeclarationName Name
14999     = Context.DeclarationNames.getCXXConstructorName(
15000                                            Context.getCanonicalType(ClassType));
15001   SourceLocation ClassLoc = ClassDecl->getLocation();
15002   DeclarationNameInfo NameInfo(Name, ClassLoc);
15003 
15004   //   An implicitly-declared copy constructor is an inline public
15005   //   member of its class.
15006   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15007       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15008       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15009       /*isInline=*/true,
15010       /*isImplicitlyDeclared=*/true,
15011       Constexpr ? ConstexprSpecKind::Constexpr
15012                 : ConstexprSpecKind::Unspecified);
15013   CopyConstructor->setAccess(AS_public);
15014   CopyConstructor->setDefaulted();
15015 
15016   if (getLangOpts().CUDA) {
15017     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15018                                             CopyConstructor,
15019                                             /* ConstRHS */ Const,
15020                                             /* Diagnose */ false);
15021   }
15022 
15023   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15024 
15025   // During template instantiation of special member functions we need a
15026   // reliable TypeSourceInfo for the parameter types in order to allow functions
15027   // to be substituted.
15028   TypeSourceInfo *TSI = nullptr;
15029   if (inTemplateInstantiation() && ClassDecl->isLambda())
15030     TSI = Context.getTrivialTypeSourceInfo(ArgType);
15031 
15032   // Add the parameter to the constructor.
15033   ParmVarDecl *FromParam =
15034       ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15035                           /*IdentifierInfo=*/nullptr, ArgType,
15036                           /*TInfo=*/TSI, SC_None, nullptr);
15037   CopyConstructor->setParams(FromParam);
15038 
15039   CopyConstructor->setTrivial(
15040       ClassDecl->needsOverloadResolutionForCopyConstructor()
15041           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15042           : ClassDecl->hasTrivialCopyConstructor());
15043 
15044   CopyConstructor->setTrivialForCall(
15045       ClassDecl->hasAttr<TrivialABIAttr>() ||
15046       (ClassDecl->needsOverloadResolutionForCopyConstructor()
15047            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15048              TAH_ConsiderTrivialABI)
15049            : ClassDecl->hasTrivialCopyConstructorForCall()));
15050 
15051   // Note that we have declared this constructor.
15052   ++getASTContext().NumImplicitCopyConstructorsDeclared;
15053 
15054   Scope *S = getScopeForContext(ClassDecl);
15055   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15056 
15057   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15058     ClassDecl->setImplicitCopyConstructorIsDeleted();
15059     SetDeclDeleted(CopyConstructor, ClassLoc);
15060   }
15061 
15062   if (S)
15063     PushOnScopeChains(CopyConstructor, S, false);
15064   ClassDecl->addDecl(CopyConstructor);
15065 
15066   return CopyConstructor;
15067 }
15068 
15069 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15070                                          CXXConstructorDecl *CopyConstructor) {
15071   assert((CopyConstructor->isDefaulted() &&
15072           CopyConstructor->isCopyConstructor() &&
15073           !CopyConstructor->doesThisDeclarationHaveABody() &&
15074           !CopyConstructor->isDeleted()) &&
15075          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15076   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15077     return;
15078 
15079   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15080   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15081 
15082   SynthesizedFunctionScope Scope(*this, CopyConstructor);
15083 
15084   // The exception specification is needed because we are defining the
15085   // function.
15086   ResolveExceptionSpec(CurrentLocation,
15087                        CopyConstructor->getType()->castAs<FunctionProtoType>());
15088   MarkVTableUsed(CurrentLocation, ClassDecl);
15089 
15090   // Add a context note for diagnostics produced after this point.
15091   Scope.addContextNote(CurrentLocation);
15092 
15093   // C++11 [class.copy]p7:
15094   //   The [definition of an implicitly declared copy constructor] is
15095   //   deprecated if the class has a user-declared copy assignment operator
15096   //   or a user-declared destructor.
15097   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15098     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15099 
15100   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15101     CopyConstructor->setInvalidDecl();
15102   }  else {
15103     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15104                              ? CopyConstructor->getEndLoc()
15105                              : CopyConstructor->getLocation();
15106     Sema::CompoundScopeRAII CompoundScope(*this);
15107     CopyConstructor->setBody(
15108         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
15109     CopyConstructor->markUsed(Context);
15110   }
15111 
15112   if (ASTMutationListener *L = getASTMutationListener()) {
15113     L->CompletedImplicitDefinition(CopyConstructor);
15114   }
15115 }
15116 
15117 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15118                                                     CXXRecordDecl *ClassDecl) {
15119   assert(ClassDecl->needsImplicitMoveConstructor());
15120 
15121   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15122   if (DSM.isAlreadyBeingDeclared())
15123     return nullptr;
15124 
15125   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15126 
15127   QualType ArgType = ClassType;
15128   LangAS AS = getDefaultCXXMethodAddrSpace();
15129   if (AS != LangAS::Default)
15130     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15131   ArgType = Context.getRValueReferenceType(ArgType);
15132 
15133   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15134                                                      CXXMoveConstructor,
15135                                                      false);
15136 
15137   DeclarationName Name
15138     = Context.DeclarationNames.getCXXConstructorName(
15139                                            Context.getCanonicalType(ClassType));
15140   SourceLocation ClassLoc = ClassDecl->getLocation();
15141   DeclarationNameInfo NameInfo(Name, ClassLoc);
15142 
15143   // C++11 [class.copy]p11:
15144   //   An implicitly-declared copy/move constructor is an inline public
15145   //   member of its class.
15146   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15147       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15148       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15149       /*isInline=*/true,
15150       /*isImplicitlyDeclared=*/true,
15151       Constexpr ? ConstexprSpecKind::Constexpr
15152                 : ConstexprSpecKind::Unspecified);
15153   MoveConstructor->setAccess(AS_public);
15154   MoveConstructor->setDefaulted();
15155 
15156   if (getLangOpts().CUDA) {
15157     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15158                                             MoveConstructor,
15159                                             /* ConstRHS */ false,
15160                                             /* Diagnose */ false);
15161   }
15162 
15163   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15164 
15165   // Add the parameter to the constructor.
15166   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15167                                                ClassLoc, ClassLoc,
15168                                                /*IdentifierInfo=*/nullptr,
15169                                                ArgType, /*TInfo=*/nullptr,
15170                                                SC_None, nullptr);
15171   MoveConstructor->setParams(FromParam);
15172 
15173   MoveConstructor->setTrivial(
15174       ClassDecl->needsOverloadResolutionForMoveConstructor()
15175           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15176           : ClassDecl->hasTrivialMoveConstructor());
15177 
15178   MoveConstructor->setTrivialForCall(
15179       ClassDecl->hasAttr<TrivialABIAttr>() ||
15180       (ClassDecl->needsOverloadResolutionForMoveConstructor()
15181            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15182                                     TAH_ConsiderTrivialABI)
15183            : ClassDecl->hasTrivialMoveConstructorForCall()));
15184 
15185   // Note that we have declared this constructor.
15186   ++getASTContext().NumImplicitMoveConstructorsDeclared;
15187 
15188   Scope *S = getScopeForContext(ClassDecl);
15189   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15190 
15191   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15192     ClassDecl->setImplicitMoveConstructorIsDeleted();
15193     SetDeclDeleted(MoveConstructor, ClassLoc);
15194   }
15195 
15196   if (S)
15197     PushOnScopeChains(MoveConstructor, S, false);
15198   ClassDecl->addDecl(MoveConstructor);
15199 
15200   return MoveConstructor;
15201 }
15202 
15203 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15204                                          CXXConstructorDecl *MoveConstructor) {
15205   assert((MoveConstructor->isDefaulted() &&
15206           MoveConstructor->isMoveConstructor() &&
15207           !MoveConstructor->doesThisDeclarationHaveABody() &&
15208           !MoveConstructor->isDeleted()) &&
15209          "DefineImplicitMoveConstructor - call it for implicit move ctor");
15210   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15211     return;
15212 
15213   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15214   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15215 
15216   SynthesizedFunctionScope Scope(*this, MoveConstructor);
15217 
15218   // The exception specification is needed because we are defining the
15219   // function.
15220   ResolveExceptionSpec(CurrentLocation,
15221                        MoveConstructor->getType()->castAs<FunctionProtoType>());
15222   MarkVTableUsed(CurrentLocation, ClassDecl);
15223 
15224   // Add a context note for diagnostics produced after this point.
15225   Scope.addContextNote(CurrentLocation);
15226 
15227   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15228     MoveConstructor->setInvalidDecl();
15229   } else {
15230     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15231                              ? MoveConstructor->getEndLoc()
15232                              : MoveConstructor->getLocation();
15233     Sema::CompoundScopeRAII CompoundScope(*this);
15234     MoveConstructor->setBody(ActOnCompoundStmt(
15235         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
15236     MoveConstructor->markUsed(Context);
15237   }
15238 
15239   if (ASTMutationListener *L = getASTMutationListener()) {
15240     L->CompletedImplicitDefinition(MoveConstructor);
15241   }
15242 }
15243 
15244 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15245   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15246 }
15247 
15248 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15249                             SourceLocation CurrentLocation,
15250                             CXXConversionDecl *Conv) {
15251   SynthesizedFunctionScope Scope(*this, Conv);
15252   assert(!Conv->getReturnType()->isUndeducedType());
15253 
15254   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15255   CallingConv CC =
15256       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15257 
15258   CXXRecordDecl *Lambda = Conv->getParent();
15259   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15260   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
15261 
15262   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15263     CallOp = InstantiateFunctionDeclaration(
15264         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15265     if (!CallOp)
15266       return;
15267 
15268     Invoker = InstantiateFunctionDeclaration(
15269         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15270     if (!Invoker)
15271       return;
15272   }
15273 
15274   if (CallOp->isInvalidDecl())
15275     return;
15276 
15277   // Mark the call operator referenced (and add to pending instantiations
15278   // if necessary).
15279   // For both the conversion and static-invoker template specializations
15280   // we construct their body's in this function, so no need to add them
15281   // to the PendingInstantiations.
15282   MarkFunctionReferenced(CurrentLocation, CallOp);
15283 
15284   // Fill in the __invoke function with a dummy implementation. IR generation
15285   // will fill in the actual details. Update its type in case it contained
15286   // an 'auto'.
15287   Invoker->markUsed(Context);
15288   Invoker->setReferenced();
15289   Invoker->setType(Conv->getReturnType()->getPointeeType());
15290   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15291 
15292   // Construct the body of the conversion function { return __invoke; }.
15293   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
15294                                        VK_LValue, Conv->getLocation());
15295   assert(FunctionRef && "Can't refer to __invoke function?");
15296   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15297   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
15298                                      Conv->getLocation()));
15299   Conv->markUsed(Context);
15300   Conv->setReferenced();
15301 
15302   if (ASTMutationListener *L = getASTMutationListener()) {
15303     L->CompletedImplicitDefinition(Conv);
15304     L->CompletedImplicitDefinition(Invoker);
15305   }
15306 }
15307 
15308 
15309 
15310 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15311        SourceLocation CurrentLocation,
15312        CXXConversionDecl *Conv)
15313 {
15314   assert(!Conv->getParent()->isGenericLambda());
15315 
15316   SynthesizedFunctionScope Scope(*this, Conv);
15317 
15318   // Copy-initialize the lambda object as needed to capture it.
15319   Expr *This = ActOnCXXThis(CurrentLocation).get();
15320   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15321 
15322   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15323                                                         Conv->getLocation(),
15324                                                         Conv, DerefThis);
15325 
15326   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15327   // behavior.  Note that only the general conversion function does this
15328   // (since it's unusable otherwise); in the case where we inline the
15329   // block literal, it has block literal lifetime semantics.
15330   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15331     BuildBlock = ImplicitCastExpr::Create(
15332         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15333         BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15334 
15335   if (BuildBlock.isInvalid()) {
15336     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15337     Conv->setInvalidDecl();
15338     return;
15339   }
15340 
15341   // Create the return statement that returns the block from the conversion
15342   // function.
15343   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15344   if (Return.isInvalid()) {
15345     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15346     Conv->setInvalidDecl();
15347     return;
15348   }
15349 
15350   // Set the body of the conversion function.
15351   Stmt *ReturnS = Return.get();
15352   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
15353                                      Conv->getLocation()));
15354   Conv->markUsed(Context);
15355 
15356   // We're done; notify the mutation listener, if any.
15357   if (ASTMutationListener *L = getASTMutationListener()) {
15358     L->CompletedImplicitDefinition(Conv);
15359   }
15360 }
15361 
15362 /// Determine whether the given list arguments contains exactly one
15363 /// "real" (non-default) argument.
15364 static bool hasOneRealArgument(MultiExprArg Args) {
15365   switch (Args.size()) {
15366   case 0:
15367     return false;
15368 
15369   default:
15370     if (!Args[1]->isDefaultArgument())
15371       return false;
15372 
15373     LLVM_FALLTHROUGH;
15374   case 1:
15375     return !Args[0]->isDefaultArgument();
15376   }
15377 
15378   return false;
15379 }
15380 
15381 ExprResult
15382 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15383                             NamedDecl *FoundDecl,
15384                             CXXConstructorDecl *Constructor,
15385                             MultiExprArg ExprArgs,
15386                             bool HadMultipleCandidates,
15387                             bool IsListInitialization,
15388                             bool IsStdInitListInitialization,
15389                             bool RequiresZeroInit,
15390                             unsigned ConstructKind,
15391                             SourceRange ParenRange) {
15392   bool Elidable = false;
15393 
15394   // C++0x [class.copy]p34:
15395   //   When certain criteria are met, an implementation is allowed to
15396   //   omit the copy/move construction of a class object, even if the
15397   //   copy/move constructor and/or destructor for the object have
15398   //   side effects. [...]
15399   //     - when a temporary class object that has not been bound to a
15400   //       reference (12.2) would be copied/moved to a class object
15401   //       with the same cv-unqualified type, the copy/move operation
15402   //       can be omitted by constructing the temporary object
15403   //       directly into the target of the omitted copy/move
15404   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15405       // FIXME: Converting constructors should also be accepted.
15406       // But to fix this, the logic that digs down into a CXXConstructExpr
15407       // to find the source object needs to handle it.
15408       // Right now it assumes the source object is passed directly as the
15409       // first argument.
15410       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15411     Expr *SubExpr = ExprArgs[0];
15412     // FIXME: Per above, this is also incorrect if we want to accept
15413     //        converting constructors, as isTemporaryObject will
15414     //        reject temporaries with different type from the
15415     //        CXXRecord itself.
15416     Elidable = SubExpr->isTemporaryObject(
15417         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15418   }
15419 
15420   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15421                                FoundDecl, Constructor,
15422                                Elidable, ExprArgs, HadMultipleCandidates,
15423                                IsListInitialization,
15424                                IsStdInitListInitialization, RequiresZeroInit,
15425                                ConstructKind, ParenRange);
15426 }
15427 
15428 ExprResult
15429 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15430                             NamedDecl *FoundDecl,
15431                             CXXConstructorDecl *Constructor,
15432                             bool Elidable,
15433                             MultiExprArg ExprArgs,
15434                             bool HadMultipleCandidates,
15435                             bool IsListInitialization,
15436                             bool IsStdInitListInitialization,
15437                             bool RequiresZeroInit,
15438                             unsigned ConstructKind,
15439                             SourceRange ParenRange) {
15440   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15441     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15442     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15443       return ExprError();
15444   }
15445 
15446   return BuildCXXConstructExpr(
15447       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15448       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15449       RequiresZeroInit, ConstructKind, ParenRange);
15450 }
15451 
15452 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15453 /// including handling of its default argument expressions.
15454 ExprResult
15455 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15456                             CXXConstructorDecl *Constructor,
15457                             bool Elidable,
15458                             MultiExprArg ExprArgs,
15459                             bool HadMultipleCandidates,
15460                             bool IsListInitialization,
15461                             bool IsStdInitListInitialization,
15462                             bool RequiresZeroInit,
15463                             unsigned ConstructKind,
15464                             SourceRange ParenRange) {
15465   assert(declaresSameEntity(
15466              Constructor->getParent(),
15467              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15468          "given constructor for wrong type");
15469   MarkFunctionReferenced(ConstructLoc, Constructor);
15470   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15471     return ExprError();
15472   if (getLangOpts().SYCLIsDevice &&
15473       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15474     return ExprError();
15475 
15476   return CheckForImmediateInvocation(
15477       CXXConstructExpr::Create(
15478           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15479           HadMultipleCandidates, IsListInitialization,
15480           IsStdInitListInitialization, RequiresZeroInit,
15481           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15482           ParenRange),
15483       Constructor);
15484 }
15485 
15486 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15487   assert(Field->hasInClassInitializer());
15488 
15489   // If we already have the in-class initializer nothing needs to be done.
15490   if (Field->getInClassInitializer())
15491     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15492 
15493   // If we might have already tried and failed to instantiate, don't try again.
15494   if (Field->isInvalidDecl())
15495     return ExprError();
15496 
15497   // Maybe we haven't instantiated the in-class initializer. Go check the
15498   // pattern FieldDecl to see if it has one.
15499   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15500 
15501   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15502     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15503     DeclContext::lookup_result Lookup =
15504         ClassPattern->lookup(Field->getDeclName());
15505 
15506     FieldDecl *Pattern = nullptr;
15507     for (auto L : Lookup) {
15508       if (isa<FieldDecl>(L)) {
15509         Pattern = cast<FieldDecl>(L);
15510         break;
15511       }
15512     }
15513     assert(Pattern && "We must have set the Pattern!");
15514 
15515     if (!Pattern->hasInClassInitializer() ||
15516         InstantiateInClassInitializer(Loc, Field, Pattern,
15517                                       getTemplateInstantiationArgs(Field))) {
15518       // Don't diagnose this again.
15519       Field->setInvalidDecl();
15520       return ExprError();
15521     }
15522     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15523   }
15524 
15525   // DR1351:
15526   //   If the brace-or-equal-initializer of a non-static data member
15527   //   invokes a defaulted default constructor of its class or of an
15528   //   enclosing class in a potentially evaluated subexpression, the
15529   //   program is ill-formed.
15530   //
15531   // This resolution is unworkable: the exception specification of the
15532   // default constructor can be needed in an unevaluated context, in
15533   // particular, in the operand of a noexcept-expression, and we can be
15534   // unable to compute an exception specification for an enclosed class.
15535   //
15536   // Any attempt to resolve the exception specification of a defaulted default
15537   // constructor before the initializer is lexically complete will ultimately
15538   // come here at which point we can diagnose it.
15539   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15540   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15541       << OutermostClass << Field;
15542   Diag(Field->getEndLoc(),
15543        diag::note_default_member_initializer_not_yet_parsed);
15544   // Recover by marking the field invalid, unless we're in a SFINAE context.
15545   if (!isSFINAEContext())
15546     Field->setInvalidDecl();
15547   return ExprError();
15548 }
15549 
15550 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15551   if (VD->isInvalidDecl()) return;
15552   // If initializing the variable failed, don't also diagnose problems with
15553   // the destructor, they're likely related.
15554   if (VD->getInit() && VD->getInit()->containsErrors())
15555     return;
15556 
15557   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15558   if (ClassDecl->isInvalidDecl()) return;
15559   if (ClassDecl->hasIrrelevantDestructor()) return;
15560   if (ClassDecl->isDependentContext()) return;
15561 
15562   if (VD->isNoDestroy(getASTContext()))
15563     return;
15564 
15565   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15566 
15567   // If this is an array, we'll require the destructor during initialization, so
15568   // we can skip over this. We still want to emit exit-time destructor warnings
15569   // though.
15570   if (!VD->getType()->isArrayType()) {
15571     MarkFunctionReferenced(VD->getLocation(), Destructor);
15572     CheckDestructorAccess(VD->getLocation(), Destructor,
15573                           PDiag(diag::err_access_dtor_var)
15574                               << VD->getDeclName() << VD->getType());
15575     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15576   }
15577 
15578   if (Destructor->isTrivial()) return;
15579 
15580   // If the destructor is constexpr, check whether the variable has constant
15581   // destruction now.
15582   if (Destructor->isConstexpr()) {
15583     bool HasConstantInit = false;
15584     if (VD->getInit() && !VD->getInit()->isValueDependent())
15585       HasConstantInit = VD->evaluateValue();
15586     SmallVector<PartialDiagnosticAt, 8> Notes;
15587     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15588         HasConstantInit) {
15589       Diag(VD->getLocation(),
15590            diag::err_constexpr_var_requires_const_destruction) << VD;
15591       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15592         Diag(Notes[I].first, Notes[I].second);
15593     }
15594   }
15595 
15596   if (!VD->hasGlobalStorage()) return;
15597 
15598   // Emit warning for non-trivial dtor in global scope (a real global,
15599   // class-static, function-static).
15600   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15601 
15602   // TODO: this should be re-enabled for static locals by !CXAAtExit
15603   if (!VD->isStaticLocal())
15604     Diag(VD->getLocation(), diag::warn_global_destructor);
15605 }
15606 
15607 /// Given a constructor and the set of arguments provided for the
15608 /// constructor, convert the arguments and add any required default arguments
15609 /// to form a proper call to this constructor.
15610 ///
15611 /// \returns true if an error occurred, false otherwise.
15612 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15613                                    QualType DeclInitType, MultiExprArg ArgsPtr,
15614                                    SourceLocation Loc,
15615                                    SmallVectorImpl<Expr *> &ConvertedArgs,
15616                                    bool AllowExplicit,
15617                                    bool IsListInitialization) {
15618   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15619   unsigned NumArgs = ArgsPtr.size();
15620   Expr **Args = ArgsPtr.data();
15621 
15622   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15623   unsigned NumParams = Proto->getNumParams();
15624 
15625   // If too few arguments are available, we'll fill in the rest with defaults.
15626   if (NumArgs < NumParams)
15627     ConvertedArgs.reserve(NumParams);
15628   else
15629     ConvertedArgs.reserve(NumArgs);
15630 
15631   VariadicCallType CallType =
15632     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15633   SmallVector<Expr *, 8> AllArgs;
15634   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15635                                         Proto, 0,
15636                                         llvm::makeArrayRef(Args, NumArgs),
15637                                         AllArgs,
15638                                         CallType, AllowExplicit,
15639                                         IsListInitialization);
15640   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15641 
15642   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15643 
15644   CheckConstructorCall(Constructor, DeclInitType,
15645                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15646                        Proto, Loc);
15647 
15648   return Invalid;
15649 }
15650 
15651 static inline bool
15652 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15653                                        const FunctionDecl *FnDecl) {
15654   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15655   if (isa<NamespaceDecl>(DC)) {
15656     return SemaRef.Diag(FnDecl->getLocation(),
15657                         diag::err_operator_new_delete_declared_in_namespace)
15658       << FnDecl->getDeclName();
15659   }
15660 
15661   if (isa<TranslationUnitDecl>(DC) &&
15662       FnDecl->getStorageClass() == SC_Static) {
15663     return SemaRef.Diag(FnDecl->getLocation(),
15664                         diag::err_operator_new_delete_declared_static)
15665       << FnDecl->getDeclName();
15666   }
15667 
15668   return false;
15669 }
15670 
15671 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15672                                              const PointerType *PtrTy) {
15673   auto &Ctx = SemaRef.Context;
15674   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15675   PtrQuals.removeAddressSpace();
15676   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15677       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15678 }
15679 
15680 static inline bool
15681 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15682                             CanQualType ExpectedResultType,
15683                             CanQualType ExpectedFirstParamType,
15684                             unsigned DependentParamTypeDiag,
15685                             unsigned InvalidParamTypeDiag) {
15686   QualType ResultType =
15687       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15688 
15689   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15690     // The operator is valid on any address space for OpenCL.
15691     // Drop address space from actual and expected result types.
15692     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15693       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15694 
15695     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15696       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15697   }
15698 
15699   // Check that the result type is what we expect.
15700   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15701     // Reject even if the type is dependent; an operator delete function is
15702     // required to have a non-dependent result type.
15703     return SemaRef.Diag(
15704                FnDecl->getLocation(),
15705                ResultType->isDependentType()
15706                    ? diag::err_operator_new_delete_dependent_result_type
15707                    : diag::err_operator_new_delete_invalid_result_type)
15708            << FnDecl->getDeclName() << ExpectedResultType;
15709   }
15710 
15711   // A function template must have at least 2 parameters.
15712   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15713     return SemaRef.Diag(FnDecl->getLocation(),
15714                       diag::err_operator_new_delete_template_too_few_parameters)
15715         << FnDecl->getDeclName();
15716 
15717   // The function decl must have at least 1 parameter.
15718   if (FnDecl->getNumParams() == 0)
15719     return SemaRef.Diag(FnDecl->getLocation(),
15720                         diag::err_operator_new_delete_too_few_parameters)
15721       << FnDecl->getDeclName();
15722 
15723   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15724   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15725     // The operator is valid on any address space for OpenCL.
15726     // Drop address space from actual and expected first parameter types.
15727     if (const auto *PtrTy =
15728             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15729       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15730 
15731     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15732       ExpectedFirstParamType =
15733           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15734   }
15735 
15736   // Check that the first parameter type is what we expect.
15737   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15738       ExpectedFirstParamType) {
15739     // The first parameter type is not allowed to be dependent. As a tentative
15740     // DR resolution, we allow a dependent parameter type if it is the right
15741     // type anyway, to allow destroying operator delete in class templates.
15742     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15743                                                    ? DependentParamTypeDiag
15744                                                    : InvalidParamTypeDiag)
15745            << FnDecl->getDeclName() << ExpectedFirstParamType;
15746   }
15747 
15748   return false;
15749 }
15750 
15751 static bool
15752 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15753   // C++ [basic.stc.dynamic.allocation]p1:
15754   //   A program is ill-formed if an allocation function is declared in a
15755   //   namespace scope other than global scope or declared static in global
15756   //   scope.
15757   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15758     return true;
15759 
15760   CanQualType SizeTy =
15761     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15762 
15763   // C++ [basic.stc.dynamic.allocation]p1:
15764   //  The return type shall be void*. The first parameter shall have type
15765   //  std::size_t.
15766   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15767                                   SizeTy,
15768                                   diag::err_operator_new_dependent_param_type,
15769                                   diag::err_operator_new_param_type))
15770     return true;
15771 
15772   // C++ [basic.stc.dynamic.allocation]p1:
15773   //  The first parameter shall not have an associated default argument.
15774   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15775     return SemaRef.Diag(FnDecl->getLocation(),
15776                         diag::err_operator_new_default_arg)
15777       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15778 
15779   return false;
15780 }
15781 
15782 static bool
15783 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15784   // C++ [basic.stc.dynamic.deallocation]p1:
15785   //   A program is ill-formed if deallocation functions are declared in a
15786   //   namespace scope other than global scope or declared static in global
15787   //   scope.
15788   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15789     return true;
15790 
15791   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15792 
15793   // C++ P0722:
15794   //   Within a class C, the first parameter of a destroying operator delete
15795   //   shall be of type C *. The first parameter of any other deallocation
15796   //   function shall be of type void *.
15797   CanQualType ExpectedFirstParamType =
15798       MD && MD->isDestroyingOperatorDelete()
15799           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15800                 SemaRef.Context.getRecordType(MD->getParent())))
15801           : SemaRef.Context.VoidPtrTy;
15802 
15803   // C++ [basic.stc.dynamic.deallocation]p2:
15804   //   Each deallocation function shall return void
15805   if (CheckOperatorNewDeleteTypes(
15806           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15807           diag::err_operator_delete_dependent_param_type,
15808           diag::err_operator_delete_param_type))
15809     return true;
15810 
15811   // C++ P0722:
15812   //   A destroying operator delete shall be a usual deallocation function.
15813   if (MD && !MD->getParent()->isDependentContext() &&
15814       MD->isDestroyingOperatorDelete() &&
15815       !SemaRef.isUsualDeallocationFunction(MD)) {
15816     SemaRef.Diag(MD->getLocation(),
15817                  diag::err_destroying_operator_delete_not_usual);
15818     return true;
15819   }
15820 
15821   return false;
15822 }
15823 
15824 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15825 /// of this overloaded operator is well-formed. If so, returns false;
15826 /// otherwise, emits appropriate diagnostics and returns true.
15827 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15828   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15829          "Expected an overloaded operator declaration");
15830 
15831   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15832 
15833   // C++ [over.oper]p5:
15834   //   The allocation and deallocation functions, operator new,
15835   //   operator new[], operator delete and operator delete[], are
15836   //   described completely in 3.7.3. The attributes and restrictions
15837   //   found in the rest of this subclause do not apply to them unless
15838   //   explicitly stated in 3.7.3.
15839   if (Op == OO_Delete || Op == OO_Array_Delete)
15840     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15841 
15842   if (Op == OO_New || Op == OO_Array_New)
15843     return CheckOperatorNewDeclaration(*this, FnDecl);
15844 
15845   // C++ [over.oper]p6:
15846   //   An operator function shall either be a non-static member
15847   //   function or be a non-member function and have at least one
15848   //   parameter whose type is a class, a reference to a class, an
15849   //   enumeration, or a reference to an enumeration.
15850   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15851     if (MethodDecl->isStatic())
15852       return Diag(FnDecl->getLocation(),
15853                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15854   } else {
15855     bool ClassOrEnumParam = false;
15856     for (auto Param : FnDecl->parameters()) {
15857       QualType ParamType = Param->getType().getNonReferenceType();
15858       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15859           ParamType->isEnumeralType()) {
15860         ClassOrEnumParam = true;
15861         break;
15862       }
15863     }
15864 
15865     if (!ClassOrEnumParam)
15866       return Diag(FnDecl->getLocation(),
15867                   diag::err_operator_overload_needs_class_or_enum)
15868         << FnDecl->getDeclName();
15869   }
15870 
15871   // C++ [over.oper]p8:
15872   //   An operator function cannot have default arguments (8.3.6),
15873   //   except where explicitly stated below.
15874   //
15875   // Only the function-call operator (C++ [over.call]p1) and the subscript
15876   // operator (CWG2507) allow default arguments.
15877   if (Op != OO_Call) {
15878     ParmVarDecl *FirstDefaultedParam = nullptr;
15879     for (auto Param : FnDecl->parameters()) {
15880       if (Param->hasDefaultArg()) {
15881         FirstDefaultedParam = Param;
15882         break;
15883       }
15884     }
15885     if (FirstDefaultedParam) {
15886       if (Op == OO_Subscript) {
15887         Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15888                                         ? diag::ext_subscript_overload
15889                                         : diag::error_subscript_overload)
15890             << FnDecl->getDeclName() << 1
15891             << FirstDefaultedParam->getDefaultArgRange();
15892       } else {
15893         return Diag(FirstDefaultedParam->getLocation(),
15894                     diag::err_operator_overload_default_arg)
15895                << FnDecl->getDeclName()
15896                << FirstDefaultedParam->getDefaultArgRange();
15897       }
15898     }
15899   }
15900 
15901   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15902     { false, false, false }
15903 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15904     , { Unary, Binary, MemberOnly }
15905 #include "clang/Basic/OperatorKinds.def"
15906   };
15907 
15908   bool CanBeUnaryOperator = OperatorUses[Op][0];
15909   bool CanBeBinaryOperator = OperatorUses[Op][1];
15910   bool MustBeMemberOperator = OperatorUses[Op][2];
15911 
15912   // C++ [over.oper]p8:
15913   //   [...] Operator functions cannot have more or fewer parameters
15914   //   than the number required for the corresponding operator, as
15915   //   described in the rest of this subclause.
15916   unsigned NumParams = FnDecl->getNumParams()
15917                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15918   if (Op != OO_Call && Op != OO_Subscript &&
15919       ((NumParams == 1 && !CanBeUnaryOperator) ||
15920        (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
15921        (NumParams > 2))) {
15922     // We have the wrong number of parameters.
15923     unsigned ErrorKind;
15924     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15925       ErrorKind = 2;  // 2 -> unary or binary.
15926     } else if (CanBeUnaryOperator) {
15927       ErrorKind = 0;  // 0 -> unary
15928     } else {
15929       assert(CanBeBinaryOperator &&
15930              "All non-call overloaded operators are unary or binary!");
15931       ErrorKind = 1;  // 1 -> binary
15932     }
15933     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15934       << FnDecl->getDeclName() << NumParams << ErrorKind;
15935   }
15936 
15937   if (Op == OO_Subscript && NumParams != 2) {
15938     Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15939                                     ? diag::ext_subscript_overload
15940                                     : diag::error_subscript_overload)
15941         << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
15942   }
15943 
15944   // Overloaded operators other than operator() and operator[] cannot be
15945   // variadic.
15946   if (Op != OO_Call &&
15947       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15948     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15949            << FnDecl->getDeclName();
15950   }
15951 
15952   // Some operators must be non-static member functions.
15953   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15954     return Diag(FnDecl->getLocation(),
15955                 diag::err_operator_overload_must_be_member)
15956       << FnDecl->getDeclName();
15957   }
15958 
15959   // C++ [over.inc]p1:
15960   //   The user-defined function called operator++ implements the
15961   //   prefix and postfix ++ operator. If this function is a member
15962   //   function with no parameters, or a non-member function with one
15963   //   parameter of class or enumeration type, it defines the prefix
15964   //   increment operator ++ for objects of that type. If the function
15965   //   is a member function with one parameter (which shall be of type
15966   //   int) or a non-member function with two parameters (the second
15967   //   of which shall be of type int), it defines the postfix
15968   //   increment operator ++ for objects of that type.
15969   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15970     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15971     QualType ParamType = LastParam->getType();
15972 
15973     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15974         !ParamType->isDependentType())
15975       return Diag(LastParam->getLocation(),
15976                   diag::err_operator_overload_post_incdec_must_be_int)
15977         << LastParam->getType() << (Op == OO_MinusMinus);
15978   }
15979 
15980   return false;
15981 }
15982 
15983 static bool
15984 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15985                                           FunctionTemplateDecl *TpDecl) {
15986   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15987 
15988   // Must have one or two template parameters.
15989   if (TemplateParams->size() == 1) {
15990     NonTypeTemplateParmDecl *PmDecl =
15991         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15992 
15993     // The template parameter must be a char parameter pack.
15994     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15995         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15996       return false;
15997 
15998     // C++20 [over.literal]p5:
15999     //   A string literal operator template is a literal operator template
16000     //   whose template-parameter-list comprises a single non-type
16001     //   template-parameter of class type.
16002     //
16003     // As a DR resolution, we also allow placeholders for deduced class
16004     // template specializations.
16005     if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16006         !PmDecl->isTemplateParameterPack() &&
16007         (PmDecl->getType()->isRecordType() ||
16008          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16009       return false;
16010   } else if (TemplateParams->size() == 2) {
16011     TemplateTypeParmDecl *PmType =
16012         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16013     NonTypeTemplateParmDecl *PmArgs =
16014         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16015 
16016     // The second template parameter must be a parameter pack with the
16017     // first template parameter as its type.
16018     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16019         PmArgs->isTemplateParameterPack()) {
16020       const TemplateTypeParmType *TArgs =
16021           PmArgs->getType()->getAs<TemplateTypeParmType>();
16022       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16023           TArgs->getIndex() == PmType->getIndex()) {
16024         if (!SemaRef.inTemplateInstantiation())
16025           SemaRef.Diag(TpDecl->getLocation(),
16026                        diag::ext_string_literal_operator_template);
16027         return false;
16028       }
16029     }
16030   }
16031 
16032   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16033                diag::err_literal_operator_template)
16034       << TpDecl->getTemplateParameters()->getSourceRange();
16035   return true;
16036 }
16037 
16038 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16039 /// of this literal operator function is well-formed. If so, returns
16040 /// false; otherwise, emits appropriate diagnostics and returns true.
16041 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16042   if (isa<CXXMethodDecl>(FnDecl)) {
16043     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16044       << FnDecl->getDeclName();
16045     return true;
16046   }
16047 
16048   if (FnDecl->isExternC()) {
16049     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16050     if (const LinkageSpecDecl *LSD =
16051             FnDecl->getDeclContext()->getExternCContext())
16052       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16053     return true;
16054   }
16055 
16056   // This might be the definition of a literal operator template.
16057   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16058 
16059   // This might be a specialization of a literal operator template.
16060   if (!TpDecl)
16061     TpDecl = FnDecl->getPrimaryTemplate();
16062 
16063   // template <char...> type operator "" name() and
16064   // template <class T, T...> type operator "" name() are the only valid
16065   // template signatures, and the only valid signatures with no parameters.
16066   //
16067   // C++20 also allows template <SomeClass T> type operator "" name().
16068   if (TpDecl) {
16069     if (FnDecl->param_size() != 0) {
16070       Diag(FnDecl->getLocation(),
16071            diag::err_literal_operator_template_with_params);
16072       return true;
16073     }
16074 
16075     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16076       return true;
16077 
16078   } else if (FnDecl->param_size() == 1) {
16079     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16080 
16081     QualType ParamType = Param->getType().getUnqualifiedType();
16082 
16083     // Only unsigned long long int, long double, any character type, and const
16084     // char * are allowed as the only parameters.
16085     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16086         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16087         Context.hasSameType(ParamType, Context.CharTy) ||
16088         Context.hasSameType(ParamType, Context.WideCharTy) ||
16089         Context.hasSameType(ParamType, Context.Char8Ty) ||
16090         Context.hasSameType(ParamType, Context.Char16Ty) ||
16091         Context.hasSameType(ParamType, Context.Char32Ty)) {
16092     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16093       QualType InnerType = Ptr->getPointeeType();
16094 
16095       // Pointer parameter must be a const char *.
16096       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16097                                 Context.CharTy) &&
16098             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16099         Diag(Param->getSourceRange().getBegin(),
16100              diag::err_literal_operator_param)
16101             << ParamType << "'const char *'" << Param->getSourceRange();
16102         return true;
16103       }
16104 
16105     } else if (ParamType->isRealFloatingType()) {
16106       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16107           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16108       return true;
16109 
16110     } else if (ParamType->isIntegerType()) {
16111       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16112           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16113       return true;
16114 
16115     } else {
16116       Diag(Param->getSourceRange().getBegin(),
16117            diag::err_literal_operator_invalid_param)
16118           << ParamType << Param->getSourceRange();
16119       return true;
16120     }
16121 
16122   } else if (FnDecl->param_size() == 2) {
16123     FunctionDecl::param_iterator Param = FnDecl->param_begin();
16124 
16125     // First, verify that the first parameter is correct.
16126 
16127     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16128 
16129     // Two parameter function must have a pointer to const as a
16130     // first parameter; let's strip those qualifiers.
16131     const PointerType *PT = FirstParamType->getAs<PointerType>();
16132 
16133     if (!PT) {
16134       Diag((*Param)->getSourceRange().getBegin(),
16135            diag::err_literal_operator_param)
16136           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16137       return true;
16138     }
16139 
16140     QualType PointeeType = PT->getPointeeType();
16141     // First parameter must be const
16142     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16143       Diag((*Param)->getSourceRange().getBegin(),
16144            diag::err_literal_operator_param)
16145           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16146       return true;
16147     }
16148 
16149     QualType InnerType = PointeeType.getUnqualifiedType();
16150     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16151     // const char32_t* are allowed as the first parameter to a two-parameter
16152     // function
16153     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16154           Context.hasSameType(InnerType, Context.WideCharTy) ||
16155           Context.hasSameType(InnerType, Context.Char8Ty) ||
16156           Context.hasSameType(InnerType, Context.Char16Ty) ||
16157           Context.hasSameType(InnerType, Context.Char32Ty))) {
16158       Diag((*Param)->getSourceRange().getBegin(),
16159            diag::err_literal_operator_param)
16160           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16161       return true;
16162     }
16163 
16164     // Move on to the second and final parameter.
16165     ++Param;
16166 
16167     // The second parameter must be a std::size_t.
16168     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16169     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16170       Diag((*Param)->getSourceRange().getBegin(),
16171            diag::err_literal_operator_param)
16172           << SecondParamType << Context.getSizeType()
16173           << (*Param)->getSourceRange();
16174       return true;
16175     }
16176   } else {
16177     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16178     return true;
16179   }
16180 
16181   // Parameters are good.
16182 
16183   // A parameter-declaration-clause containing a default argument is not
16184   // equivalent to any of the permitted forms.
16185   for (auto Param : FnDecl->parameters()) {
16186     if (Param->hasDefaultArg()) {
16187       Diag(Param->getDefaultArgRange().getBegin(),
16188            diag::err_literal_operator_default_argument)
16189         << Param->getDefaultArgRange();
16190       break;
16191     }
16192   }
16193 
16194   StringRef LiteralName
16195     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16196   if (LiteralName[0] != '_' &&
16197       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16198     // C++11 [usrlit.suffix]p1:
16199     //   Literal suffix identifiers that do not start with an underscore
16200     //   are reserved for future standardization.
16201     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16202       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16203   }
16204 
16205   return false;
16206 }
16207 
16208 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16209 /// linkage specification, including the language and (if present)
16210 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16211 /// language string literal. LBraceLoc, if valid, provides the location of
16212 /// the '{' brace. Otherwise, this linkage specification does not
16213 /// have any braces.
16214 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16215                                            Expr *LangStr,
16216                                            SourceLocation LBraceLoc) {
16217   StringLiteral *Lit = cast<StringLiteral>(LangStr);
16218   if (!Lit->isAscii()) {
16219     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16220       << LangStr->getSourceRange();
16221     return nullptr;
16222   }
16223 
16224   StringRef Lang = Lit->getString();
16225   LinkageSpecDecl::LanguageIDs Language;
16226   if (Lang == "C")
16227     Language = LinkageSpecDecl::lang_c;
16228   else if (Lang == "C++")
16229     Language = LinkageSpecDecl::lang_cxx;
16230   else {
16231     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16232       << LangStr->getSourceRange();
16233     return nullptr;
16234   }
16235 
16236   // FIXME: Add all the various semantics of linkage specifications
16237 
16238   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16239                                                LangStr->getExprLoc(), Language,
16240                                                LBraceLoc.isValid());
16241 
16242   /// C++ [module.unit]p7.2.3
16243   /// - Otherwise, if the declaration
16244   ///   - ...
16245   ///   - ...
16246   ///   - appears within a linkage-specification,
16247   ///   it is attached to the global module.
16248   ///
16249   /// If the declaration is already in global module fragment, we don't
16250   /// need to attach it again.
16251   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16252     Module *GlobalModule =
16253         PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
16254     D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16255     D->setLocalOwningModule(GlobalModule);
16256   }
16257 
16258   CurContext->addDecl(D);
16259   PushDeclContext(S, D);
16260   return D;
16261 }
16262 
16263 /// ActOnFinishLinkageSpecification - Complete the definition of
16264 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16265 /// valid, it's the position of the closing '}' brace in a linkage
16266 /// specification that uses braces.
16267 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16268                                             Decl *LinkageSpec,
16269                                             SourceLocation RBraceLoc) {
16270   if (RBraceLoc.isValid()) {
16271     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16272     LSDecl->setRBraceLoc(RBraceLoc);
16273   }
16274 
16275   // If the current module doesn't has Parent, it implies that the
16276   // LinkageSpec isn't in the module created by itself. So we don't
16277   // need to pop it.
16278   if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16279       getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
16280     PopGlobalModuleFragment();
16281 
16282   PopDeclContext();
16283   return LinkageSpec;
16284 }
16285 
16286 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16287                                   const ParsedAttributesView &AttrList,
16288                                   SourceLocation SemiLoc) {
16289   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16290   // Attribute declarations appertain to empty declaration so we handle
16291   // them here.
16292   ProcessDeclAttributeList(S, ED, AttrList);
16293 
16294   CurContext->addDecl(ED);
16295   return ED;
16296 }
16297 
16298 /// Perform semantic analysis for the variable declaration that
16299 /// occurs within a C++ catch clause, returning the newly-created
16300 /// variable.
16301 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16302                                          TypeSourceInfo *TInfo,
16303                                          SourceLocation StartLoc,
16304                                          SourceLocation Loc,
16305                                          IdentifierInfo *Name) {
16306   bool Invalid = false;
16307   QualType ExDeclType = TInfo->getType();
16308 
16309   // Arrays and functions decay.
16310   if (ExDeclType->isArrayType())
16311     ExDeclType = Context.getArrayDecayedType(ExDeclType);
16312   else if (ExDeclType->isFunctionType())
16313     ExDeclType = Context.getPointerType(ExDeclType);
16314 
16315   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16316   // The exception-declaration shall not denote a pointer or reference to an
16317   // incomplete type, other than [cv] void*.
16318   // N2844 forbids rvalue references.
16319   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16320     Diag(Loc, diag::err_catch_rvalue_ref);
16321     Invalid = true;
16322   }
16323 
16324   if (ExDeclType->isVariablyModifiedType()) {
16325     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16326     Invalid = true;
16327   }
16328 
16329   QualType BaseType = ExDeclType;
16330   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16331   unsigned DK = diag::err_catch_incomplete;
16332   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16333     BaseType = Ptr->getPointeeType();
16334     Mode = 1;
16335     DK = diag::err_catch_incomplete_ptr;
16336   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16337     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16338     BaseType = Ref->getPointeeType();
16339     Mode = 2;
16340     DK = diag::err_catch_incomplete_ref;
16341   }
16342   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16343       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16344     Invalid = true;
16345 
16346   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16347     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16348     Invalid = true;
16349   }
16350 
16351   if (!Invalid && !ExDeclType->isDependentType() &&
16352       RequireNonAbstractType(Loc, ExDeclType,
16353                              diag::err_abstract_type_in_decl,
16354                              AbstractVariableType))
16355     Invalid = true;
16356 
16357   // Only the non-fragile NeXT runtime currently supports C++ catches
16358   // of ObjC types, and no runtime supports catching ObjC types by value.
16359   if (!Invalid && getLangOpts().ObjC) {
16360     QualType T = ExDeclType;
16361     if (const ReferenceType *RT = T->getAs<ReferenceType>())
16362       T = RT->getPointeeType();
16363 
16364     if (T->isObjCObjectType()) {
16365       Diag(Loc, diag::err_objc_object_catch);
16366       Invalid = true;
16367     } else if (T->isObjCObjectPointerType()) {
16368       // FIXME: should this be a test for macosx-fragile specifically?
16369       if (getLangOpts().ObjCRuntime.isFragile())
16370         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16371     }
16372   }
16373 
16374   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16375                                     ExDeclType, TInfo, SC_None);
16376   ExDecl->setExceptionVariable(true);
16377 
16378   // In ARC, infer 'retaining' for variables of retainable type.
16379   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16380     Invalid = true;
16381 
16382   if (!Invalid && !ExDeclType->isDependentType()) {
16383     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16384       // Insulate this from anything else we might currently be parsing.
16385       EnterExpressionEvaluationContext scope(
16386           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16387 
16388       // C++ [except.handle]p16:
16389       //   The object declared in an exception-declaration or, if the
16390       //   exception-declaration does not specify a name, a temporary (12.2) is
16391       //   copy-initialized (8.5) from the exception object. [...]
16392       //   The object is destroyed when the handler exits, after the destruction
16393       //   of any automatic objects initialized within the handler.
16394       //
16395       // We just pretend to initialize the object with itself, then make sure
16396       // it can be destroyed later.
16397       QualType initType = Context.getExceptionObjectType(ExDeclType);
16398 
16399       InitializedEntity entity =
16400         InitializedEntity::InitializeVariable(ExDecl);
16401       InitializationKind initKind =
16402         InitializationKind::CreateCopy(Loc, SourceLocation());
16403 
16404       Expr *opaqueValue =
16405         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16406       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16407       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16408       if (result.isInvalid())
16409         Invalid = true;
16410       else {
16411         // If the constructor used was non-trivial, set this as the
16412         // "initializer".
16413         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16414         if (!construct->getConstructor()->isTrivial()) {
16415           Expr *init = MaybeCreateExprWithCleanups(construct);
16416           ExDecl->setInit(init);
16417         }
16418 
16419         // And make sure it's destructable.
16420         FinalizeVarWithDestructor(ExDecl, recordType);
16421       }
16422     }
16423   }
16424 
16425   if (Invalid)
16426     ExDecl->setInvalidDecl();
16427 
16428   return ExDecl;
16429 }
16430 
16431 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16432 /// handler.
16433 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16434   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16435   bool Invalid = D.isInvalidType();
16436 
16437   // Check for unexpanded parameter packs.
16438   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16439                                       UPPC_ExceptionType)) {
16440     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16441                                              D.getIdentifierLoc());
16442     Invalid = true;
16443   }
16444 
16445   IdentifierInfo *II = D.getIdentifier();
16446   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16447                                              LookupOrdinaryName,
16448                                              ForVisibleRedeclaration)) {
16449     // The scope should be freshly made just for us. There is just no way
16450     // it contains any previous declaration, except for function parameters in
16451     // a function-try-block's catch statement.
16452     assert(!S->isDeclScope(PrevDecl));
16453     if (isDeclInScope(PrevDecl, CurContext, S)) {
16454       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16455         << D.getIdentifier();
16456       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16457       Invalid = true;
16458     } else if (PrevDecl->isTemplateParameter())
16459       // Maybe we will complain about the shadowed template parameter.
16460       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16461   }
16462 
16463   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16464     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16465       << D.getCXXScopeSpec().getRange();
16466     Invalid = true;
16467   }
16468 
16469   VarDecl *ExDecl = BuildExceptionDeclaration(
16470       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16471   if (Invalid)
16472     ExDecl->setInvalidDecl();
16473 
16474   // Add the exception declaration into this scope.
16475   if (II)
16476     PushOnScopeChains(ExDecl, S);
16477   else
16478     CurContext->addDecl(ExDecl);
16479 
16480   ProcessDeclAttributes(S, ExDecl, D);
16481   return ExDecl;
16482 }
16483 
16484 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16485                                          Expr *AssertExpr,
16486                                          Expr *AssertMessageExpr,
16487                                          SourceLocation RParenLoc) {
16488   StringLiteral *AssertMessage =
16489       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16490 
16491   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16492     return nullptr;
16493 
16494   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16495                                       AssertMessage, RParenLoc, false);
16496 }
16497 
16498 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16499                                          Expr *AssertExpr,
16500                                          StringLiteral *AssertMessage,
16501                                          SourceLocation RParenLoc,
16502                                          bool Failed) {
16503   assert(AssertExpr != nullptr && "Expected non-null condition");
16504   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16505       !Failed) {
16506     // In a static_assert-declaration, the constant-expression shall be a
16507     // constant expression that can be contextually converted to bool.
16508     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16509     if (Converted.isInvalid())
16510       Failed = true;
16511 
16512     ExprResult FullAssertExpr =
16513         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16514                             /*DiscardedValue*/ false,
16515                             /*IsConstexpr*/ true);
16516     if (FullAssertExpr.isInvalid())
16517       Failed = true;
16518     else
16519       AssertExpr = FullAssertExpr.get();
16520 
16521     llvm::APSInt Cond;
16522     if (!Failed && VerifyIntegerConstantExpression(
16523                        AssertExpr, &Cond,
16524                        diag::err_static_assert_expression_is_not_constant)
16525                        .isInvalid())
16526       Failed = true;
16527 
16528     if (!Failed && !Cond) {
16529       SmallString<256> MsgBuffer;
16530       llvm::raw_svector_ostream Msg(MsgBuffer);
16531       if (AssertMessage)
16532         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16533 
16534       Expr *InnerCond = nullptr;
16535       std::string InnerCondDescription;
16536       std::tie(InnerCond, InnerCondDescription) =
16537         findFailedBooleanCondition(Converted.get());
16538       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16539         // Drill down into concept specialization expressions to see why they
16540         // weren't satisfied.
16541         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16542           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16543         ConstraintSatisfaction Satisfaction;
16544         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16545           DiagnoseUnsatisfiedConstraint(Satisfaction);
16546       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16547                            && !isa<IntegerLiteral>(InnerCond)) {
16548         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16549           << InnerCondDescription << !AssertMessage
16550           << Msg.str() << InnerCond->getSourceRange();
16551       } else {
16552         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16553           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16554       }
16555       Failed = true;
16556     }
16557   } else {
16558     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16559                                                     /*DiscardedValue*/false,
16560                                                     /*IsConstexpr*/true);
16561     if (FullAssertExpr.isInvalid())
16562       Failed = true;
16563     else
16564       AssertExpr = FullAssertExpr.get();
16565   }
16566 
16567   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16568                                         AssertExpr, AssertMessage, RParenLoc,
16569                                         Failed);
16570 
16571   CurContext->addDecl(Decl);
16572   return Decl;
16573 }
16574 
16575 /// Perform semantic analysis of the given friend type declaration.
16576 ///
16577 /// \returns A friend declaration that.
16578 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16579                                       SourceLocation FriendLoc,
16580                                       TypeSourceInfo *TSInfo) {
16581   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16582 
16583   QualType T = TSInfo->getType();
16584   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16585 
16586   // C++03 [class.friend]p2:
16587   //   An elaborated-type-specifier shall be used in a friend declaration
16588   //   for a class.*
16589   //
16590   //   * The class-key of the elaborated-type-specifier is required.
16591   if (!CodeSynthesisContexts.empty()) {
16592     // Do not complain about the form of friend template types during any kind
16593     // of code synthesis. For template instantiation, we will have complained
16594     // when the template was defined.
16595   } else {
16596     if (!T->isElaboratedTypeSpecifier()) {
16597       // If we evaluated the type to a record type, suggest putting
16598       // a tag in front.
16599       if (const RecordType *RT = T->getAs<RecordType>()) {
16600         RecordDecl *RD = RT->getDecl();
16601 
16602         SmallString<16> InsertionText(" ");
16603         InsertionText += RD->getKindName();
16604 
16605         Diag(TypeRange.getBegin(),
16606              getLangOpts().CPlusPlus11 ?
16607                diag::warn_cxx98_compat_unelaborated_friend_type :
16608                diag::ext_unelaborated_friend_type)
16609           << (unsigned) RD->getTagKind()
16610           << T
16611           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16612                                         InsertionText);
16613       } else {
16614         Diag(FriendLoc,
16615              getLangOpts().CPlusPlus11 ?
16616                diag::warn_cxx98_compat_nonclass_type_friend :
16617                diag::ext_nonclass_type_friend)
16618           << T
16619           << TypeRange;
16620       }
16621     } else if (T->getAs<EnumType>()) {
16622       Diag(FriendLoc,
16623            getLangOpts().CPlusPlus11 ?
16624              diag::warn_cxx98_compat_enum_friend :
16625              diag::ext_enum_friend)
16626         << T
16627         << TypeRange;
16628     }
16629 
16630     // C++11 [class.friend]p3:
16631     //   A friend declaration that does not declare a function shall have one
16632     //   of the following forms:
16633     //     friend elaborated-type-specifier ;
16634     //     friend simple-type-specifier ;
16635     //     friend typename-specifier ;
16636     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16637       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16638   }
16639 
16640   //   If the type specifier in a friend declaration designates a (possibly
16641   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16642   //   the friend declaration is ignored.
16643   return FriendDecl::Create(Context, CurContext,
16644                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16645                             FriendLoc);
16646 }
16647 
16648 /// Handle a friend tag declaration where the scope specifier was
16649 /// templated.
16650 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16651                                     unsigned TagSpec, SourceLocation TagLoc,
16652                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16653                                     SourceLocation NameLoc,
16654                                     const ParsedAttributesView &Attr,
16655                                     MultiTemplateParamsArg TempParamLists) {
16656   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16657 
16658   bool IsMemberSpecialization = false;
16659   bool Invalid = false;
16660 
16661   if (TemplateParameterList *TemplateParams =
16662           MatchTemplateParametersToScopeSpecifier(
16663               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16664               IsMemberSpecialization, Invalid)) {
16665     if (TemplateParams->size() > 0) {
16666       // This is a declaration of a class template.
16667       if (Invalid)
16668         return nullptr;
16669 
16670       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16671                                 NameLoc, Attr, TemplateParams, AS_public,
16672                                 /*ModulePrivateLoc=*/SourceLocation(),
16673                                 FriendLoc, TempParamLists.size() - 1,
16674                                 TempParamLists.data()).get();
16675     } else {
16676       // The "template<>" header is extraneous.
16677       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16678         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16679       IsMemberSpecialization = true;
16680     }
16681   }
16682 
16683   if (Invalid) return nullptr;
16684 
16685   bool isAllExplicitSpecializations = true;
16686   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16687     if (TempParamLists[I]->size()) {
16688       isAllExplicitSpecializations = false;
16689       break;
16690     }
16691   }
16692 
16693   // FIXME: don't ignore attributes.
16694 
16695   // If it's explicit specializations all the way down, just forget
16696   // about the template header and build an appropriate non-templated
16697   // friend.  TODO: for source fidelity, remember the headers.
16698   if (isAllExplicitSpecializations) {
16699     if (SS.isEmpty()) {
16700       bool Owned = false;
16701       bool IsDependent = false;
16702       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16703                       Attr, AS_public,
16704                       /*ModulePrivateLoc=*/SourceLocation(),
16705                       MultiTemplateParamsArg(), Owned, IsDependent,
16706                       /*ScopedEnumKWLoc=*/SourceLocation(),
16707                       /*ScopedEnumUsesClassTag=*/false,
16708                       /*UnderlyingType=*/TypeResult(),
16709                       /*IsTypeSpecifier=*/false,
16710                       /*IsTemplateParamOrArg=*/false);
16711     }
16712 
16713     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16714     ElaboratedTypeKeyword Keyword
16715       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16716     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16717                                    *Name, NameLoc);
16718     if (T.isNull())
16719       return nullptr;
16720 
16721     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16722     if (isa<DependentNameType>(T)) {
16723       DependentNameTypeLoc TL =
16724           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16725       TL.setElaboratedKeywordLoc(TagLoc);
16726       TL.setQualifierLoc(QualifierLoc);
16727       TL.setNameLoc(NameLoc);
16728     } else {
16729       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16730       TL.setElaboratedKeywordLoc(TagLoc);
16731       TL.setQualifierLoc(QualifierLoc);
16732       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16733     }
16734 
16735     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16736                                             TSI, FriendLoc, TempParamLists);
16737     Friend->setAccess(AS_public);
16738     CurContext->addDecl(Friend);
16739     return Friend;
16740   }
16741 
16742   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16743 
16744 
16745 
16746   // Handle the case of a templated-scope friend class.  e.g.
16747   //   template <class T> class A<T>::B;
16748   // FIXME: we don't support these right now.
16749   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16750     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16751   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16752   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16753   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16754   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16755   TL.setElaboratedKeywordLoc(TagLoc);
16756   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16757   TL.setNameLoc(NameLoc);
16758 
16759   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16760                                           TSI, FriendLoc, TempParamLists);
16761   Friend->setAccess(AS_public);
16762   Friend->setUnsupportedFriend(true);
16763   CurContext->addDecl(Friend);
16764   return Friend;
16765 }
16766 
16767 /// Handle a friend type declaration.  This works in tandem with
16768 /// ActOnTag.
16769 ///
16770 /// Notes on friend class templates:
16771 ///
16772 /// We generally treat friend class declarations as if they were
16773 /// declaring a class.  So, for example, the elaborated type specifier
16774 /// in a friend declaration is required to obey the restrictions of a
16775 /// class-head (i.e. no typedefs in the scope chain), template
16776 /// parameters are required to match up with simple template-ids, &c.
16777 /// However, unlike when declaring a template specialization, it's
16778 /// okay to refer to a template specialization without an empty
16779 /// template parameter declaration, e.g.
16780 ///   friend class A<T>::B<unsigned>;
16781 /// We permit this as a special case; if there are any template
16782 /// parameters present at all, require proper matching, i.e.
16783 ///   template <> template \<class T> friend class A<int>::B;
16784 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16785                                 MultiTemplateParamsArg TempParams) {
16786   SourceLocation Loc = DS.getBeginLoc();
16787 
16788   assert(DS.isFriendSpecified());
16789   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16790 
16791   // C++ [class.friend]p3:
16792   // A friend declaration that does not declare a function shall have one of
16793   // the following forms:
16794   //     friend elaborated-type-specifier ;
16795   //     friend simple-type-specifier ;
16796   //     friend typename-specifier ;
16797   //
16798   // Any declaration with a type qualifier does not have that form. (It's
16799   // legal to specify a qualified type as a friend, you just can't write the
16800   // keywords.)
16801   if (DS.getTypeQualifiers()) {
16802     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16803       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16804     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16805       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16806     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16807       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16808     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16809       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16810     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16811       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16812   }
16813 
16814   // Try to convert the decl specifier to a type.  This works for
16815   // friend templates because ActOnTag never produces a ClassTemplateDecl
16816   // for a TUK_Friend.
16817   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16818   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16819   QualType T = TSI->getType();
16820   if (TheDeclarator.isInvalidType())
16821     return nullptr;
16822 
16823   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16824     return nullptr;
16825 
16826   // This is definitely an error in C++98.  It's probably meant to
16827   // be forbidden in C++0x, too, but the specification is just
16828   // poorly written.
16829   //
16830   // The problem is with declarations like the following:
16831   //   template <T> friend A<T>::foo;
16832   // where deciding whether a class C is a friend or not now hinges
16833   // on whether there exists an instantiation of A that causes
16834   // 'foo' to equal C.  There are restrictions on class-heads
16835   // (which we declare (by fiat) elaborated friend declarations to
16836   // be) that makes this tractable.
16837   //
16838   // FIXME: handle "template <> friend class A<T>;", which
16839   // is possibly well-formed?  Who even knows?
16840   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16841     Diag(Loc, diag::err_tagless_friend_type_template)
16842       << DS.getSourceRange();
16843     return nullptr;
16844   }
16845 
16846   // C++98 [class.friend]p1: A friend of a class is a function
16847   //   or class that is not a member of the class . . .
16848   // This is fixed in DR77, which just barely didn't make the C++03
16849   // deadline.  It's also a very silly restriction that seriously
16850   // affects inner classes and which nobody else seems to implement;
16851   // thus we never diagnose it, not even in -pedantic.
16852   //
16853   // But note that we could warn about it: it's always useless to
16854   // friend one of your own members (it's not, however, worthless to
16855   // friend a member of an arbitrary specialization of your template).
16856 
16857   Decl *D;
16858   if (!TempParams.empty())
16859     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16860                                    TempParams,
16861                                    TSI,
16862                                    DS.getFriendSpecLoc());
16863   else
16864     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16865 
16866   if (!D)
16867     return nullptr;
16868 
16869   D->setAccess(AS_public);
16870   CurContext->addDecl(D);
16871 
16872   return D;
16873 }
16874 
16875 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16876                                         MultiTemplateParamsArg TemplateParams) {
16877   const DeclSpec &DS = D.getDeclSpec();
16878 
16879   assert(DS.isFriendSpecified());
16880   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16881 
16882   SourceLocation Loc = D.getIdentifierLoc();
16883   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16884 
16885   // C++ [class.friend]p1
16886   //   A friend of a class is a function or class....
16887   // Note that this sees through typedefs, which is intended.
16888   // It *doesn't* see through dependent types, which is correct
16889   // according to [temp.arg.type]p3:
16890   //   If a declaration acquires a function type through a
16891   //   type dependent on a template-parameter and this causes
16892   //   a declaration that does not use the syntactic form of a
16893   //   function declarator to have a function type, the program
16894   //   is ill-formed.
16895   if (!TInfo->getType()->isFunctionType()) {
16896     Diag(Loc, diag::err_unexpected_friend);
16897 
16898     // It might be worthwhile to try to recover by creating an
16899     // appropriate declaration.
16900     return nullptr;
16901   }
16902 
16903   // C++ [namespace.memdef]p3
16904   //  - If a friend declaration in a non-local class first declares a
16905   //    class or function, the friend class or function is a member
16906   //    of the innermost enclosing namespace.
16907   //  - The name of the friend is not found by simple name lookup
16908   //    until a matching declaration is provided in that namespace
16909   //    scope (either before or after the class declaration granting
16910   //    friendship).
16911   //  - If a friend function is called, its name may be found by the
16912   //    name lookup that considers functions from namespaces and
16913   //    classes associated with the types of the function arguments.
16914   //  - When looking for a prior declaration of a class or a function
16915   //    declared as a friend, scopes outside the innermost enclosing
16916   //    namespace scope are not considered.
16917 
16918   CXXScopeSpec &SS = D.getCXXScopeSpec();
16919   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16920   assert(NameInfo.getName());
16921 
16922   // Check for unexpanded parameter packs.
16923   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16924       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16925       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16926     return nullptr;
16927 
16928   // The context we found the declaration in, or in which we should
16929   // create the declaration.
16930   DeclContext *DC;
16931   Scope *DCScope = S;
16932   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16933                         ForExternalRedeclaration);
16934 
16935   // There are five cases here.
16936   //   - There's no scope specifier and we're in a local class. Only look
16937   //     for functions declared in the immediately-enclosing block scope.
16938   // We recover from invalid scope qualifiers as if they just weren't there.
16939   FunctionDecl *FunctionContainingLocalClass = nullptr;
16940   if ((SS.isInvalid() || !SS.isSet()) &&
16941       (FunctionContainingLocalClass =
16942            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16943     // C++11 [class.friend]p11:
16944     //   If a friend declaration appears in a local class and the name
16945     //   specified is an unqualified name, a prior declaration is
16946     //   looked up without considering scopes that are outside the
16947     //   innermost enclosing non-class scope. For a friend function
16948     //   declaration, if there is no prior declaration, the program is
16949     //   ill-formed.
16950 
16951     // Find the innermost enclosing non-class scope. This is the block
16952     // scope containing the local class definition (or for a nested class,
16953     // the outer local class).
16954     DCScope = S->getFnParent();
16955 
16956     // Look up the function name in the scope.
16957     Previous.clear(LookupLocalFriendName);
16958     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16959 
16960     if (!Previous.empty()) {
16961       // All possible previous declarations must have the same context:
16962       // either they were declared at block scope or they are members of
16963       // one of the enclosing local classes.
16964       DC = Previous.getRepresentativeDecl()->getDeclContext();
16965     } else {
16966       // This is ill-formed, but provide the context that we would have
16967       // declared the function in, if we were permitted to, for error recovery.
16968       DC = FunctionContainingLocalClass;
16969     }
16970     adjustContextForLocalExternDecl(DC);
16971 
16972     // C++ [class.friend]p6:
16973     //   A function can be defined in a friend declaration of a class if and
16974     //   only if the class is a non-local class (9.8), the function name is
16975     //   unqualified, and the function has namespace scope.
16976     if (D.isFunctionDefinition()) {
16977       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16978     }
16979 
16980   //   - There's no scope specifier, in which case we just go to the
16981   //     appropriate scope and look for a function or function template
16982   //     there as appropriate.
16983   } else if (SS.isInvalid() || !SS.isSet()) {
16984     // C++11 [namespace.memdef]p3:
16985     //   If the name in a friend declaration is neither qualified nor
16986     //   a template-id and the declaration is a function or an
16987     //   elaborated-type-specifier, the lookup to determine whether
16988     //   the entity has been previously declared shall not consider
16989     //   any scopes outside the innermost enclosing namespace.
16990     bool isTemplateId =
16991         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16992 
16993     // Find the appropriate context according to the above.
16994     DC = CurContext;
16995 
16996     // Skip class contexts.  If someone can cite chapter and verse
16997     // for this behavior, that would be nice --- it's what GCC and
16998     // EDG do, and it seems like a reasonable intent, but the spec
16999     // really only says that checks for unqualified existing
17000     // declarations should stop at the nearest enclosing namespace,
17001     // not that they should only consider the nearest enclosing
17002     // namespace.
17003     while (DC->isRecord())
17004       DC = DC->getParent();
17005 
17006     DeclContext *LookupDC = DC->getNonTransparentContext();
17007     while (true) {
17008       LookupQualifiedName(Previous, LookupDC);
17009 
17010       if (!Previous.empty()) {
17011         DC = LookupDC;
17012         break;
17013       }
17014 
17015       if (isTemplateId) {
17016         if (isa<TranslationUnitDecl>(LookupDC)) break;
17017       } else {
17018         if (LookupDC->isFileContext()) break;
17019       }
17020       LookupDC = LookupDC->getParent();
17021     }
17022 
17023     DCScope = getScopeForDeclContext(S, DC);
17024 
17025   //   - There's a non-dependent scope specifier, in which case we
17026   //     compute it and do a previous lookup there for a function
17027   //     or function template.
17028   } else if (!SS.getScopeRep()->isDependent()) {
17029     DC = computeDeclContext(SS);
17030     if (!DC) return nullptr;
17031 
17032     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17033 
17034     LookupQualifiedName(Previous, DC);
17035 
17036     // C++ [class.friend]p1: A friend of a class is a function or
17037     //   class that is not a member of the class . . .
17038     if (DC->Equals(CurContext))
17039       Diag(DS.getFriendSpecLoc(),
17040            getLangOpts().CPlusPlus11 ?
17041              diag::warn_cxx98_compat_friend_is_member :
17042              diag::err_friend_is_member);
17043 
17044     if (D.isFunctionDefinition()) {
17045       // C++ [class.friend]p6:
17046       //   A function can be defined in a friend declaration of a class if and
17047       //   only if the class is a non-local class (9.8), the function name is
17048       //   unqualified, and the function has namespace scope.
17049       //
17050       // FIXME: We should only do this if the scope specifier names the
17051       // innermost enclosing namespace; otherwise the fixit changes the
17052       // meaning of the code.
17053       SemaDiagnosticBuilder DB
17054         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17055 
17056       DB << SS.getScopeRep();
17057       if (DC->isFileContext())
17058         DB << FixItHint::CreateRemoval(SS.getRange());
17059       SS.clear();
17060     }
17061 
17062   //   - There's a scope specifier that does not match any template
17063   //     parameter lists, in which case we use some arbitrary context,
17064   //     create a method or method template, and wait for instantiation.
17065   //   - There's a scope specifier that does match some template
17066   //     parameter lists, which we don't handle right now.
17067   } else {
17068     if (D.isFunctionDefinition()) {
17069       // C++ [class.friend]p6:
17070       //   A function can be defined in a friend declaration of a class if and
17071       //   only if the class is a non-local class (9.8), the function name is
17072       //   unqualified, and the function has namespace scope.
17073       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17074         << SS.getScopeRep();
17075     }
17076 
17077     DC = CurContext;
17078     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17079   }
17080 
17081   if (!DC->isRecord()) {
17082     int DiagArg = -1;
17083     switch (D.getName().getKind()) {
17084     case UnqualifiedIdKind::IK_ConstructorTemplateId:
17085     case UnqualifiedIdKind::IK_ConstructorName:
17086       DiagArg = 0;
17087       break;
17088     case UnqualifiedIdKind::IK_DestructorName:
17089       DiagArg = 1;
17090       break;
17091     case UnqualifiedIdKind::IK_ConversionFunctionId:
17092       DiagArg = 2;
17093       break;
17094     case UnqualifiedIdKind::IK_DeductionGuideName:
17095       DiagArg = 3;
17096       break;
17097     case UnqualifiedIdKind::IK_Identifier:
17098     case UnqualifiedIdKind::IK_ImplicitSelfParam:
17099     case UnqualifiedIdKind::IK_LiteralOperatorId:
17100     case UnqualifiedIdKind::IK_OperatorFunctionId:
17101     case UnqualifiedIdKind::IK_TemplateId:
17102       break;
17103     }
17104     // This implies that it has to be an operator or function.
17105     if (DiagArg >= 0) {
17106       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17107       return nullptr;
17108     }
17109   }
17110 
17111   // FIXME: This is an egregious hack to cope with cases where the scope stack
17112   // does not contain the declaration context, i.e., in an out-of-line
17113   // definition of a class.
17114   Scope FakeDCScope(S, Scope::DeclScope, Diags);
17115   if (!DCScope) {
17116     FakeDCScope.setEntity(DC);
17117     DCScope = &FakeDCScope;
17118   }
17119 
17120   bool AddToScope = true;
17121   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17122                                           TemplateParams, AddToScope);
17123   if (!ND) return nullptr;
17124 
17125   assert(ND->getLexicalDeclContext() == CurContext);
17126 
17127   // If we performed typo correction, we might have added a scope specifier
17128   // and changed the decl context.
17129   DC = ND->getDeclContext();
17130 
17131   // Add the function declaration to the appropriate lookup tables,
17132   // adjusting the redeclarations list as necessary.  We don't
17133   // want to do this yet if the friending class is dependent.
17134   //
17135   // Also update the scope-based lookup if the target context's
17136   // lookup context is in lexical scope.
17137   if (!CurContext->isDependentContext()) {
17138     DC = DC->getRedeclContext();
17139     DC->makeDeclVisibleInContext(ND);
17140     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17141       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17142   }
17143 
17144   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17145                                        D.getIdentifierLoc(), ND,
17146                                        DS.getFriendSpecLoc());
17147   FrD->setAccess(AS_public);
17148   CurContext->addDecl(FrD);
17149 
17150   if (ND->isInvalidDecl()) {
17151     FrD->setInvalidDecl();
17152   } else {
17153     if (DC->isRecord()) CheckFriendAccess(ND);
17154 
17155     FunctionDecl *FD;
17156     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17157       FD = FTD->getTemplatedDecl();
17158     else
17159       FD = cast<FunctionDecl>(ND);
17160 
17161     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17162     // default argument expression, that declaration shall be a definition
17163     // and shall be the only declaration of the function or function
17164     // template in the translation unit.
17165     if (functionDeclHasDefaultArgument(FD)) {
17166       // We can't look at FD->getPreviousDecl() because it may not have been set
17167       // if we're in a dependent context. If the function is known to be a
17168       // redeclaration, we will have narrowed Previous down to the right decl.
17169       if (D.isRedeclaration()) {
17170         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17171         Diag(Previous.getRepresentativeDecl()->getLocation(),
17172              diag::note_previous_declaration);
17173       } else if (!D.isFunctionDefinition())
17174         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17175     }
17176 
17177     // Mark templated-scope function declarations as unsupported.
17178     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17179       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17180         << SS.getScopeRep() << SS.getRange()
17181         << cast<CXXRecordDecl>(CurContext);
17182       FrD->setUnsupportedFriend(true);
17183     }
17184   }
17185 
17186   warnOnReservedIdentifier(ND);
17187 
17188   return ND;
17189 }
17190 
17191 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17192   AdjustDeclIfTemplate(Dcl);
17193 
17194   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17195   if (!Fn) {
17196     Diag(DelLoc, diag::err_deleted_non_function);
17197     return;
17198   }
17199 
17200   // Deleted function does not have a body.
17201   Fn->setWillHaveBody(false);
17202 
17203   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17204     // Don't consider the implicit declaration we generate for explicit
17205     // specializations. FIXME: Do not generate these implicit declarations.
17206     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17207          Prev->getPreviousDecl()) &&
17208         !Prev->isDefined()) {
17209       Diag(DelLoc, diag::err_deleted_decl_not_first);
17210       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17211            Prev->isImplicit() ? diag::note_previous_implicit_declaration
17212                               : diag::note_previous_declaration);
17213       // We can't recover from this; the declaration might have already
17214       // been used.
17215       Fn->setInvalidDecl();
17216       return;
17217     }
17218 
17219     // To maintain the invariant that functions are only deleted on their first
17220     // declaration, mark the implicitly-instantiated declaration of the
17221     // explicitly-specialized function as deleted instead of marking the
17222     // instantiated redeclaration.
17223     Fn = Fn->getCanonicalDecl();
17224   }
17225 
17226   // dllimport/dllexport cannot be deleted.
17227   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17228     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17229     Fn->setInvalidDecl();
17230   }
17231 
17232   // C++11 [basic.start.main]p3:
17233   //   A program that defines main as deleted [...] is ill-formed.
17234   if (Fn->isMain())
17235     Diag(DelLoc, diag::err_deleted_main);
17236 
17237   // C++11 [dcl.fct.def.delete]p4:
17238   //  A deleted function is implicitly inline.
17239   Fn->setImplicitlyInline();
17240   Fn->setDeletedAsWritten();
17241 }
17242 
17243 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17244   if (!Dcl || Dcl->isInvalidDecl())
17245     return;
17246 
17247   auto *FD = dyn_cast<FunctionDecl>(Dcl);
17248   if (!FD) {
17249     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17250       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17251         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17252         return;
17253       }
17254     }
17255 
17256     Diag(DefaultLoc, diag::err_default_special_members)
17257         << getLangOpts().CPlusPlus20;
17258     return;
17259   }
17260 
17261   // Reject if this can't possibly be a defaultable function.
17262   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17263   if (!DefKind &&
17264       // A dependent function that doesn't locally look defaultable can
17265       // still instantiate to a defaultable function if it's a constructor
17266       // or assignment operator.
17267       (!FD->isDependentContext() ||
17268        (!isa<CXXConstructorDecl>(FD) &&
17269         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17270     Diag(DefaultLoc, diag::err_default_special_members)
17271         << getLangOpts().CPlusPlus20;
17272     return;
17273   }
17274 
17275   // Issue compatibility warning. We already warned if the operator is
17276   // 'operator<=>' when parsing the '<=>' token.
17277   if (DefKind.isComparison() &&
17278       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17279     Diag(DefaultLoc, getLangOpts().CPlusPlus20
17280                          ? diag::warn_cxx17_compat_defaulted_comparison
17281                          : diag::ext_defaulted_comparison);
17282   }
17283 
17284   FD->setDefaulted();
17285   FD->setExplicitlyDefaulted();
17286 
17287   // Defer checking functions that are defaulted in a dependent context.
17288   if (FD->isDependentContext())
17289     return;
17290 
17291   // Unset that we will have a body for this function. We might not,
17292   // if it turns out to be trivial, and we don't need this marking now
17293   // that we've marked it as defaulted.
17294   FD->setWillHaveBody(false);
17295 
17296   if (DefKind.isComparison()) {
17297     // If this comparison's defaulting occurs within the definition of its
17298     // lexical class context, we have to do the checking when complete.
17299     if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17300       if (!RD->isCompleteDefinition())
17301         return;
17302   }
17303 
17304   // If this member fn was defaulted on its first declaration, we will have
17305   // already performed the checking in CheckCompletedCXXClass. Such a
17306   // declaration doesn't trigger an implicit definition.
17307   if (isa<CXXMethodDecl>(FD)) {
17308     const FunctionDecl *Primary = FD;
17309     if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17310       // Ask the template instantiation pattern that actually had the
17311       // '= default' on it.
17312       Primary = Pattern;
17313     if (Primary->getCanonicalDecl()->isDefaulted())
17314       return;
17315   }
17316 
17317   if (DefKind.isComparison()) {
17318     if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17319       FD->setInvalidDecl();
17320     else
17321       DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17322   } else {
17323     auto *MD = cast<CXXMethodDecl>(FD);
17324 
17325     if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
17326       MD->setInvalidDecl();
17327     else
17328       DefineDefaultedFunction(*this, MD, DefaultLoc);
17329   }
17330 }
17331 
17332 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17333   for (Stmt *SubStmt : S->children()) {
17334     if (!SubStmt)
17335       continue;
17336     if (isa<ReturnStmt>(SubStmt))
17337       Self.Diag(SubStmt->getBeginLoc(),
17338                 diag::err_return_in_constructor_handler);
17339     if (!isa<Expr>(SubStmt))
17340       SearchForReturnInStmt(Self, SubStmt);
17341   }
17342 }
17343 
17344 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17345   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17346     CXXCatchStmt *Handler = TryBlock->getHandler(I);
17347     SearchForReturnInStmt(*this, Handler);
17348   }
17349 }
17350 
17351 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17352                                              const CXXMethodDecl *Old) {
17353   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17354   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17355 
17356   if (OldFT->hasExtParameterInfos()) {
17357     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17358       // A parameter of the overriding method should be annotated with noescape
17359       // if the corresponding parameter of the overridden method is annotated.
17360       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17361           !NewFT->getExtParameterInfo(I).isNoEscape()) {
17362         Diag(New->getParamDecl(I)->getLocation(),
17363              diag::warn_overriding_method_missing_noescape);
17364         Diag(Old->getParamDecl(I)->getLocation(),
17365              diag::note_overridden_marked_noescape);
17366       }
17367   }
17368 
17369   // Virtual overrides must have the same code_seg.
17370   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17371   const auto *NewCSA = New->getAttr<CodeSegAttr>();
17372   if ((NewCSA || OldCSA) &&
17373       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17374     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17375     Diag(Old->getLocation(), diag::note_previous_declaration);
17376     return true;
17377   }
17378 
17379   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17380 
17381   // If the calling conventions match, everything is fine
17382   if (NewCC == OldCC)
17383     return false;
17384 
17385   // If the calling conventions mismatch because the new function is static,
17386   // suppress the calling convention mismatch error; the error about static
17387   // function override (err_static_overrides_virtual from
17388   // Sema::CheckFunctionDeclaration) is more clear.
17389   if (New->getStorageClass() == SC_Static)
17390     return false;
17391 
17392   Diag(New->getLocation(),
17393        diag::err_conflicting_overriding_cc_attributes)
17394     << New->getDeclName() << New->getType() << Old->getType();
17395   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17396   return true;
17397 }
17398 
17399 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17400                                              const CXXMethodDecl *Old) {
17401   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17402   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17403 
17404   if (Context.hasSameType(NewTy, OldTy) ||
17405       NewTy->isDependentType() || OldTy->isDependentType())
17406     return false;
17407 
17408   // Check if the return types are covariant
17409   QualType NewClassTy, OldClassTy;
17410 
17411   /// Both types must be pointers or references to classes.
17412   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17413     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17414       NewClassTy = NewPT->getPointeeType();
17415       OldClassTy = OldPT->getPointeeType();
17416     }
17417   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17418     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17419       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17420         NewClassTy = NewRT->getPointeeType();
17421         OldClassTy = OldRT->getPointeeType();
17422       }
17423     }
17424   }
17425 
17426   // The return types aren't either both pointers or references to a class type.
17427   if (NewClassTy.isNull()) {
17428     Diag(New->getLocation(),
17429          diag::err_different_return_type_for_overriding_virtual_function)
17430         << New->getDeclName() << NewTy << OldTy
17431         << New->getReturnTypeSourceRange();
17432     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17433         << Old->getReturnTypeSourceRange();
17434 
17435     return true;
17436   }
17437 
17438   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17439     // C++14 [class.virtual]p8:
17440     //   If the class type in the covariant return type of D::f differs from
17441     //   that of B::f, the class type in the return type of D::f shall be
17442     //   complete at the point of declaration of D::f or shall be the class
17443     //   type D.
17444     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17445       if (!RT->isBeingDefined() &&
17446           RequireCompleteType(New->getLocation(), NewClassTy,
17447                               diag::err_covariant_return_incomplete,
17448                               New->getDeclName()))
17449         return true;
17450     }
17451 
17452     // Check if the new class derives from the old class.
17453     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17454       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17455           << New->getDeclName() << NewTy << OldTy
17456           << New->getReturnTypeSourceRange();
17457       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17458           << Old->getReturnTypeSourceRange();
17459       return true;
17460     }
17461 
17462     // Check if we the conversion from derived to base is valid.
17463     if (CheckDerivedToBaseConversion(
17464             NewClassTy, OldClassTy,
17465             diag::err_covariant_return_inaccessible_base,
17466             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17467             New->getLocation(), New->getReturnTypeSourceRange(),
17468             New->getDeclName(), nullptr)) {
17469       // FIXME: this note won't trigger for delayed access control
17470       // diagnostics, and it's impossible to get an undelayed error
17471       // here from access control during the original parse because
17472       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17473       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17474           << Old->getReturnTypeSourceRange();
17475       return true;
17476     }
17477   }
17478 
17479   // The qualifiers of the return types must be the same.
17480   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17481     Diag(New->getLocation(),
17482          diag::err_covariant_return_type_different_qualifications)
17483         << New->getDeclName() << NewTy << OldTy
17484         << New->getReturnTypeSourceRange();
17485     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17486         << Old->getReturnTypeSourceRange();
17487     return true;
17488   }
17489 
17490 
17491   // The new class type must have the same or less qualifiers as the old type.
17492   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17493     Diag(New->getLocation(),
17494          diag::err_covariant_return_type_class_type_more_qualified)
17495         << New->getDeclName() << NewTy << OldTy
17496         << New->getReturnTypeSourceRange();
17497     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17498         << Old->getReturnTypeSourceRange();
17499     return true;
17500   }
17501 
17502   return false;
17503 }
17504 
17505 /// Mark the given method pure.
17506 ///
17507 /// \param Method the method to be marked pure.
17508 ///
17509 /// \param InitRange the source range that covers the "0" initializer.
17510 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17511   SourceLocation EndLoc = InitRange.getEnd();
17512   if (EndLoc.isValid())
17513     Method->setRangeEnd(EndLoc);
17514 
17515   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17516     Method->setPure();
17517     return false;
17518   }
17519 
17520   if (!Method->isInvalidDecl())
17521     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17522       << Method->getDeclName() << InitRange;
17523   return true;
17524 }
17525 
17526 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17527   if (D->getFriendObjectKind())
17528     Diag(D->getLocation(), diag::err_pure_friend);
17529   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17530     CheckPureMethod(M, ZeroLoc);
17531   else
17532     Diag(D->getLocation(), diag::err_illegal_initializer);
17533 }
17534 
17535 /// Determine whether the given declaration is a global variable or
17536 /// static data member.
17537 static bool isNonlocalVariable(const Decl *D) {
17538   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17539     return Var->hasGlobalStorage();
17540 
17541   return false;
17542 }
17543 
17544 /// Invoked when we are about to parse an initializer for the declaration
17545 /// 'Dcl'.
17546 ///
17547 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17548 /// static data member of class X, names should be looked up in the scope of
17549 /// class X. If the declaration had a scope specifier, a scope will have
17550 /// been created and passed in for this purpose. Otherwise, S will be null.
17551 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17552   // If there is no declaration, there was an error parsing it.
17553   if (!D || D->isInvalidDecl())
17554     return;
17555 
17556   // We will always have a nested name specifier here, but this declaration
17557   // might not be out of line if the specifier names the current namespace:
17558   //   extern int n;
17559   //   int ::n = 0;
17560   if (S && D->isOutOfLine())
17561     EnterDeclaratorContext(S, D->getDeclContext());
17562 
17563   // If we are parsing the initializer for a static data member, push a
17564   // new expression evaluation context that is associated with this static
17565   // data member.
17566   if (isNonlocalVariable(D))
17567     PushExpressionEvaluationContext(
17568         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17569 }
17570 
17571 /// Invoked after we are finished parsing an initializer for the declaration D.
17572 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17573   // If there is no declaration, there was an error parsing it.
17574   if (!D || D->isInvalidDecl())
17575     return;
17576 
17577   if (isNonlocalVariable(D))
17578     PopExpressionEvaluationContext();
17579 
17580   if (S && D->isOutOfLine())
17581     ExitDeclaratorContext(S);
17582 }
17583 
17584 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17585 /// C++ if/switch/while/for statement.
17586 /// e.g: "if (int x = f()) {...}"
17587 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17588   // C++ 6.4p2:
17589   // The declarator shall not specify a function or an array.
17590   // The type-specifier-seq shall not contain typedef and shall not declare a
17591   // new class or enumeration.
17592   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17593          "Parser allowed 'typedef' as storage class of condition decl.");
17594 
17595   Decl *Dcl = ActOnDeclarator(S, D);
17596   if (!Dcl)
17597     return true;
17598 
17599   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17600     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17601       << D.getSourceRange();
17602     return true;
17603   }
17604 
17605   return Dcl;
17606 }
17607 
17608 void Sema::LoadExternalVTableUses() {
17609   if (!ExternalSource)
17610     return;
17611 
17612   SmallVector<ExternalVTableUse, 4> VTables;
17613   ExternalSource->ReadUsedVTables(VTables);
17614   SmallVector<VTableUse, 4> NewUses;
17615   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17616     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17617       = VTablesUsed.find(VTables[I].Record);
17618     // Even if a definition wasn't required before, it may be required now.
17619     if (Pos != VTablesUsed.end()) {
17620       if (!Pos->second && VTables[I].DefinitionRequired)
17621         Pos->second = true;
17622       continue;
17623     }
17624 
17625     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17626     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17627   }
17628 
17629   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17630 }
17631 
17632 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17633                           bool DefinitionRequired) {
17634   // Ignore any vtable uses in unevaluated operands or for classes that do
17635   // not have a vtable.
17636   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17637       CurContext->isDependentContext() || isUnevaluatedContext())
17638     return;
17639   // Do not mark as used if compiling for the device outside of the target
17640   // region.
17641   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17642       !isInOpenMPDeclareTargetContext() &&
17643       !isInOpenMPTargetExecutionDirective()) {
17644     if (!DefinitionRequired)
17645       MarkVirtualMembersReferenced(Loc, Class);
17646     return;
17647   }
17648 
17649   // Try to insert this class into the map.
17650   LoadExternalVTableUses();
17651   Class = Class->getCanonicalDecl();
17652   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17653     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17654   if (!Pos.second) {
17655     // If we already had an entry, check to see if we are promoting this vtable
17656     // to require a definition. If so, we need to reappend to the VTableUses
17657     // list, since we may have already processed the first entry.
17658     if (DefinitionRequired && !Pos.first->second) {
17659       Pos.first->second = true;
17660     } else {
17661       // Otherwise, we can early exit.
17662       return;
17663     }
17664   } else {
17665     // The Microsoft ABI requires that we perform the destructor body
17666     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17667     // the deleting destructor is emitted with the vtable, not with the
17668     // destructor definition as in the Itanium ABI.
17669     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17670       CXXDestructorDecl *DD = Class->getDestructor();
17671       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17672         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17673           // If this is an out-of-line declaration, marking it referenced will
17674           // not do anything. Manually call CheckDestructor to look up operator
17675           // delete().
17676           ContextRAII SavedContext(*this, DD);
17677           CheckDestructor(DD);
17678         } else {
17679           MarkFunctionReferenced(Loc, Class->getDestructor());
17680         }
17681       }
17682     }
17683   }
17684 
17685   // Local classes need to have their virtual members marked
17686   // immediately. For all other classes, we mark their virtual members
17687   // at the end of the translation unit.
17688   if (Class->isLocalClass())
17689     MarkVirtualMembersReferenced(Loc, Class);
17690   else
17691     VTableUses.push_back(std::make_pair(Class, Loc));
17692 }
17693 
17694 bool Sema::DefineUsedVTables() {
17695   LoadExternalVTableUses();
17696   if (VTableUses.empty())
17697     return false;
17698 
17699   // Note: The VTableUses vector could grow as a result of marking
17700   // the members of a class as "used", so we check the size each
17701   // time through the loop and prefer indices (which are stable) to
17702   // iterators (which are not).
17703   bool DefinedAnything = false;
17704   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17705     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17706     if (!Class)
17707       continue;
17708     TemplateSpecializationKind ClassTSK =
17709         Class->getTemplateSpecializationKind();
17710 
17711     SourceLocation Loc = VTableUses[I].second;
17712 
17713     bool DefineVTable = true;
17714 
17715     // If this class has a key function, but that key function is
17716     // defined in another translation unit, we don't need to emit the
17717     // vtable even though we're using it.
17718     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17719     if (KeyFunction && !KeyFunction->hasBody()) {
17720       // The key function is in another translation unit.
17721       DefineVTable = false;
17722       TemplateSpecializationKind TSK =
17723           KeyFunction->getTemplateSpecializationKind();
17724       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17725              TSK != TSK_ImplicitInstantiation &&
17726              "Instantiations don't have key functions");
17727       (void)TSK;
17728     } else if (!KeyFunction) {
17729       // If we have a class with no key function that is the subject
17730       // of an explicit instantiation declaration, suppress the
17731       // vtable; it will live with the explicit instantiation
17732       // definition.
17733       bool IsExplicitInstantiationDeclaration =
17734           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17735       for (auto R : Class->redecls()) {
17736         TemplateSpecializationKind TSK
17737           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17738         if (TSK == TSK_ExplicitInstantiationDeclaration)
17739           IsExplicitInstantiationDeclaration = true;
17740         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17741           IsExplicitInstantiationDeclaration = false;
17742           break;
17743         }
17744       }
17745 
17746       if (IsExplicitInstantiationDeclaration)
17747         DefineVTable = false;
17748     }
17749 
17750     // The exception specifications for all virtual members may be needed even
17751     // if we are not providing an authoritative form of the vtable in this TU.
17752     // We may choose to emit it available_externally anyway.
17753     if (!DefineVTable) {
17754       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17755       continue;
17756     }
17757 
17758     // Mark all of the virtual members of this class as referenced, so
17759     // that we can build a vtable. Then, tell the AST consumer that a
17760     // vtable for this class is required.
17761     DefinedAnything = true;
17762     MarkVirtualMembersReferenced(Loc, Class);
17763     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17764     if (VTablesUsed[Canonical])
17765       Consumer.HandleVTable(Class);
17766 
17767     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17768     // no key function or the key function is inlined. Don't warn in C++ ABIs
17769     // that lack key functions, since the user won't be able to make one.
17770     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17771         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
17772         ClassTSK != TSK_ExplicitInstantiationDefinition) {
17773       const FunctionDecl *KeyFunctionDef = nullptr;
17774       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17775                            KeyFunctionDef->isInlined()))
17776         Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
17777     }
17778   }
17779   VTableUses.clear();
17780 
17781   return DefinedAnything;
17782 }
17783 
17784 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17785                                                  const CXXRecordDecl *RD) {
17786   for (const auto *I : RD->methods())
17787     if (I->isVirtual() && !I->isPure())
17788       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17789 }
17790 
17791 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17792                                         const CXXRecordDecl *RD,
17793                                         bool ConstexprOnly) {
17794   // Mark all functions which will appear in RD's vtable as used.
17795   CXXFinalOverriderMap FinalOverriders;
17796   RD->getFinalOverriders(FinalOverriders);
17797   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17798                                             E = FinalOverriders.end();
17799        I != E; ++I) {
17800     for (OverridingMethods::const_iterator OI = I->second.begin(),
17801                                            OE = I->second.end();
17802          OI != OE; ++OI) {
17803       assert(OI->second.size() > 0 && "no final overrider");
17804       CXXMethodDecl *Overrider = OI->second.front().Method;
17805 
17806       // C++ [basic.def.odr]p2:
17807       //   [...] A virtual member function is used if it is not pure. [...]
17808       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17809         MarkFunctionReferenced(Loc, Overrider);
17810     }
17811   }
17812 
17813   // Only classes that have virtual bases need a VTT.
17814   if (RD->getNumVBases() == 0)
17815     return;
17816 
17817   for (const auto &I : RD->bases()) {
17818     const auto *Base =
17819         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17820     if (Base->getNumVBases() == 0)
17821       continue;
17822     MarkVirtualMembersReferenced(Loc, Base);
17823   }
17824 }
17825 
17826 /// SetIvarInitializers - This routine builds initialization ASTs for the
17827 /// Objective-C implementation whose ivars need be initialized.
17828 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17829   if (!getLangOpts().CPlusPlus)
17830     return;
17831   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17832     SmallVector<ObjCIvarDecl*, 8> ivars;
17833     CollectIvarsToConstructOrDestruct(OID, ivars);
17834     if (ivars.empty())
17835       return;
17836     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17837     for (unsigned i = 0; i < ivars.size(); i++) {
17838       FieldDecl *Field = ivars[i];
17839       if (Field->isInvalidDecl())
17840         continue;
17841 
17842       CXXCtorInitializer *Member;
17843       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17844       InitializationKind InitKind =
17845         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17846 
17847       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17848       ExprResult MemberInit =
17849         InitSeq.Perform(*this, InitEntity, InitKind, None);
17850       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17851       // Note, MemberInit could actually come back empty if no initialization
17852       // is required (e.g., because it would call a trivial default constructor)
17853       if (!MemberInit.get() || MemberInit.isInvalid())
17854         continue;
17855 
17856       Member =
17857         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17858                                          SourceLocation(),
17859                                          MemberInit.getAs<Expr>(),
17860                                          SourceLocation());
17861       AllToInit.push_back(Member);
17862 
17863       // Be sure that the destructor is accessible and is marked as referenced.
17864       if (const RecordType *RecordTy =
17865               Context.getBaseElementType(Field->getType())
17866                   ->getAs<RecordType>()) {
17867         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17868         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17869           MarkFunctionReferenced(Field->getLocation(), Destructor);
17870           CheckDestructorAccess(Field->getLocation(), Destructor,
17871                             PDiag(diag::err_access_dtor_ivar)
17872                               << Context.getBaseElementType(Field->getType()));
17873         }
17874       }
17875     }
17876     ObjCImplementation->setIvarInitializers(Context,
17877                                             AllToInit.data(), AllToInit.size());
17878   }
17879 }
17880 
17881 static
17882 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17883                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17884                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17885                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17886                            Sema &S) {
17887   if (Ctor->isInvalidDecl())
17888     return;
17889 
17890   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17891 
17892   // Target may not be determinable yet, for instance if this is a dependent
17893   // call in an uninstantiated template.
17894   if (Target) {
17895     const FunctionDecl *FNTarget = nullptr;
17896     (void)Target->hasBody(FNTarget);
17897     Target = const_cast<CXXConstructorDecl*>(
17898       cast_or_null<CXXConstructorDecl>(FNTarget));
17899   }
17900 
17901   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17902                      // Avoid dereferencing a null pointer here.
17903                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17904 
17905   if (!Current.insert(Canonical).second)
17906     return;
17907 
17908   // We know that beyond here, we aren't chaining into a cycle.
17909   if (!Target || !Target->isDelegatingConstructor() ||
17910       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17911     Valid.insert(Current.begin(), Current.end());
17912     Current.clear();
17913   // We've hit a cycle.
17914   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17915              Current.count(TCanonical)) {
17916     // If we haven't diagnosed this cycle yet, do so now.
17917     if (!Invalid.count(TCanonical)) {
17918       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17919              diag::warn_delegating_ctor_cycle)
17920         << Ctor;
17921 
17922       // Don't add a note for a function delegating directly to itself.
17923       if (TCanonical != Canonical)
17924         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17925 
17926       CXXConstructorDecl *C = Target;
17927       while (C->getCanonicalDecl() != Canonical) {
17928         const FunctionDecl *FNTarget = nullptr;
17929         (void)C->getTargetConstructor()->hasBody(FNTarget);
17930         assert(FNTarget && "Ctor cycle through bodiless function");
17931 
17932         C = const_cast<CXXConstructorDecl*>(
17933           cast<CXXConstructorDecl>(FNTarget));
17934         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17935       }
17936     }
17937 
17938     Invalid.insert(Current.begin(), Current.end());
17939     Current.clear();
17940   } else {
17941     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17942   }
17943 }
17944 
17945 
17946 void Sema::CheckDelegatingCtorCycles() {
17947   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17948 
17949   for (DelegatingCtorDeclsType::iterator
17950          I = DelegatingCtorDecls.begin(ExternalSource),
17951          E = DelegatingCtorDecls.end();
17952        I != E; ++I)
17953     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17954 
17955   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17956     (*CI)->setInvalidDecl();
17957 }
17958 
17959 namespace {
17960   /// AST visitor that finds references to the 'this' expression.
17961   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17962     Sema &S;
17963 
17964   public:
17965     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17966 
17967     bool VisitCXXThisExpr(CXXThisExpr *E) {
17968       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17969         << E->isImplicit();
17970       return false;
17971     }
17972   };
17973 }
17974 
17975 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17976   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17977   if (!TSInfo)
17978     return false;
17979 
17980   TypeLoc TL = TSInfo->getTypeLoc();
17981   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17982   if (!ProtoTL)
17983     return false;
17984 
17985   // C++11 [expr.prim.general]p3:
17986   //   [The expression this] shall not appear before the optional
17987   //   cv-qualifier-seq and it shall not appear within the declaration of a
17988   //   static member function (although its type and value category are defined
17989   //   within a static member function as they are within a non-static member
17990   //   function). [ Note: this is because declaration matching does not occur
17991   //  until the complete declarator is known. - end note ]
17992   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17993   FindCXXThisExpr Finder(*this);
17994 
17995   // If the return type came after the cv-qualifier-seq, check it now.
17996   if (Proto->hasTrailingReturn() &&
17997       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17998     return true;
17999 
18000   // Check the exception specification.
18001   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18002     return true;
18003 
18004   // Check the trailing requires clause
18005   if (Expr *E = Method->getTrailingRequiresClause())
18006     if (!Finder.TraverseStmt(E))
18007       return true;
18008 
18009   return checkThisInStaticMemberFunctionAttributes(Method);
18010 }
18011 
18012 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18013   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18014   if (!TSInfo)
18015     return false;
18016 
18017   TypeLoc TL = TSInfo->getTypeLoc();
18018   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18019   if (!ProtoTL)
18020     return false;
18021 
18022   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18023   FindCXXThisExpr Finder(*this);
18024 
18025   switch (Proto->getExceptionSpecType()) {
18026   case EST_Unparsed:
18027   case EST_Uninstantiated:
18028   case EST_Unevaluated:
18029   case EST_BasicNoexcept:
18030   case EST_NoThrow:
18031   case EST_DynamicNone:
18032   case EST_MSAny:
18033   case EST_None:
18034     break;
18035 
18036   case EST_DependentNoexcept:
18037   case EST_NoexceptFalse:
18038   case EST_NoexceptTrue:
18039     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18040       return true;
18041     LLVM_FALLTHROUGH;
18042 
18043   case EST_Dynamic:
18044     for (const auto &E : Proto->exceptions()) {
18045       if (!Finder.TraverseType(E))
18046         return true;
18047     }
18048     break;
18049   }
18050 
18051   return false;
18052 }
18053 
18054 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
18055   FindCXXThisExpr Finder(*this);
18056 
18057   // Check attributes.
18058   for (const auto *A : Method->attrs()) {
18059     // FIXME: This should be emitted by tblgen.
18060     Expr *Arg = nullptr;
18061     ArrayRef<Expr *> Args;
18062     if (const auto *G = dyn_cast<GuardedByAttr>(A))
18063       Arg = G->getArg();
18064     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18065       Arg = G->getArg();
18066     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18067       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
18068     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18069       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
18070     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18071       Arg = ETLF->getSuccessValue();
18072       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
18073     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18074       Arg = STLF->getSuccessValue();
18075       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
18076     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18077       Arg = LR->getArg();
18078     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18079       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
18080     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18081       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18082     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18083       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18084     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18085       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18086     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18087       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18088 
18089     if (Arg && !Finder.TraverseStmt(Arg))
18090       return true;
18091 
18092     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18093       if (!Finder.TraverseStmt(Args[I]))
18094         return true;
18095     }
18096   }
18097 
18098   return false;
18099 }
18100 
18101 void Sema::checkExceptionSpecification(
18102     bool IsTopLevel, ExceptionSpecificationType EST,
18103     ArrayRef<ParsedType> DynamicExceptions,
18104     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18105     SmallVectorImpl<QualType> &Exceptions,
18106     FunctionProtoType::ExceptionSpecInfo &ESI) {
18107   Exceptions.clear();
18108   ESI.Type = EST;
18109   if (EST == EST_Dynamic) {
18110     Exceptions.reserve(DynamicExceptions.size());
18111     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18112       // FIXME: Preserve type source info.
18113       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18114 
18115       if (IsTopLevel) {
18116         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
18117         collectUnexpandedParameterPacks(ET, Unexpanded);
18118         if (!Unexpanded.empty()) {
18119           DiagnoseUnexpandedParameterPacks(
18120               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18121               Unexpanded);
18122           continue;
18123         }
18124       }
18125 
18126       // Check that the type is valid for an exception spec, and
18127       // drop it if not.
18128       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18129         Exceptions.push_back(ET);
18130     }
18131     ESI.Exceptions = Exceptions;
18132     return;
18133   }
18134 
18135   if (isComputedNoexcept(EST)) {
18136     assert((NoexceptExpr->isTypeDependent() ||
18137             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18138             Context.BoolTy) &&
18139            "Parser should have made sure that the expression is boolean");
18140     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18141       ESI.Type = EST_BasicNoexcept;
18142       return;
18143     }
18144 
18145     ESI.NoexceptExpr = NoexceptExpr;
18146     return;
18147   }
18148 }
18149 
18150 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
18151              ExceptionSpecificationType EST,
18152              SourceRange SpecificationRange,
18153              ArrayRef<ParsedType> DynamicExceptions,
18154              ArrayRef<SourceRange> DynamicExceptionRanges,
18155              Expr *NoexceptExpr) {
18156   if (!MethodD)
18157     return;
18158 
18159   // Dig out the method we're referring to.
18160   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18161     MethodD = FunTmpl->getTemplatedDecl();
18162 
18163   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18164   if (!Method)
18165     return;
18166 
18167   // Check the exception specification.
18168   llvm::SmallVector<QualType, 4> Exceptions;
18169   FunctionProtoType::ExceptionSpecInfo ESI;
18170   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18171                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
18172                               ESI);
18173 
18174   // Update the exception specification on the function type.
18175   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18176 
18177   if (Method->isStatic())
18178     checkThisInStaticMemberFunctionExceptionSpec(Method);
18179 
18180   if (Method->isVirtual()) {
18181     // Check overrides, which we previously had to delay.
18182     for (const CXXMethodDecl *O : Method->overridden_methods())
18183       CheckOverridingFunctionExceptionSpec(Method, O);
18184   }
18185 }
18186 
18187 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18188 ///
18189 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18190                                        SourceLocation DeclStart, Declarator &D,
18191                                        Expr *BitWidth,
18192                                        InClassInitStyle InitStyle,
18193                                        AccessSpecifier AS,
18194                                        const ParsedAttr &MSPropertyAttr) {
18195   IdentifierInfo *II = D.getIdentifier();
18196   if (!II) {
18197     Diag(DeclStart, diag::err_anonymous_property);
18198     return nullptr;
18199   }
18200   SourceLocation Loc = D.getIdentifierLoc();
18201 
18202   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18203   QualType T = TInfo->getType();
18204   if (getLangOpts().CPlusPlus) {
18205     CheckExtraCXXDefaultArguments(D);
18206 
18207     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18208                                         UPPC_DataMemberType)) {
18209       D.setInvalidType();
18210       T = Context.IntTy;
18211       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18212     }
18213   }
18214 
18215   DiagnoseFunctionSpecifiers(D.getDeclSpec());
18216 
18217   if (D.getDeclSpec().isInlineSpecified())
18218     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18219         << getLangOpts().CPlusPlus17;
18220   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18221     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18222          diag::err_invalid_thread)
18223       << DeclSpec::getSpecifierName(TSCS);
18224 
18225   // Check to see if this name was declared as a member previously
18226   NamedDecl *PrevDecl = nullptr;
18227   LookupResult Previous(*this, II, Loc, LookupMemberName,
18228                         ForVisibleRedeclaration);
18229   LookupName(Previous, S);
18230   switch (Previous.getResultKind()) {
18231   case LookupResult::Found:
18232   case LookupResult::FoundUnresolvedValue:
18233     PrevDecl = Previous.getAsSingle<NamedDecl>();
18234     break;
18235 
18236   case LookupResult::FoundOverloaded:
18237     PrevDecl = Previous.getRepresentativeDecl();
18238     break;
18239 
18240   case LookupResult::NotFound:
18241   case LookupResult::NotFoundInCurrentInstantiation:
18242   case LookupResult::Ambiguous:
18243     break;
18244   }
18245 
18246   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18247     // Maybe we will complain about the shadowed template parameter.
18248     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18249     // Just pretend that we didn't see the previous declaration.
18250     PrevDecl = nullptr;
18251   }
18252 
18253   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18254     PrevDecl = nullptr;
18255 
18256   SourceLocation TSSL = D.getBeginLoc();
18257   MSPropertyDecl *NewPD =
18258       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18259                              MSPropertyAttr.getPropertyDataGetter(),
18260                              MSPropertyAttr.getPropertyDataSetter());
18261   ProcessDeclAttributes(TUScope, NewPD, D);
18262   NewPD->setAccess(AS);
18263 
18264   if (NewPD->isInvalidDecl())
18265     Record->setInvalidDecl();
18266 
18267   if (D.getDeclSpec().isModulePrivateSpecified())
18268     NewPD->setModulePrivate();
18269 
18270   if (NewPD->isInvalidDecl() && PrevDecl) {
18271     // Don't introduce NewFD into scope; there's already something
18272     // with the same name in the same scope.
18273   } else if (II) {
18274     PushOnScopeChains(NewPD, S);
18275   } else
18276     Record->addDecl(NewPD);
18277 
18278   return NewPD;
18279 }
18280 
18281 void Sema::ActOnStartFunctionDeclarationDeclarator(
18282     Declarator &Declarator, unsigned TemplateParameterDepth) {
18283   auto &Info = InventedParameterInfos.emplace_back();
18284   TemplateParameterList *ExplicitParams = nullptr;
18285   ArrayRef<TemplateParameterList *> ExplicitLists =
18286       Declarator.getTemplateParameterLists();
18287   if (!ExplicitLists.empty()) {
18288     bool IsMemberSpecialization, IsInvalid;
18289     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18290         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18291         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18292         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18293         /*SuppressDiagnostic=*/true);
18294   }
18295   if (ExplicitParams) {
18296     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18297     llvm::append_range(Info.TemplateParams, *ExplicitParams);
18298     Info.NumExplicitTemplateParams = ExplicitParams->size();
18299   } else {
18300     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18301     Info.NumExplicitTemplateParams = 0;
18302   }
18303 }
18304 
18305 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18306   auto &FSI = InventedParameterInfos.back();
18307   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18308     if (FSI.NumExplicitTemplateParams != 0) {
18309       TemplateParameterList *ExplicitParams =
18310           Declarator.getTemplateParameterLists().back();
18311       Declarator.setInventedTemplateParameterList(
18312           TemplateParameterList::Create(
18313               Context, ExplicitParams->getTemplateLoc(),
18314               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18315               ExplicitParams->getRAngleLoc(),
18316               ExplicitParams->getRequiresClause()));
18317     } else {
18318       Declarator.setInventedTemplateParameterList(
18319           TemplateParameterList::Create(
18320               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18321               SourceLocation(), /*RequiresClause=*/nullptr));
18322     }
18323   }
18324   InventedParameterInfos.pop_back();
18325 }
18326