1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/AttributeCommonInfo.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/CXXFieldCollector.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Initialization.h"
36 #include "clang/Sema/Lookup.h"
37 #include "clang/Sema/ParsedTemplate.h"
38 #include "clang/Sema/Scope.h"
39 #include "clang/Sema/ScopeInfo.h"
40 #include "clang/Sema/SemaInternal.h"
41 #include "clang/Sema/Template.h"
42 #include "llvm/ADT/ScopeExit.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include <map>
47 #include <set>
48 
49 using namespace clang;
50 
51 //===----------------------------------------------------------------------===//
52 // CheckDefaultArgumentVisitor
53 //===----------------------------------------------------------------------===//
54 
55 namespace {
56 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
57 /// the default argument of a parameter to determine whether it
58 /// contains any ill-formed subexpressions. For example, this will
59 /// diagnose the use of local variables or parameters within the
60 /// default argument expression.
61 class CheckDefaultArgumentVisitor
62     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
63   Sema &S;
64   const Expr *DefaultArg;
65 
66 public:
67   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
68       : S(S), DefaultArg(DefaultArg) {}
69 
70   bool VisitExpr(const Expr *Node);
71   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
72   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
73   bool VisitLambdaExpr(const LambdaExpr *Lambda);
74   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
75 };
76 
77 /// VisitExpr - Visit all of the children of this expression.
78 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
79   bool IsInvalid = false;
80   for (const Stmt *SubStmt : Node->children())
81     IsInvalid |= Visit(SubStmt);
82   return IsInvalid;
83 }
84 
85 /// VisitDeclRefExpr - Visit a reference to a declaration, to
86 /// determine whether this declaration can be used in the default
87 /// argument expression.
88 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
89   const NamedDecl *Decl = DRE->getDecl();
90   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
91     // C++ [dcl.fct.default]p9:
92     //   [...] parameters of a function shall not be used in default
93     //   argument expressions, even if they are not evaluated. [...]
94     //
95     // C++17 [dcl.fct.default]p9 (by CWG 2082):
96     //   [...] A parameter shall not appear as a potentially-evaluated
97     //   expression in a default argument. [...]
98     //
99     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
100       return S.Diag(DRE->getBeginLoc(),
101                     diag::err_param_default_argument_references_param)
102              << Param->getDeclName() << DefaultArg->getSourceRange();
103   } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
104     // C++ [dcl.fct.default]p7:
105     //   Local variables shall not be used in default argument
106     //   expressions.
107     //
108     // C++17 [dcl.fct.default]p7 (by CWG 2082):
109     //   A local variable shall not appear as a potentially-evaluated
110     //   expression in a default argument.
111     //
112     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
113     //   Note: A local variable cannot be odr-used (6.3) in a default argument.
114     //
115     if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
116       return S.Diag(DRE->getBeginLoc(),
117                     diag::err_param_default_argument_references_local)
118              << VDecl->getDeclName() << DefaultArg->getSourceRange();
119   }
120 
121   return false;
122 }
123 
124 /// VisitCXXThisExpr - Visit a C++ "this" expression.
125 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
126   // C++ [dcl.fct.default]p8:
127   //   The keyword this shall not be used in a default argument of a
128   //   member function.
129   return S.Diag(ThisE->getBeginLoc(),
130                 diag::err_param_default_argument_references_this)
131          << ThisE->getSourceRange();
132 }
133 
134 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
135     const PseudoObjectExpr *POE) {
136   bool Invalid = false;
137   for (const Expr *E : POE->semantics()) {
138     // Look through bindings.
139     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
140       E = OVE->getSourceExpr();
141       assert(E && "pseudo-object binding without source expression?");
142     }
143 
144     Invalid |= Visit(E);
145   }
146   return Invalid;
147 }
148 
149 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
150   // C++11 [expr.lambda.prim]p13:
151   //   A lambda-expression appearing in a default argument shall not
152   //   implicitly or explicitly capture any entity.
153   if (Lambda->capture_begin() == Lambda->capture_end())
154     return false;
155 
156   return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
157 }
158 } // namespace
159 
160 void
161 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
162                                                  const CXXMethodDecl *Method) {
163   // If we have an MSAny spec already, don't bother.
164   if (!Method || ComputedEST == EST_MSAny)
165     return;
166 
167   const FunctionProtoType *Proto
168     = Method->getType()->getAs<FunctionProtoType>();
169   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
170   if (!Proto)
171     return;
172 
173   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
174 
175   // If we have a throw-all spec at this point, ignore the function.
176   if (ComputedEST == EST_None)
177     return;
178 
179   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
180     EST = EST_BasicNoexcept;
181 
182   switch (EST) {
183   case EST_Unparsed:
184   case EST_Uninstantiated:
185   case EST_Unevaluated:
186     llvm_unreachable("should not see unresolved exception specs here");
187 
188   // If this function can throw any exceptions, make a note of that.
189   case EST_MSAny:
190   case EST_None:
191     // FIXME: Whichever we see last of MSAny and None determines our result.
192     // We should make a consistent, order-independent choice here.
193     ClearExceptions();
194     ComputedEST = EST;
195     return;
196   case EST_NoexceptFalse:
197     ClearExceptions();
198     ComputedEST = EST_None;
199     return;
200   // FIXME: If the call to this decl is using any of its default arguments, we
201   // need to search them for potentially-throwing calls.
202   // If this function has a basic noexcept, it doesn't affect the outcome.
203   case EST_BasicNoexcept:
204   case EST_NoexceptTrue:
205   case EST_NoThrow:
206     return;
207   // If we're still at noexcept(true) and there's a throw() callee,
208   // change to that specification.
209   case EST_DynamicNone:
210     if (ComputedEST == EST_BasicNoexcept)
211       ComputedEST = EST_DynamicNone;
212     return;
213   case EST_DependentNoexcept:
214     llvm_unreachable(
215         "should not generate implicit declarations for dependent cases");
216   case EST_Dynamic:
217     break;
218   }
219   assert(EST == EST_Dynamic && "EST case not considered earlier.");
220   assert(ComputedEST != EST_None &&
221          "Shouldn't collect exceptions when throw-all is guaranteed.");
222   ComputedEST = EST_Dynamic;
223   // Record the exceptions in this function's exception specification.
224   for (const auto &E : Proto->exceptions())
225     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
226       Exceptions.push_back(E);
227 }
228 
229 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
230   if (!S || ComputedEST == EST_MSAny)
231     return;
232 
233   // FIXME:
234   //
235   // C++0x [except.spec]p14:
236   //   [An] implicit exception-specification specifies the type-id T if and
237   // only if T is allowed by the exception-specification of a function directly
238   // invoked by f's implicit definition; f shall allow all exceptions if any
239   // function it directly invokes allows all exceptions, and f shall allow no
240   // exceptions if every function it directly invokes allows no exceptions.
241   //
242   // Note in particular that if an implicit exception-specification is generated
243   // for a function containing a throw-expression, that specification can still
244   // be noexcept(true).
245   //
246   // Note also that 'directly invoked' is not defined in the standard, and there
247   // is no indication that we should only consider potentially-evaluated calls.
248   //
249   // Ultimately we should implement the intent of the standard: the exception
250   // specification should be the set of exceptions which can be thrown by the
251   // implicit definition. For now, we assume that any non-nothrow expression can
252   // throw any exception.
253 
254   if (Self->canThrow(S))
255     ComputedEST = EST_None;
256 }
257 
258 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
259                                              SourceLocation EqualLoc) {
260   if (RequireCompleteType(Param->getLocation(), Param->getType(),
261                           diag::err_typecheck_decl_incomplete_type))
262     return true;
263 
264   // C++ [dcl.fct.default]p5
265   //   A default argument expression is implicitly converted (clause
266   //   4) to the parameter type. The default argument expression has
267   //   the same semantic constraints as the initializer expression in
268   //   a declaration of a variable of the parameter type, using the
269   //   copy-initialization semantics (8.5).
270   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
271                                                                     Param);
272   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
273                                                            EqualLoc);
274   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276   if (Result.isInvalid())
277     return true;
278   Arg = Result.getAs<Expr>();
279 
280   CheckCompletedExpr(Arg, EqualLoc);
281   Arg = MaybeCreateExprWithCleanups(Arg);
282 
283   return Arg;
284 }
285 
286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
287                                    SourceLocation EqualLoc) {
288   // Add the default argument to the parameter
289   Param->setDefaultArg(Arg);
290 
291   // We have already instantiated this parameter; provide each of the
292   // instantiations with the uninstantiated default argument.
293   UnparsedDefaultArgInstantiationsMap::iterator InstPos
294     = UnparsedDefaultArgInstantiations.find(Param);
295   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
297       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
298 
299     // We're done tracking this parameter's instantiations.
300     UnparsedDefaultArgInstantiations.erase(InstPos);
301   }
302 }
303 
304 /// ActOnParamDefaultArgument - Check whether the default argument
305 /// provided for a function parameter is well-formed. If so, attach it
306 /// to the parameter declaration.
307 void
308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
309                                 Expr *DefaultArg) {
310   if (!param || !DefaultArg)
311     return;
312 
313   ParmVarDecl *Param = cast<ParmVarDecl>(param);
314   UnparsedDefaultArgLocs.erase(Param);
315 
316   auto Fail = [&] {
317     Param->setInvalidDecl();
318     Param->setDefaultArg(new (Context) OpaqueValueExpr(
319         EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
320   };
321 
322   // Default arguments are only permitted in C++
323   if (!getLangOpts().CPlusPlus) {
324     Diag(EqualLoc, diag::err_param_default_argument)
325       << DefaultArg->getSourceRange();
326     return Fail();
327   }
328 
329   // Check for unexpanded parameter packs.
330   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
331     return Fail();
332   }
333 
334   // C++11 [dcl.fct.default]p3
335   //   A default argument expression [...] shall not be specified for a
336   //   parameter pack.
337   if (Param->isParameterPack()) {
338     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339         << DefaultArg->getSourceRange();
340     // Recover by discarding the default argument.
341     Param->setDefaultArg(nullptr);
342     return;
343   }
344 
345   ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346   if (Result.isInvalid())
347     return Fail();
348 
349   DefaultArg = Result.getAs<Expr>();
350 
351   // Check that the default argument is well-formed
352   CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353   if (DefaultArgChecker.Visit(DefaultArg))
354     return Fail();
355 
356   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
357 }
358 
359 /// ActOnParamUnparsedDefaultArgument - We've seen a default
360 /// argument for a function parameter, but we can't parse it yet
361 /// because we're inside a class definition. Note that this default
362 /// argument will be parsed later.
363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
364                                              SourceLocation EqualLoc,
365                                              SourceLocation ArgLoc) {
366   if (!param)
367     return;
368 
369   ParmVarDecl *Param = cast<ParmVarDecl>(param);
370   Param->setUnparsedDefaultArg();
371   UnparsedDefaultArgLocs[Param] = ArgLoc;
372 }
373 
374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375 /// the default argument for the parameter param failed.
376 void Sema::ActOnParamDefaultArgumentError(Decl *param,
377                                           SourceLocation EqualLoc) {
378   if (!param)
379     return;
380 
381   ParmVarDecl *Param = cast<ParmVarDecl>(param);
382   Param->setInvalidDecl();
383   UnparsedDefaultArgLocs.erase(Param);
384   Param->setDefaultArg(new (Context) OpaqueValueExpr(
385       EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
386 }
387 
388 /// CheckExtraCXXDefaultArguments - Check for any extra default
389 /// arguments in the declarator, which is not a function declaration
390 /// or definition and therefore is not permitted to have default
391 /// arguments. This routine should be invoked for every declarator
392 /// that is not a function declaration or definition.
393 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
394   // C++ [dcl.fct.default]p3
395   //   A default argument expression shall be specified only in the
396   //   parameter-declaration-clause of a function declaration or in a
397   //   template-parameter (14.1). It shall not be specified for a
398   //   parameter pack. If it is specified in a
399   //   parameter-declaration-clause, it shall not occur within a
400   //   declarator or abstract-declarator of a parameter-declaration.
401   bool MightBeFunction = D.isFunctionDeclarationContext();
402   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
403     DeclaratorChunk &chunk = D.getTypeObject(i);
404     if (chunk.Kind == DeclaratorChunk::Function) {
405       if (MightBeFunction) {
406         // This is a function declaration. It can have default arguments, but
407         // keep looking in case its return type is a function type with default
408         // arguments.
409         MightBeFunction = false;
410         continue;
411       }
412       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
413            ++argIdx) {
414         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
415         if (Param->hasUnparsedDefaultArg()) {
416           std::unique_ptr<CachedTokens> Toks =
417               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
418           SourceRange SR;
419           if (Toks->size() > 1)
420             SR = SourceRange((*Toks)[1].getLocation(),
421                              Toks->back().getLocation());
422           else
423             SR = UnparsedDefaultArgLocs[Param];
424           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
425             << SR;
426         } else if (Param->getDefaultArg()) {
427           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
428             << Param->getDefaultArg()->getSourceRange();
429           Param->setDefaultArg(nullptr);
430         }
431       }
432     } else if (chunk.Kind != DeclaratorChunk::Paren) {
433       MightBeFunction = false;
434     }
435   }
436 }
437 
438 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
439   return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
440     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
441   });
442 }
443 
444 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
445 /// function, once we already know that they have the same
446 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
447 /// error, false otherwise.
448 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
449                                 Scope *S) {
450   bool Invalid = false;
451 
452   // The declaration context corresponding to the scope is the semantic
453   // parent, unless this is a local function declaration, in which case
454   // it is that surrounding function.
455   DeclContext *ScopeDC = New->isLocalExternDecl()
456                              ? New->getLexicalDeclContext()
457                              : New->getDeclContext();
458 
459   // Find the previous declaration for the purpose of default arguments.
460   FunctionDecl *PrevForDefaultArgs = Old;
461   for (/**/; PrevForDefaultArgs;
462        // Don't bother looking back past the latest decl if this is a local
463        // extern declaration; nothing else could work.
464        PrevForDefaultArgs = New->isLocalExternDecl()
465                                 ? nullptr
466                                 : PrevForDefaultArgs->getPreviousDecl()) {
467     // Ignore hidden declarations.
468     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
469       continue;
470 
471     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
472         !New->isCXXClassMember()) {
473       // Ignore default arguments of old decl if they are not in
474       // the same scope and this is not an out-of-line definition of
475       // a member function.
476       continue;
477     }
478 
479     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
480       // If only one of these is a local function declaration, then they are
481       // declared in different scopes, even though isDeclInScope may think
482       // they're in the same scope. (If both are local, the scope check is
483       // sufficient, and if neither is local, then they are in the same scope.)
484       continue;
485     }
486 
487     // We found the right previous declaration.
488     break;
489   }
490 
491   // C++ [dcl.fct.default]p4:
492   //   For non-template functions, default arguments can be added in
493   //   later declarations of a function in the same
494   //   scope. Declarations in different scopes have completely
495   //   distinct sets of default arguments. That is, declarations in
496   //   inner scopes do not acquire default arguments from
497   //   declarations in outer scopes, and vice versa. In a given
498   //   function declaration, all parameters subsequent to a
499   //   parameter with a default argument shall have default
500   //   arguments supplied in this or previous declarations. A
501   //   default argument shall not be redefined by a later
502   //   declaration (not even to the same value).
503   //
504   // C++ [dcl.fct.default]p6:
505   //   Except for member functions of class templates, the default arguments
506   //   in a member function definition that appears outside of the class
507   //   definition are added to the set of default arguments provided by the
508   //   member function declaration in the class definition.
509   for (unsigned p = 0, NumParams = PrevForDefaultArgs
510                                        ? PrevForDefaultArgs->getNumParams()
511                                        : 0;
512        p < NumParams; ++p) {
513     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
514     ParmVarDecl *NewParam = New->getParamDecl(p);
515 
516     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
517     bool NewParamHasDfl = NewParam->hasDefaultArg();
518 
519     if (OldParamHasDfl && NewParamHasDfl) {
520       unsigned DiagDefaultParamID =
521         diag::err_param_default_argument_redefinition;
522 
523       // MSVC accepts that default parameters be redefined for member functions
524       // of template class. The new default parameter's value is ignored.
525       Invalid = true;
526       if (getLangOpts().MicrosoftExt) {
527         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
528         if (MD && MD->getParent()->getDescribedClassTemplate()) {
529           // Merge the old default argument into the new parameter.
530           NewParam->setHasInheritedDefaultArg();
531           if (OldParam->hasUninstantiatedDefaultArg())
532             NewParam->setUninstantiatedDefaultArg(
533                                       OldParam->getUninstantiatedDefaultArg());
534           else
535             NewParam->setDefaultArg(OldParam->getInit());
536           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
537           Invalid = false;
538         }
539       }
540 
541       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
542       // hint here. Alternatively, we could walk the type-source information
543       // for NewParam to find the last source location in the type... but it
544       // isn't worth the effort right now. This is the kind of test case that
545       // is hard to get right:
546       //   int f(int);
547       //   void g(int (*fp)(int) = f);
548       //   void g(int (*fp)(int) = &f);
549       Diag(NewParam->getLocation(), DiagDefaultParamID)
550         << NewParam->getDefaultArgRange();
551 
552       // Look for the function declaration where the default argument was
553       // actually written, which may be a declaration prior to Old.
554       for (auto Older = PrevForDefaultArgs;
555            OldParam->hasInheritedDefaultArg(); /**/) {
556         Older = Older->getPreviousDecl();
557         OldParam = Older->getParamDecl(p);
558       }
559 
560       Diag(OldParam->getLocation(), diag::note_previous_definition)
561         << OldParam->getDefaultArgRange();
562     } else if (OldParamHasDfl) {
563       // Merge the old default argument into the new parameter unless the new
564       // function is a friend declaration in a template class. In the latter
565       // case the default arguments will be inherited when the friend
566       // declaration will be instantiated.
567       if (New->getFriendObjectKind() == Decl::FOK_None ||
568           !New->getLexicalDeclContext()->isDependentContext()) {
569         // It's important to use getInit() here;  getDefaultArg()
570         // strips off any top-level ExprWithCleanups.
571         NewParam->setHasInheritedDefaultArg();
572         if (OldParam->hasUnparsedDefaultArg())
573           NewParam->setUnparsedDefaultArg();
574         else if (OldParam->hasUninstantiatedDefaultArg())
575           NewParam->setUninstantiatedDefaultArg(
576                                        OldParam->getUninstantiatedDefaultArg());
577         else
578           NewParam->setDefaultArg(OldParam->getInit());
579       }
580     } else if (NewParamHasDfl) {
581       if (New->getDescribedFunctionTemplate()) {
582         // Paragraph 4, quoted above, only applies to non-template functions.
583         Diag(NewParam->getLocation(),
584              diag::err_param_default_argument_template_redecl)
585           << NewParam->getDefaultArgRange();
586         Diag(PrevForDefaultArgs->getLocation(),
587              diag::note_template_prev_declaration)
588             << false;
589       } else if (New->getTemplateSpecializationKind()
590                    != TSK_ImplicitInstantiation &&
591                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
592         // C++ [temp.expr.spec]p21:
593         //   Default function arguments shall not be specified in a declaration
594         //   or a definition for one of the following explicit specializations:
595         //     - the explicit specialization of a function template;
596         //     - the explicit specialization of a member function template;
597         //     - the explicit specialization of a member function of a class
598         //       template where the class template specialization to which the
599         //       member function specialization belongs is implicitly
600         //       instantiated.
601         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
602           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
603           << New->getDeclName()
604           << NewParam->getDefaultArgRange();
605       } else if (New->getDeclContext()->isDependentContext()) {
606         // C++ [dcl.fct.default]p6 (DR217):
607         //   Default arguments for a member function of a class template shall
608         //   be specified on the initial declaration of the member function
609         //   within the class template.
610         //
611         // Reading the tea leaves a bit in DR217 and its reference to DR205
612         // leads me to the conclusion that one cannot add default function
613         // arguments for an out-of-line definition of a member function of a
614         // dependent type.
615         int WhichKind = 2;
616         if (CXXRecordDecl *Record
617               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
618           if (Record->getDescribedClassTemplate())
619             WhichKind = 0;
620           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
621             WhichKind = 1;
622           else
623             WhichKind = 2;
624         }
625 
626         Diag(NewParam->getLocation(),
627              diag::err_param_default_argument_member_template_redecl)
628           << WhichKind
629           << NewParam->getDefaultArgRange();
630       }
631     }
632   }
633 
634   // DR1344: If a default argument is added outside a class definition and that
635   // default argument makes the function a special member function, the program
636   // is ill-formed. This can only happen for constructors.
637   if (isa<CXXConstructorDecl>(New) &&
638       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
639     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
640                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
641     if (NewSM != OldSM) {
642       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
643       assert(NewParam->hasDefaultArg());
644       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
645         << NewParam->getDefaultArgRange() << NewSM;
646       Diag(Old->getLocation(), diag::note_previous_declaration);
647     }
648   }
649 
650   const FunctionDecl *Def;
651   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
652   // template has a constexpr specifier then all its declarations shall
653   // contain the constexpr specifier.
654   if (New->getConstexprKind() != Old->getConstexprKind()) {
655     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
656         << New << static_cast<int>(New->getConstexprKind())
657         << static_cast<int>(Old->getConstexprKind());
658     Diag(Old->getLocation(), diag::note_previous_declaration);
659     Invalid = true;
660   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
661              Old->isDefined(Def) &&
662              // If a friend function is inlined but does not have 'inline'
663              // specifier, it is a definition. Do not report attribute conflict
664              // in this case, redefinition will be diagnosed later.
665              (New->isInlineSpecified() ||
666               New->getFriendObjectKind() == Decl::FOK_None)) {
667     // C++11 [dcl.fcn.spec]p4:
668     //   If the definition of a function appears in a translation unit before its
669     //   first declaration as inline, the program is ill-formed.
670     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
671     Diag(Def->getLocation(), diag::note_previous_definition);
672     Invalid = true;
673   }
674 
675   // C++17 [temp.deduct.guide]p3:
676   //   Two deduction guide declarations in the same translation unit
677   //   for the same class template shall not have equivalent
678   //   parameter-declaration-clauses.
679   if (isa<CXXDeductionGuideDecl>(New) &&
680       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
681     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
682     Diag(Old->getLocation(), diag::note_previous_declaration);
683   }
684 
685   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
686   // argument expression, that declaration shall be a definition and shall be
687   // the only declaration of the function or function template in the
688   // translation unit.
689   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
690       functionDeclHasDefaultArgument(Old)) {
691     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
692     Diag(Old->getLocation(), diag::note_previous_declaration);
693     Invalid = true;
694   }
695 
696   // C++11 [temp.friend]p4 (DR329):
697   //   When a function is defined in a friend function declaration in a class
698   //   template, the function is instantiated when the function is odr-used.
699   //   The same restrictions on multiple declarations and definitions that
700   //   apply to non-template function declarations and definitions also apply
701   //   to these implicit definitions.
702   const FunctionDecl *OldDefinition = nullptr;
703   if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
704       Old->isDefined(OldDefinition, true))
705     CheckForFunctionRedefinition(New, OldDefinition);
706 
707   return Invalid;
708 }
709 
710 NamedDecl *
711 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
712                                    MultiTemplateParamsArg TemplateParamLists) {
713   assert(D.isDecompositionDeclarator());
714   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
715 
716   // The syntax only allows a decomposition declarator as a simple-declaration,
717   // a for-range-declaration, or a condition in Clang, but we parse it in more
718   // cases than that.
719   if (!D.mayHaveDecompositionDeclarator()) {
720     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
721       << Decomp.getSourceRange();
722     return nullptr;
723   }
724 
725   if (!TemplateParamLists.empty()) {
726     // FIXME: There's no rule against this, but there are also no rules that
727     // would actually make it usable, so we reject it for now.
728     Diag(TemplateParamLists.front()->getTemplateLoc(),
729          diag::err_decomp_decl_template);
730     return nullptr;
731   }
732 
733   Diag(Decomp.getLSquareLoc(),
734        !getLangOpts().CPlusPlus17
735            ? diag::ext_decomp_decl
736            : D.getContext() == DeclaratorContext::Condition
737                  ? diag::ext_decomp_decl_cond
738                  : diag::warn_cxx14_compat_decomp_decl)
739       << Decomp.getSourceRange();
740 
741   // The semantic context is always just the current context.
742   DeclContext *const DC = CurContext;
743 
744   // C++17 [dcl.dcl]/8:
745   //   The decl-specifier-seq shall contain only the type-specifier auto
746   //   and cv-qualifiers.
747   // C++2a [dcl.dcl]/8:
748   //   If decl-specifier-seq contains any decl-specifier other than static,
749   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
750   auto &DS = D.getDeclSpec();
751   {
752     SmallVector<StringRef, 8> BadSpecifiers;
753     SmallVector<SourceLocation, 8> BadSpecifierLocs;
754     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
755     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
756     if (auto SCS = DS.getStorageClassSpec()) {
757       if (SCS == DeclSpec::SCS_static) {
758         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
759         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
760       } else {
761         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
762         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
763       }
764     }
765     if (auto TSCS = DS.getThreadStorageClassSpec()) {
766       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
767       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
768     }
769     if (DS.hasConstexprSpecifier()) {
770       BadSpecifiers.push_back(
771           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
772       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
773     }
774     if (DS.isInlineSpecified()) {
775       BadSpecifiers.push_back("inline");
776       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
777     }
778     if (!BadSpecifiers.empty()) {
779       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
780       Err << (int)BadSpecifiers.size()
781           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
782       // Don't add FixItHints to remove the specifiers; we do still respect
783       // them when building the underlying variable.
784       for (auto Loc : BadSpecifierLocs)
785         Err << SourceRange(Loc, Loc);
786     } else if (!CPlusPlus20Specifiers.empty()) {
787       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
788                          getLangOpts().CPlusPlus20
789                              ? diag::warn_cxx17_compat_decomp_decl_spec
790                              : diag::ext_decomp_decl_spec);
791       Warn << (int)CPlusPlus20Specifiers.size()
792            << llvm::join(CPlusPlus20Specifiers.begin(),
793                          CPlusPlus20Specifiers.end(), " ");
794       for (auto Loc : CPlusPlus20SpecifierLocs)
795         Warn << SourceRange(Loc, Loc);
796     }
797     // We can't recover from it being declared as a typedef.
798     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
799       return nullptr;
800   }
801 
802   // C++2a [dcl.struct.bind]p1:
803   //   A cv that includes volatile is deprecated
804   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
805       getLangOpts().CPlusPlus20)
806     Diag(DS.getVolatileSpecLoc(),
807          diag::warn_deprecated_volatile_structured_binding);
808 
809   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
810   QualType R = TInfo->getType();
811 
812   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
813                                       UPPC_DeclarationType))
814     D.setInvalidType();
815 
816   // The syntax only allows a single ref-qualifier prior to the decomposition
817   // declarator. No other declarator chunks are permitted. Also check the type
818   // specifier here.
819   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
820       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
821       (D.getNumTypeObjects() == 1 &&
822        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
823     Diag(Decomp.getLSquareLoc(),
824          (D.hasGroupingParens() ||
825           (D.getNumTypeObjects() &&
826            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
827              ? diag::err_decomp_decl_parens
828              : diag::err_decomp_decl_type)
829         << R;
830 
831     // In most cases, there's no actual problem with an explicitly-specified
832     // type, but a function type won't work here, and ActOnVariableDeclarator
833     // shouldn't be called for such a type.
834     if (R->isFunctionType())
835       D.setInvalidType();
836   }
837 
838   // Build the BindingDecls.
839   SmallVector<BindingDecl*, 8> Bindings;
840 
841   // Build the BindingDecls.
842   for (auto &B : D.getDecompositionDeclarator().bindings()) {
843     // Check for name conflicts.
844     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
845     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
846                           ForVisibleRedeclaration);
847     LookupName(Previous, S,
848                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
849 
850     // It's not permitted to shadow a template parameter name.
851     if (Previous.isSingleResult() &&
852         Previous.getFoundDecl()->isTemplateParameter()) {
853       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
854                                       Previous.getFoundDecl());
855       Previous.clear();
856     }
857 
858     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
859 
860     // Find the shadowed declaration before filtering for scope.
861     NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
862                                   ? getShadowedDeclaration(BD, Previous)
863                                   : nullptr;
864 
865     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
866                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
867     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
868                          /*AllowInlineNamespace*/false);
869 
870     if (!Previous.empty()) {
871       auto *Old = Previous.getRepresentativeDecl();
872       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
873       Diag(Old->getLocation(), diag::note_previous_definition);
874     } else if (ShadowedDecl && !D.isRedeclaration()) {
875       CheckShadow(BD, ShadowedDecl, Previous);
876     }
877     PushOnScopeChains(BD, S, true);
878     Bindings.push_back(BD);
879     ParsingInitForAutoVars.insert(BD);
880   }
881 
882   // There are no prior lookup results for the variable itself, because it
883   // is unnamed.
884   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
885                                Decomp.getLSquareLoc());
886   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
887                         ForVisibleRedeclaration);
888 
889   // Build the variable that holds the non-decomposed object.
890   bool AddToScope = true;
891   NamedDecl *New =
892       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
893                               MultiTemplateParamsArg(), AddToScope, Bindings);
894   if (AddToScope) {
895     S->AddDecl(New);
896     CurContext->addHiddenDecl(New);
897   }
898 
899   if (isInOpenMPDeclareTargetContext())
900     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
901 
902   return New;
903 }
904 
905 static bool checkSimpleDecomposition(
906     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
907     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
908     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
909   if ((int64_t)Bindings.size() != NumElems) {
910     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
911         << DecompType << (unsigned)Bindings.size()
912         << (unsigned)NumElems.getLimitedValue(UINT_MAX)
913         << toString(NumElems, 10) << (NumElems < Bindings.size());
914     return true;
915   }
916 
917   unsigned I = 0;
918   for (auto *B : Bindings) {
919     SourceLocation Loc = B->getLocation();
920     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
921     if (E.isInvalid())
922       return true;
923     E = GetInit(Loc, E.get(), I++);
924     if (E.isInvalid())
925       return true;
926     B->setBinding(ElemType, E.get());
927   }
928 
929   return false;
930 }
931 
932 static bool checkArrayLikeDecomposition(Sema &S,
933                                         ArrayRef<BindingDecl *> Bindings,
934                                         ValueDecl *Src, QualType DecompType,
935                                         const llvm::APSInt &NumElems,
936                                         QualType ElemType) {
937   return checkSimpleDecomposition(
938       S, Bindings, Src, DecompType, NumElems, ElemType,
939       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
940         ExprResult E = S.ActOnIntegerConstant(Loc, I);
941         if (E.isInvalid())
942           return ExprError();
943         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
944       });
945 }
946 
947 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
948                                     ValueDecl *Src, QualType DecompType,
949                                     const ConstantArrayType *CAT) {
950   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
951                                      llvm::APSInt(CAT->getSize()),
952                                      CAT->getElementType());
953 }
954 
955 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
956                                      ValueDecl *Src, QualType DecompType,
957                                      const VectorType *VT) {
958   return checkArrayLikeDecomposition(
959       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
960       S.Context.getQualifiedType(VT->getElementType(),
961                                  DecompType.getQualifiers()));
962 }
963 
964 static bool checkComplexDecomposition(Sema &S,
965                                       ArrayRef<BindingDecl *> Bindings,
966                                       ValueDecl *Src, QualType DecompType,
967                                       const ComplexType *CT) {
968   return checkSimpleDecomposition(
969       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
970       S.Context.getQualifiedType(CT->getElementType(),
971                                  DecompType.getQualifiers()),
972       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
973         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
974       });
975 }
976 
977 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
978                                      TemplateArgumentListInfo &Args,
979                                      const TemplateParameterList *Params) {
980   SmallString<128> SS;
981   llvm::raw_svector_ostream OS(SS);
982   bool First = true;
983   unsigned I = 0;
984   for (auto &Arg : Args.arguments()) {
985     if (!First)
986       OS << ", ";
987     Arg.getArgument().print(PrintingPolicy, OS,
988                             TemplateParameterList::shouldIncludeTypeForArgument(
989                                 PrintingPolicy, Params, I));
990     First = false;
991     I++;
992   }
993   return std::string(OS.str());
994 }
995 
996 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
997                                      SourceLocation Loc, StringRef Trait,
998                                      TemplateArgumentListInfo &Args,
999                                      unsigned DiagID) {
1000   auto DiagnoseMissing = [&] {
1001     if (DiagID)
1002       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1003                                                Args, /*Params*/ nullptr);
1004     return true;
1005   };
1006 
1007   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1008   NamespaceDecl *Std = S.getStdNamespace();
1009   if (!Std)
1010     return DiagnoseMissing();
1011 
1012   // Look up the trait itself, within namespace std. We can diagnose various
1013   // problems with this lookup even if we've been asked to not diagnose a
1014   // missing specialization, because this can only fail if the user has been
1015   // declaring their own names in namespace std or we don't support the
1016   // standard library implementation in use.
1017   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1018                       Loc, Sema::LookupOrdinaryName);
1019   if (!S.LookupQualifiedName(Result, Std))
1020     return DiagnoseMissing();
1021   if (Result.isAmbiguous())
1022     return true;
1023 
1024   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1025   if (!TraitTD) {
1026     Result.suppressDiagnostics();
1027     NamedDecl *Found = *Result.begin();
1028     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1029     S.Diag(Found->getLocation(), diag::note_declared_at);
1030     return true;
1031   }
1032 
1033   // Build the template-id.
1034   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1035   if (TraitTy.isNull())
1036     return true;
1037   if (!S.isCompleteType(Loc, TraitTy)) {
1038     if (DiagID)
1039       S.RequireCompleteType(
1040           Loc, TraitTy, DiagID,
1041           printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1042                             TraitTD->getTemplateParameters()));
1043     return true;
1044   }
1045 
1046   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1047   assert(RD && "specialization of class template is not a class?");
1048 
1049   // Look up the member of the trait type.
1050   S.LookupQualifiedName(TraitMemberLookup, RD);
1051   return TraitMemberLookup.isAmbiguous();
1052 }
1053 
1054 static TemplateArgumentLoc
1055 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1056                                    uint64_t I) {
1057   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1058   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1059 }
1060 
1061 static TemplateArgumentLoc
1062 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1063   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1064 }
1065 
1066 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1067 
1068 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1069                                llvm::APSInt &Size) {
1070   EnterExpressionEvaluationContext ContextRAII(
1071       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1072 
1073   DeclarationName Value = S.PP.getIdentifierInfo("value");
1074   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1075 
1076   // Form template argument list for tuple_size<T>.
1077   TemplateArgumentListInfo Args(Loc, Loc);
1078   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1079 
1080   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1081   // it's not tuple-like.
1082   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1083       R.empty())
1084     return IsTupleLike::NotTupleLike;
1085 
1086   // If we get this far, we've committed to the tuple interpretation, but
1087   // we can still fail if there actually isn't a usable ::value.
1088 
1089   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1090     LookupResult &R;
1091     TemplateArgumentListInfo &Args;
1092     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1093         : R(R), Args(Args) {}
1094     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1095                                                SourceLocation Loc) override {
1096       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1097              << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1098                                   /*Params*/ nullptr);
1099     }
1100   } Diagnoser(R, Args);
1101 
1102   ExprResult E =
1103       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1104   if (E.isInvalid())
1105     return IsTupleLike::Error;
1106 
1107   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1108   if (E.isInvalid())
1109     return IsTupleLike::Error;
1110 
1111   return IsTupleLike::TupleLike;
1112 }
1113 
1114 /// \return std::tuple_element<I, T>::type.
1115 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1116                                         unsigned I, QualType T) {
1117   // Form template argument list for tuple_element<I, T>.
1118   TemplateArgumentListInfo Args(Loc, Loc);
1119   Args.addArgument(
1120       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1121   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1122 
1123   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1124   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1125   if (lookupStdTypeTraitMember(
1126           S, R, Loc, "tuple_element", Args,
1127           diag::err_decomp_decl_std_tuple_element_not_specialized))
1128     return QualType();
1129 
1130   auto *TD = R.getAsSingle<TypeDecl>();
1131   if (!TD) {
1132     R.suppressDiagnostics();
1133     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1134         << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1135                              /*Params*/ nullptr);
1136     if (!R.empty())
1137       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1138     return QualType();
1139   }
1140 
1141   return S.Context.getTypeDeclType(TD);
1142 }
1143 
1144 namespace {
1145 struct InitializingBinding {
1146   Sema &S;
1147   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1148     Sema::CodeSynthesisContext Ctx;
1149     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1150     Ctx.PointOfInstantiation = BD->getLocation();
1151     Ctx.Entity = BD;
1152     S.pushCodeSynthesisContext(Ctx);
1153   }
1154   ~InitializingBinding() {
1155     S.popCodeSynthesisContext();
1156   }
1157 };
1158 }
1159 
1160 static bool checkTupleLikeDecomposition(Sema &S,
1161                                         ArrayRef<BindingDecl *> Bindings,
1162                                         VarDecl *Src, QualType DecompType,
1163                                         const llvm::APSInt &TupleSize) {
1164   if ((int64_t)Bindings.size() != TupleSize) {
1165     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1166         << DecompType << (unsigned)Bindings.size()
1167         << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1168         << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1169     return true;
1170   }
1171 
1172   if (Bindings.empty())
1173     return false;
1174 
1175   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1176 
1177   // [dcl.decomp]p3:
1178   //   The unqualified-id get is looked up in the scope of E by class member
1179   //   access lookup ...
1180   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1181   bool UseMemberGet = false;
1182   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1183     if (auto *RD = DecompType->getAsCXXRecordDecl())
1184       S.LookupQualifiedName(MemberGet, RD);
1185     if (MemberGet.isAmbiguous())
1186       return true;
1187     //   ... and if that finds at least one declaration that is a function
1188     //   template whose first template parameter is a non-type parameter ...
1189     for (NamedDecl *D : MemberGet) {
1190       if (FunctionTemplateDecl *FTD =
1191               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1192         TemplateParameterList *TPL = FTD->getTemplateParameters();
1193         if (TPL->size() != 0 &&
1194             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1195           //   ... the initializer is e.get<i>().
1196           UseMemberGet = true;
1197           break;
1198         }
1199       }
1200     }
1201   }
1202 
1203   unsigned I = 0;
1204   for (auto *B : Bindings) {
1205     InitializingBinding InitContext(S, B);
1206     SourceLocation Loc = B->getLocation();
1207 
1208     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1209     if (E.isInvalid())
1210       return true;
1211 
1212     //   e is an lvalue if the type of the entity is an lvalue reference and
1213     //   an xvalue otherwise
1214     if (!Src->getType()->isLValueReferenceType())
1215       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1216                                    E.get(), nullptr, VK_XValue,
1217                                    FPOptionsOverride());
1218 
1219     TemplateArgumentListInfo Args(Loc, Loc);
1220     Args.addArgument(
1221         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1222 
1223     if (UseMemberGet) {
1224       //   if [lookup of member get] finds at least one declaration, the
1225       //   initializer is e.get<i-1>().
1226       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1227                                      CXXScopeSpec(), SourceLocation(), nullptr,
1228                                      MemberGet, &Args, nullptr);
1229       if (E.isInvalid())
1230         return true;
1231 
1232       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1233     } else {
1234       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1235       //   in the associated namespaces.
1236       Expr *Get = UnresolvedLookupExpr::Create(
1237           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1238           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1239           UnresolvedSetIterator(), UnresolvedSetIterator());
1240 
1241       Expr *Arg = E.get();
1242       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1243     }
1244     if (E.isInvalid())
1245       return true;
1246     Expr *Init = E.get();
1247 
1248     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1249     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1250     if (T.isNull())
1251       return true;
1252 
1253     //   each vi is a variable of type "reference to T" initialized with the
1254     //   initializer, where the reference is an lvalue reference if the
1255     //   initializer is an lvalue and an rvalue reference otherwise
1256     QualType RefType =
1257         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1258     if (RefType.isNull())
1259       return true;
1260     auto *RefVD = VarDecl::Create(
1261         S.Context, Src->getDeclContext(), Loc, Loc,
1262         B->getDeclName().getAsIdentifierInfo(), RefType,
1263         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1264     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1265     RefVD->setTSCSpec(Src->getTSCSpec());
1266     RefVD->setImplicit();
1267     if (Src->isInlineSpecified())
1268       RefVD->setInlineSpecified();
1269     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1270 
1271     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1272     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1273     InitializationSequence Seq(S, Entity, Kind, Init);
1274     E = Seq.Perform(S, Entity, Kind, Init);
1275     if (E.isInvalid())
1276       return true;
1277     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1278     if (E.isInvalid())
1279       return true;
1280     RefVD->setInit(E.get());
1281     S.CheckCompleteVariableDeclaration(RefVD);
1282 
1283     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1284                                    DeclarationNameInfo(B->getDeclName(), Loc),
1285                                    RefVD);
1286     if (E.isInvalid())
1287       return true;
1288 
1289     B->setBinding(T, E.get());
1290     I++;
1291   }
1292 
1293   return false;
1294 }
1295 
1296 /// Find the base class to decompose in a built-in decomposition of a class type.
1297 /// This base class search is, unfortunately, not quite like any other that we
1298 /// perform anywhere else in C++.
1299 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1300                                                 const CXXRecordDecl *RD,
1301                                                 CXXCastPath &BasePath) {
1302   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1303                           CXXBasePath &Path) {
1304     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1305   };
1306 
1307   const CXXRecordDecl *ClassWithFields = nullptr;
1308   AccessSpecifier AS = AS_public;
1309   if (RD->hasDirectFields())
1310     // [dcl.decomp]p4:
1311     //   Otherwise, all of E's non-static data members shall be public direct
1312     //   members of E ...
1313     ClassWithFields = RD;
1314   else {
1315     //   ... or of ...
1316     CXXBasePaths Paths;
1317     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1318     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1319       // If no classes have fields, just decompose RD itself. (This will work
1320       // if and only if zero bindings were provided.)
1321       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1322     }
1323 
1324     CXXBasePath *BestPath = nullptr;
1325     for (auto &P : Paths) {
1326       if (!BestPath)
1327         BestPath = &P;
1328       else if (!S.Context.hasSameType(P.back().Base->getType(),
1329                                       BestPath->back().Base->getType())) {
1330         //   ... the same ...
1331         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1332           << false << RD << BestPath->back().Base->getType()
1333           << P.back().Base->getType();
1334         return DeclAccessPair();
1335       } else if (P.Access < BestPath->Access) {
1336         BestPath = &P;
1337       }
1338     }
1339 
1340     //   ... unambiguous ...
1341     QualType BaseType = BestPath->back().Base->getType();
1342     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1343       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1344         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1345       return DeclAccessPair();
1346     }
1347 
1348     //   ... [accessible, implied by other rules] base class of E.
1349     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1350                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1351     AS = BestPath->Access;
1352 
1353     ClassWithFields = BaseType->getAsCXXRecordDecl();
1354     S.BuildBasePathArray(Paths, BasePath);
1355   }
1356 
1357   // The above search did not check whether the selected class itself has base
1358   // classes with fields, so check that now.
1359   CXXBasePaths Paths;
1360   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1361     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1362       << (ClassWithFields == RD) << RD << ClassWithFields
1363       << Paths.front().back().Base->getType();
1364     return DeclAccessPair();
1365   }
1366 
1367   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1368 }
1369 
1370 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1371                                      ValueDecl *Src, QualType DecompType,
1372                                      const CXXRecordDecl *OrigRD) {
1373   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1374                             diag::err_incomplete_type))
1375     return true;
1376 
1377   CXXCastPath BasePath;
1378   DeclAccessPair BasePair =
1379       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1380   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1381   if (!RD)
1382     return true;
1383   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1384                                                  DecompType.getQualifiers());
1385 
1386   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1387     unsigned NumFields = llvm::count_if(
1388         RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1389     assert(Bindings.size() != NumFields);
1390     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1391         << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1392         << (NumFields < Bindings.size());
1393     return true;
1394   };
1395 
1396   //   all of E's non-static data members shall be [...] well-formed
1397   //   when named as e.name in the context of the structured binding,
1398   //   E shall not have an anonymous union member, ...
1399   unsigned I = 0;
1400   for (auto *FD : RD->fields()) {
1401     if (FD->isUnnamedBitfield())
1402       continue;
1403 
1404     // All the non-static data members are required to be nameable, so they
1405     // must all have names.
1406     if (!FD->getDeclName()) {
1407       if (RD->isLambda()) {
1408         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1409         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1410         return true;
1411       }
1412 
1413       if (FD->isAnonymousStructOrUnion()) {
1414         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1415           << DecompType << FD->getType()->isUnionType();
1416         S.Diag(FD->getLocation(), diag::note_declared_at);
1417         return true;
1418       }
1419 
1420       // FIXME: Are there any other ways we could have an anonymous member?
1421     }
1422 
1423     // We have a real field to bind.
1424     if (I >= Bindings.size())
1425       return DiagnoseBadNumberOfBindings();
1426     auto *B = Bindings[I++];
1427     SourceLocation Loc = B->getLocation();
1428 
1429     // The field must be accessible in the context of the structured binding.
1430     // We already checked that the base class is accessible.
1431     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1432     // const_cast here.
1433     S.CheckStructuredBindingMemberAccess(
1434         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1435         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1436                                      BasePair.getAccess(), FD->getAccess())));
1437 
1438     // Initialize the binding to Src.FD.
1439     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1440     if (E.isInvalid())
1441       return true;
1442     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1443                             VK_LValue, &BasePath);
1444     if (E.isInvalid())
1445       return true;
1446     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1447                                   CXXScopeSpec(), FD,
1448                                   DeclAccessPair::make(FD, FD->getAccess()),
1449                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1450     if (E.isInvalid())
1451       return true;
1452 
1453     // If the type of the member is T, the referenced type is cv T, where cv is
1454     // the cv-qualification of the decomposition expression.
1455     //
1456     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1457     // 'const' to the type of the field.
1458     Qualifiers Q = DecompType.getQualifiers();
1459     if (FD->isMutable())
1460       Q.removeConst();
1461     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1462   }
1463 
1464   if (I != Bindings.size())
1465     return DiagnoseBadNumberOfBindings();
1466 
1467   return false;
1468 }
1469 
1470 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1471   QualType DecompType = DD->getType();
1472 
1473   // If the type of the decomposition is dependent, then so is the type of
1474   // each binding.
1475   if (DecompType->isDependentType()) {
1476     for (auto *B : DD->bindings())
1477       B->setType(Context.DependentTy);
1478     return;
1479   }
1480 
1481   DecompType = DecompType.getNonReferenceType();
1482   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1483 
1484   // C++1z [dcl.decomp]/2:
1485   //   If E is an array type [...]
1486   // As an extension, we also support decomposition of built-in complex and
1487   // vector types.
1488   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1489     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1490       DD->setInvalidDecl();
1491     return;
1492   }
1493   if (auto *VT = DecompType->getAs<VectorType>()) {
1494     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1495       DD->setInvalidDecl();
1496     return;
1497   }
1498   if (auto *CT = DecompType->getAs<ComplexType>()) {
1499     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1500       DD->setInvalidDecl();
1501     return;
1502   }
1503 
1504   // C++1z [dcl.decomp]/3:
1505   //   if the expression std::tuple_size<E>::value is a well-formed integral
1506   //   constant expression, [...]
1507   llvm::APSInt TupleSize(32);
1508   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1509   case IsTupleLike::Error:
1510     DD->setInvalidDecl();
1511     return;
1512 
1513   case IsTupleLike::TupleLike:
1514     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1515       DD->setInvalidDecl();
1516     return;
1517 
1518   case IsTupleLike::NotTupleLike:
1519     break;
1520   }
1521 
1522   // C++1z [dcl.dcl]/8:
1523   //   [E shall be of array or non-union class type]
1524   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1525   if (!RD || RD->isUnion()) {
1526     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1527         << DD << !RD << DecompType;
1528     DD->setInvalidDecl();
1529     return;
1530   }
1531 
1532   // C++1z [dcl.decomp]/4:
1533   //   all of E's non-static data members shall be [...] direct members of
1534   //   E or of the same unambiguous public base class of E, ...
1535   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1536     DD->setInvalidDecl();
1537 }
1538 
1539 /// Merge the exception specifications of two variable declarations.
1540 ///
1541 /// This is called when there's a redeclaration of a VarDecl. The function
1542 /// checks if the redeclaration might have an exception specification and
1543 /// validates compatibility and merges the specs if necessary.
1544 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1545   // Shortcut if exceptions are disabled.
1546   if (!getLangOpts().CXXExceptions)
1547     return;
1548 
1549   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1550          "Should only be called if types are otherwise the same.");
1551 
1552   QualType NewType = New->getType();
1553   QualType OldType = Old->getType();
1554 
1555   // We're only interested in pointers and references to functions, as well
1556   // as pointers to member functions.
1557   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1558     NewType = R->getPointeeType();
1559     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1560   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1561     NewType = P->getPointeeType();
1562     OldType = OldType->castAs<PointerType>()->getPointeeType();
1563   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1564     NewType = M->getPointeeType();
1565     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1566   }
1567 
1568   if (!NewType->isFunctionProtoType())
1569     return;
1570 
1571   // There's lots of special cases for functions. For function pointers, system
1572   // libraries are hopefully not as broken so that we don't need these
1573   // workarounds.
1574   if (CheckEquivalentExceptionSpec(
1575         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1576         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1577     New->setInvalidDecl();
1578   }
1579 }
1580 
1581 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1582 /// function declaration are well-formed according to C++
1583 /// [dcl.fct.default].
1584 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1585   unsigned NumParams = FD->getNumParams();
1586   unsigned ParamIdx = 0;
1587 
1588   // This checking doesn't make sense for explicit specializations; their
1589   // default arguments are determined by the declaration we're specializing,
1590   // not by FD.
1591   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1592     return;
1593   if (auto *FTD = FD->getDescribedFunctionTemplate())
1594     if (FTD->isMemberSpecialization())
1595       return;
1596 
1597   // Find first parameter with a default argument
1598   for (; ParamIdx < NumParams; ++ParamIdx) {
1599     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1600     if (Param->hasDefaultArg())
1601       break;
1602   }
1603 
1604   // C++20 [dcl.fct.default]p4:
1605   //   In a given function declaration, each parameter subsequent to a parameter
1606   //   with a default argument shall have a default argument supplied in this or
1607   //   a previous declaration, unless the parameter was expanded from a
1608   //   parameter pack, or shall be a function parameter pack.
1609   for (; ParamIdx < NumParams; ++ParamIdx) {
1610     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1611     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1612         !(CurrentInstantiationScope &&
1613           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1614       if (Param->isInvalidDecl())
1615         /* We already complained about this parameter. */;
1616       else if (Param->getIdentifier())
1617         Diag(Param->getLocation(),
1618              diag::err_param_default_argument_missing_name)
1619           << Param->getIdentifier();
1620       else
1621         Diag(Param->getLocation(),
1622              diag::err_param_default_argument_missing);
1623     }
1624   }
1625 }
1626 
1627 /// Check that the given type is a literal type. Issue a diagnostic if not,
1628 /// if Kind is Diagnose.
1629 /// \return \c true if a problem has been found (and optionally diagnosed).
1630 template <typename... Ts>
1631 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1632                              SourceLocation Loc, QualType T, unsigned DiagID,
1633                              Ts &&...DiagArgs) {
1634   if (T->isDependentType())
1635     return false;
1636 
1637   switch (Kind) {
1638   case Sema::CheckConstexprKind::Diagnose:
1639     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1640                                       std::forward<Ts>(DiagArgs)...);
1641 
1642   case Sema::CheckConstexprKind::CheckValid:
1643     return !T->isLiteralType(SemaRef.Context);
1644   }
1645 
1646   llvm_unreachable("unknown CheckConstexprKind");
1647 }
1648 
1649 /// Determine whether a destructor cannot be constexpr due to
1650 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1651                                                const CXXDestructorDecl *DD,
1652                                                Sema::CheckConstexprKind Kind) {
1653   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1654     const CXXRecordDecl *RD =
1655         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1656     if (!RD || RD->hasConstexprDestructor())
1657       return true;
1658 
1659     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1660       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1661           << static_cast<int>(DD->getConstexprKind()) << !FD
1662           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1663       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1664           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1665     }
1666     return false;
1667   };
1668 
1669   const CXXRecordDecl *RD = DD->getParent();
1670   for (const CXXBaseSpecifier &B : RD->bases())
1671     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1672       return false;
1673   for (const FieldDecl *FD : RD->fields())
1674     if (!Check(FD->getLocation(), FD->getType(), FD))
1675       return false;
1676   return true;
1677 }
1678 
1679 /// Check whether a function's parameter types are all literal types. If so,
1680 /// return true. If not, produce a suitable diagnostic and return false.
1681 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1682                                          const FunctionDecl *FD,
1683                                          Sema::CheckConstexprKind Kind) {
1684   unsigned ArgIndex = 0;
1685   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1686   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1687                                               e = FT->param_type_end();
1688        i != e; ++i, ++ArgIndex) {
1689     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1690     SourceLocation ParamLoc = PD->getLocation();
1691     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1692                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1693                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1694                          FD->isConsteval()))
1695       return false;
1696   }
1697   return true;
1698 }
1699 
1700 /// Check whether a function's return type is a literal type. If so, return
1701 /// true. If not, produce a suitable diagnostic and return false.
1702 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1703                                      Sema::CheckConstexprKind Kind) {
1704   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1705                        diag::err_constexpr_non_literal_return,
1706                        FD->isConsteval()))
1707     return false;
1708   return true;
1709 }
1710 
1711 /// Get diagnostic %select index for tag kind for
1712 /// record diagnostic message.
1713 /// WARNING: Indexes apply to particular diagnostics only!
1714 ///
1715 /// \returns diagnostic %select index.
1716 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1717   switch (Tag) {
1718   case TTK_Struct: return 0;
1719   case TTK_Interface: return 1;
1720   case TTK_Class:  return 2;
1721   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1722   }
1723 }
1724 
1725 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1726                                        Stmt *Body,
1727                                        Sema::CheckConstexprKind Kind);
1728 
1729 // Check whether a function declaration satisfies the requirements of a
1730 // constexpr function definition or a constexpr constructor definition. If so,
1731 // return true. If not, produce appropriate diagnostics (unless asked not to by
1732 // Kind) and return false.
1733 //
1734 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1735 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1736                                             CheckConstexprKind Kind) {
1737   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1738   if (MD && MD->isInstance()) {
1739     // C++11 [dcl.constexpr]p4:
1740     //  The definition of a constexpr constructor shall satisfy the following
1741     //  constraints:
1742     //  - the class shall not have any virtual base classes;
1743     //
1744     // FIXME: This only applies to constructors and destructors, not arbitrary
1745     // member functions.
1746     const CXXRecordDecl *RD = MD->getParent();
1747     if (RD->getNumVBases()) {
1748       if (Kind == CheckConstexprKind::CheckValid)
1749         return false;
1750 
1751       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1752         << isa<CXXConstructorDecl>(NewFD)
1753         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1754       for (const auto &I : RD->vbases())
1755         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1756             << I.getSourceRange();
1757       return false;
1758     }
1759   }
1760 
1761   if (!isa<CXXConstructorDecl>(NewFD)) {
1762     // C++11 [dcl.constexpr]p3:
1763     //  The definition of a constexpr function shall satisfy the following
1764     //  constraints:
1765     // - it shall not be virtual; (removed in C++20)
1766     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1767     if (Method && Method->isVirtual()) {
1768       if (getLangOpts().CPlusPlus20) {
1769         if (Kind == CheckConstexprKind::Diagnose)
1770           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1771       } else {
1772         if (Kind == CheckConstexprKind::CheckValid)
1773           return false;
1774 
1775         Method = Method->getCanonicalDecl();
1776         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1777 
1778         // If it's not obvious why this function is virtual, find an overridden
1779         // function which uses the 'virtual' keyword.
1780         const CXXMethodDecl *WrittenVirtual = Method;
1781         while (!WrittenVirtual->isVirtualAsWritten())
1782           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1783         if (WrittenVirtual != Method)
1784           Diag(WrittenVirtual->getLocation(),
1785                diag::note_overridden_virtual_function);
1786         return false;
1787       }
1788     }
1789 
1790     // - its return type shall be a literal type;
1791     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1792       return false;
1793   }
1794 
1795   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1796     // A destructor can be constexpr only if the defaulted destructor could be;
1797     // we don't need to check the members and bases if we already know they all
1798     // have constexpr destructors.
1799     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1800       if (Kind == CheckConstexprKind::CheckValid)
1801         return false;
1802       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1803         return false;
1804     }
1805   }
1806 
1807   // - each of its parameter types shall be a literal type;
1808   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1809     return false;
1810 
1811   Stmt *Body = NewFD->getBody();
1812   assert(Body &&
1813          "CheckConstexprFunctionDefinition called on function with no body");
1814   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1815 }
1816 
1817 /// Check the given declaration statement is legal within a constexpr function
1818 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1819 ///
1820 /// \return true if the body is OK (maybe only as an extension), false if we
1821 ///         have diagnosed a problem.
1822 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1823                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1824                                    Sema::CheckConstexprKind Kind) {
1825   // C++11 [dcl.constexpr]p3 and p4:
1826   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1827   //  contain only
1828   for (const auto *DclIt : DS->decls()) {
1829     switch (DclIt->getKind()) {
1830     case Decl::StaticAssert:
1831     case Decl::Using:
1832     case Decl::UsingShadow:
1833     case Decl::UsingDirective:
1834     case Decl::UnresolvedUsingTypename:
1835     case Decl::UnresolvedUsingValue:
1836     case Decl::UsingEnum:
1837       //   - static_assert-declarations
1838       //   - using-declarations,
1839       //   - using-directives,
1840       //   - using-enum-declaration
1841       continue;
1842 
1843     case Decl::Typedef:
1844     case Decl::TypeAlias: {
1845       //   - typedef declarations and alias-declarations that do not define
1846       //     classes or enumerations,
1847       const auto *TN = cast<TypedefNameDecl>(DclIt);
1848       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1849         // Don't allow variably-modified types in constexpr functions.
1850         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1851           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1852           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1853             << TL.getSourceRange() << TL.getType()
1854             << isa<CXXConstructorDecl>(Dcl);
1855         }
1856         return false;
1857       }
1858       continue;
1859     }
1860 
1861     case Decl::Enum:
1862     case Decl::CXXRecord:
1863       // C++1y allows types to be defined, not just declared.
1864       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1865         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866           SemaRef.Diag(DS->getBeginLoc(),
1867                        SemaRef.getLangOpts().CPlusPlus14
1868                            ? diag::warn_cxx11_compat_constexpr_type_definition
1869                            : diag::ext_constexpr_type_definition)
1870               << isa<CXXConstructorDecl>(Dcl);
1871         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1872           return false;
1873         }
1874       }
1875       continue;
1876 
1877     case Decl::EnumConstant:
1878     case Decl::IndirectField:
1879     case Decl::ParmVar:
1880       // These can only appear with other declarations which are banned in
1881       // C++11 and permitted in C++1y, so ignore them.
1882       continue;
1883 
1884     case Decl::Var:
1885     case Decl::Decomposition: {
1886       // C++1y [dcl.constexpr]p3 allows anything except:
1887       //   a definition of a variable of non-literal type or of static or
1888       //   thread storage duration or [before C++2a] for which no
1889       //   initialization is performed.
1890       const auto *VD = cast<VarDecl>(DclIt);
1891       if (VD->isThisDeclarationADefinition()) {
1892         if (VD->isStaticLocal()) {
1893           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1894             SemaRef.Diag(VD->getLocation(),
1895                          SemaRef.getLangOpts().CPlusPlus2b
1896                              ? diag::warn_cxx20_compat_constexpr_var
1897                              : diag::ext_constexpr_static_var)
1898                 << isa<CXXConstructorDecl>(Dcl)
1899                 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1900           } else if (!SemaRef.getLangOpts().CPlusPlus2b) {
1901             return false;
1902           }
1903         }
1904         if (SemaRef.LangOpts.CPlusPlus2b) {
1905           CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1906                            diag::warn_cxx20_compat_constexpr_var,
1907                            isa<CXXConstructorDecl>(Dcl),
1908                            /*variable of non-literal type*/ 2);
1909         } else if (CheckLiteralType(
1910                        SemaRef, Kind, VD->getLocation(), VD->getType(),
1911                        diag::err_constexpr_local_var_non_literal_type,
1912                        isa<CXXConstructorDecl>(Dcl))) {
1913           return false;
1914         }
1915         if (!VD->getType()->isDependentType() &&
1916             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1917           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1918             SemaRef.Diag(
1919                 VD->getLocation(),
1920                 SemaRef.getLangOpts().CPlusPlus20
1921                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1922                     : diag::ext_constexpr_local_var_no_init)
1923                 << isa<CXXConstructorDecl>(Dcl);
1924           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1925             return false;
1926           }
1927           continue;
1928         }
1929       }
1930       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1931         SemaRef.Diag(VD->getLocation(),
1932                      SemaRef.getLangOpts().CPlusPlus14
1933                       ? diag::warn_cxx11_compat_constexpr_local_var
1934                       : diag::ext_constexpr_local_var)
1935           << isa<CXXConstructorDecl>(Dcl);
1936       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1937         return false;
1938       }
1939       continue;
1940     }
1941 
1942     case Decl::NamespaceAlias:
1943     case Decl::Function:
1944       // These are disallowed in C++11 and permitted in C++1y. Allow them
1945       // everywhere as an extension.
1946       if (!Cxx1yLoc.isValid())
1947         Cxx1yLoc = DS->getBeginLoc();
1948       continue;
1949 
1950     default:
1951       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1952         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1953             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1954       }
1955       return false;
1956     }
1957   }
1958 
1959   return true;
1960 }
1961 
1962 /// Check that the given field is initialized within a constexpr constructor.
1963 ///
1964 /// \param Dcl The constexpr constructor being checked.
1965 /// \param Field The field being checked. This may be a member of an anonymous
1966 ///        struct or union nested within the class being checked.
1967 /// \param Inits All declarations, including anonymous struct/union members and
1968 ///        indirect members, for which any initialization was provided.
1969 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1970 ///        multiple notes for different members to the same error.
1971 /// \param Kind Whether we're diagnosing a constructor as written or determining
1972 ///        whether the formal requirements are satisfied.
1973 /// \return \c false if we're checking for validity and the constructor does
1974 ///         not satisfy the requirements on a constexpr constructor.
1975 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1976                                           const FunctionDecl *Dcl,
1977                                           FieldDecl *Field,
1978                                           llvm::SmallSet<Decl*, 16> &Inits,
1979                                           bool &Diagnosed,
1980                                           Sema::CheckConstexprKind Kind) {
1981   // In C++20 onwards, there's nothing to check for validity.
1982   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1983       SemaRef.getLangOpts().CPlusPlus20)
1984     return true;
1985 
1986   if (Field->isInvalidDecl())
1987     return true;
1988 
1989   if (Field->isUnnamedBitfield())
1990     return true;
1991 
1992   // Anonymous unions with no variant members and empty anonymous structs do not
1993   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1994   // indirect fields don't need initializing.
1995   if (Field->isAnonymousStructOrUnion() &&
1996       (Field->getType()->isUnionType()
1997            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1998            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1999     return true;
2000 
2001   if (!Inits.count(Field)) {
2002     if (Kind == Sema::CheckConstexprKind::Diagnose) {
2003       if (!Diagnosed) {
2004         SemaRef.Diag(Dcl->getLocation(),
2005                      SemaRef.getLangOpts().CPlusPlus20
2006                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2007                          : diag::ext_constexpr_ctor_missing_init);
2008         Diagnosed = true;
2009       }
2010       SemaRef.Diag(Field->getLocation(),
2011                    diag::note_constexpr_ctor_missing_init);
2012     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2013       return false;
2014     }
2015   } else if (Field->isAnonymousStructOrUnion()) {
2016     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2017     for (auto *I : RD->fields())
2018       // If an anonymous union contains an anonymous struct of which any member
2019       // is initialized, all members must be initialized.
2020       if (!RD->isUnion() || Inits.count(I))
2021         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2022                                            Kind))
2023           return false;
2024   }
2025   return true;
2026 }
2027 
2028 /// Check the provided statement is allowed in a constexpr function
2029 /// definition.
2030 static bool
2031 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2032                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2033                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2034                            SourceLocation &Cxx2bLoc,
2035                            Sema::CheckConstexprKind Kind) {
2036   // - its function-body shall be [...] a compound-statement that contains only
2037   switch (S->getStmtClass()) {
2038   case Stmt::NullStmtClass:
2039     //   - null statements,
2040     return true;
2041 
2042   case Stmt::DeclStmtClass:
2043     //   - static_assert-declarations
2044     //   - using-declarations,
2045     //   - using-directives,
2046     //   - typedef declarations and alias-declarations that do not define
2047     //     classes or enumerations,
2048     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2049       return false;
2050     return true;
2051 
2052   case Stmt::ReturnStmtClass:
2053     //   - and exactly one return statement;
2054     if (isa<CXXConstructorDecl>(Dcl)) {
2055       // C++1y allows return statements in constexpr constructors.
2056       if (!Cxx1yLoc.isValid())
2057         Cxx1yLoc = S->getBeginLoc();
2058       return true;
2059     }
2060 
2061     ReturnStmts.push_back(S->getBeginLoc());
2062     return true;
2063 
2064   case Stmt::AttributedStmtClass:
2065     // Attributes on a statement don't affect its formal kind and hence don't
2066     // affect its validity in a constexpr function.
2067     return CheckConstexprFunctionStmt(
2068         SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2069         Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2070 
2071   case Stmt::CompoundStmtClass: {
2072     // C++1y allows compound-statements.
2073     if (!Cxx1yLoc.isValid())
2074       Cxx1yLoc = S->getBeginLoc();
2075 
2076     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2077     for (auto *BodyIt : CompStmt->body()) {
2078       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2079                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2080         return false;
2081     }
2082     return true;
2083   }
2084 
2085   case Stmt::IfStmtClass: {
2086     // C++1y allows if-statements.
2087     if (!Cxx1yLoc.isValid())
2088       Cxx1yLoc = S->getBeginLoc();
2089 
2090     IfStmt *If = cast<IfStmt>(S);
2091     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2092                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2093       return false;
2094     if (If->getElse() &&
2095         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2096                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2097       return false;
2098     return true;
2099   }
2100 
2101   case Stmt::WhileStmtClass:
2102   case Stmt::DoStmtClass:
2103   case Stmt::ForStmtClass:
2104   case Stmt::CXXForRangeStmtClass:
2105   case Stmt::ContinueStmtClass:
2106     // C++1y allows all of these. We don't allow them as extensions in C++11,
2107     // because they don't make sense without variable mutation.
2108     if (!SemaRef.getLangOpts().CPlusPlus14)
2109       break;
2110     if (!Cxx1yLoc.isValid())
2111       Cxx1yLoc = S->getBeginLoc();
2112     for (Stmt *SubStmt : S->children()) {
2113       if (SubStmt &&
2114           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2115                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2116         return false;
2117     }
2118     return true;
2119 
2120   case Stmt::SwitchStmtClass:
2121   case Stmt::CaseStmtClass:
2122   case Stmt::DefaultStmtClass:
2123   case Stmt::BreakStmtClass:
2124     // C++1y allows switch-statements, and since they don't need variable
2125     // mutation, we can reasonably allow them in C++11 as an extension.
2126     if (!Cxx1yLoc.isValid())
2127       Cxx1yLoc = S->getBeginLoc();
2128     for (Stmt *SubStmt : S->children()) {
2129       if (SubStmt &&
2130           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2131                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2132         return false;
2133     }
2134     return true;
2135 
2136   case Stmt::LabelStmtClass:
2137   case Stmt::GotoStmtClass:
2138     if (Cxx2bLoc.isInvalid())
2139       Cxx2bLoc = S->getBeginLoc();
2140     for (Stmt *SubStmt : S->children()) {
2141       if (SubStmt &&
2142           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2143                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2144         return false;
2145     }
2146     return true;
2147 
2148   case Stmt::GCCAsmStmtClass:
2149   case Stmt::MSAsmStmtClass:
2150     // C++2a allows inline assembly statements.
2151   case Stmt::CXXTryStmtClass:
2152     if (Cxx2aLoc.isInvalid())
2153       Cxx2aLoc = S->getBeginLoc();
2154     for (Stmt *SubStmt : S->children()) {
2155       if (SubStmt &&
2156           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2157                                       Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2158         return false;
2159     }
2160     return true;
2161 
2162   case Stmt::CXXCatchStmtClass:
2163     // Do not bother checking the language mode (already covered by the
2164     // try block check).
2165     if (!CheckConstexprFunctionStmt(
2166             SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2167             Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2168       return false;
2169     return true;
2170 
2171   default:
2172     if (!isa<Expr>(S))
2173       break;
2174 
2175     // C++1y allows expression-statements.
2176     if (!Cxx1yLoc.isValid())
2177       Cxx1yLoc = S->getBeginLoc();
2178     return true;
2179   }
2180 
2181   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2182     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2183         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2184   }
2185   return false;
2186 }
2187 
2188 /// Check the body for the given constexpr function declaration only contains
2189 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2190 ///
2191 /// \return true if the body is OK, false if we have found or diagnosed a
2192 /// problem.
2193 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2194                                        Stmt *Body,
2195                                        Sema::CheckConstexprKind Kind) {
2196   SmallVector<SourceLocation, 4> ReturnStmts;
2197 
2198   if (isa<CXXTryStmt>(Body)) {
2199     // C++11 [dcl.constexpr]p3:
2200     //  The definition of a constexpr function shall satisfy the following
2201     //  constraints: [...]
2202     // - its function-body shall be = delete, = default, or a
2203     //   compound-statement
2204     //
2205     // C++11 [dcl.constexpr]p4:
2206     //  In the definition of a constexpr constructor, [...]
2207     // - its function-body shall not be a function-try-block;
2208     //
2209     // This restriction is lifted in C++2a, as long as inner statements also
2210     // apply the general constexpr rules.
2211     switch (Kind) {
2212     case Sema::CheckConstexprKind::CheckValid:
2213       if (!SemaRef.getLangOpts().CPlusPlus20)
2214         return false;
2215       break;
2216 
2217     case Sema::CheckConstexprKind::Diagnose:
2218       SemaRef.Diag(Body->getBeginLoc(),
2219            !SemaRef.getLangOpts().CPlusPlus20
2220                ? diag::ext_constexpr_function_try_block_cxx20
2221                : diag::warn_cxx17_compat_constexpr_function_try_block)
2222           << isa<CXXConstructorDecl>(Dcl);
2223       break;
2224     }
2225   }
2226 
2227   // - its function-body shall be [...] a compound-statement that contains only
2228   //   [... list of cases ...]
2229   //
2230   // Note that walking the children here is enough to properly check for
2231   // CompoundStmt and CXXTryStmt body.
2232   SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2233   for (Stmt *SubStmt : Body->children()) {
2234     if (SubStmt &&
2235         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2236                                     Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2237       return false;
2238   }
2239 
2240   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2241     // If this is only valid as an extension, report that we don't satisfy the
2242     // constraints of the current language.
2243     if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2b) ||
2244         (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2245         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2246       return false;
2247   } else if (Cxx2bLoc.isValid()) {
2248     SemaRef.Diag(Cxx2bLoc,
2249                  SemaRef.getLangOpts().CPlusPlus2b
2250                      ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2251                      : diag::ext_constexpr_body_invalid_stmt_cxx2b)
2252         << isa<CXXConstructorDecl>(Dcl);
2253   } else if (Cxx2aLoc.isValid()) {
2254     SemaRef.Diag(Cxx2aLoc,
2255          SemaRef.getLangOpts().CPlusPlus20
2256            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2257            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2258       << isa<CXXConstructorDecl>(Dcl);
2259   } else if (Cxx1yLoc.isValid()) {
2260     SemaRef.Diag(Cxx1yLoc,
2261          SemaRef.getLangOpts().CPlusPlus14
2262            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2263            : diag::ext_constexpr_body_invalid_stmt)
2264       << isa<CXXConstructorDecl>(Dcl);
2265   }
2266 
2267   if (const CXXConstructorDecl *Constructor
2268         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2269     const CXXRecordDecl *RD = Constructor->getParent();
2270     // DR1359:
2271     // - every non-variant non-static data member and base class sub-object
2272     //   shall be initialized;
2273     // DR1460:
2274     // - if the class is a union having variant members, exactly one of them
2275     //   shall be initialized;
2276     if (RD->isUnion()) {
2277       if (Constructor->getNumCtorInitializers() == 0 &&
2278           RD->hasVariantMembers()) {
2279         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2280           SemaRef.Diag(
2281               Dcl->getLocation(),
2282               SemaRef.getLangOpts().CPlusPlus20
2283                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2284                   : diag::ext_constexpr_union_ctor_no_init);
2285         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2286           return false;
2287         }
2288       }
2289     } else if (!Constructor->isDependentContext() &&
2290                !Constructor->isDelegatingConstructor()) {
2291       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2292 
2293       // Skip detailed checking if we have enough initializers, and we would
2294       // allow at most one initializer per member.
2295       bool AnyAnonStructUnionMembers = false;
2296       unsigned Fields = 0;
2297       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2298            E = RD->field_end(); I != E; ++I, ++Fields) {
2299         if (I->isAnonymousStructOrUnion()) {
2300           AnyAnonStructUnionMembers = true;
2301           break;
2302         }
2303       }
2304       // DR1460:
2305       // - if the class is a union-like class, but is not a union, for each of
2306       //   its anonymous union members having variant members, exactly one of
2307       //   them shall be initialized;
2308       if (AnyAnonStructUnionMembers ||
2309           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2310         // Check initialization of non-static data members. Base classes are
2311         // always initialized so do not need to be checked. Dependent bases
2312         // might not have initializers in the member initializer list.
2313         llvm::SmallSet<Decl*, 16> Inits;
2314         for (const auto *I: Constructor->inits()) {
2315           if (FieldDecl *FD = I->getMember())
2316             Inits.insert(FD);
2317           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2318             Inits.insert(ID->chain_begin(), ID->chain_end());
2319         }
2320 
2321         bool Diagnosed = false;
2322         for (auto *I : RD->fields())
2323           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2324                                              Kind))
2325             return false;
2326       }
2327     }
2328   } else {
2329     if (ReturnStmts.empty()) {
2330       // C++1y doesn't require constexpr functions to contain a 'return'
2331       // statement. We still do, unless the return type might be void, because
2332       // otherwise if there's no return statement, the function cannot
2333       // be used in a core constant expression.
2334       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2335                 (Dcl->getReturnType()->isVoidType() ||
2336                  Dcl->getReturnType()->isDependentType());
2337       switch (Kind) {
2338       case Sema::CheckConstexprKind::Diagnose:
2339         SemaRef.Diag(Dcl->getLocation(),
2340                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2341                         : diag::err_constexpr_body_no_return)
2342             << Dcl->isConsteval();
2343         if (!OK)
2344           return false;
2345         break;
2346 
2347       case Sema::CheckConstexprKind::CheckValid:
2348         // The formal requirements don't include this rule in C++14, even
2349         // though the "must be able to produce a constant expression" rules
2350         // still imply it in some cases.
2351         if (!SemaRef.getLangOpts().CPlusPlus14)
2352           return false;
2353         break;
2354       }
2355     } else if (ReturnStmts.size() > 1) {
2356       switch (Kind) {
2357       case Sema::CheckConstexprKind::Diagnose:
2358         SemaRef.Diag(
2359             ReturnStmts.back(),
2360             SemaRef.getLangOpts().CPlusPlus14
2361                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2362                 : diag::ext_constexpr_body_multiple_return);
2363         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2364           SemaRef.Diag(ReturnStmts[I],
2365                        diag::note_constexpr_body_previous_return);
2366         break;
2367 
2368       case Sema::CheckConstexprKind::CheckValid:
2369         if (!SemaRef.getLangOpts().CPlusPlus14)
2370           return false;
2371         break;
2372       }
2373     }
2374   }
2375 
2376   // C++11 [dcl.constexpr]p5:
2377   //   if no function argument values exist such that the function invocation
2378   //   substitution would produce a constant expression, the program is
2379   //   ill-formed; no diagnostic required.
2380   // C++11 [dcl.constexpr]p3:
2381   //   - every constructor call and implicit conversion used in initializing the
2382   //     return value shall be one of those allowed in a constant expression.
2383   // C++11 [dcl.constexpr]p4:
2384   //   - every constructor involved in initializing non-static data members and
2385   //     base class sub-objects shall be a constexpr constructor.
2386   //
2387   // Note that this rule is distinct from the "requirements for a constexpr
2388   // function", so is not checked in CheckValid mode.
2389   SmallVector<PartialDiagnosticAt, 8> Diags;
2390   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2391       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2392     SemaRef.Diag(Dcl->getLocation(),
2393                  diag::ext_constexpr_function_never_constant_expr)
2394         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2395     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2396       SemaRef.Diag(Diags[I].first, Diags[I].second);
2397     // Don't return false here: we allow this for compatibility in
2398     // system headers.
2399   }
2400 
2401   return true;
2402 }
2403 
2404 /// Get the class that is directly named by the current context. This is the
2405 /// class for which an unqualified-id in this scope could name a constructor
2406 /// or destructor.
2407 ///
2408 /// If the scope specifier denotes a class, this will be that class.
2409 /// If the scope specifier is empty, this will be the class whose
2410 /// member-specification we are currently within. Otherwise, there
2411 /// is no such class.
2412 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2413   assert(getLangOpts().CPlusPlus && "No class names in C!");
2414 
2415   if (SS && SS->isInvalid())
2416     return nullptr;
2417 
2418   if (SS && SS->isNotEmpty()) {
2419     DeclContext *DC = computeDeclContext(*SS, true);
2420     return dyn_cast_or_null<CXXRecordDecl>(DC);
2421   }
2422 
2423   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2424 }
2425 
2426 /// isCurrentClassName - Determine whether the identifier II is the
2427 /// name of the class type currently being defined. In the case of
2428 /// nested classes, this will only return true if II is the name of
2429 /// the innermost class.
2430 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2431                               const CXXScopeSpec *SS) {
2432   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2433   return CurDecl && &II == CurDecl->getIdentifier();
2434 }
2435 
2436 /// Determine whether the identifier II is a typo for the name of
2437 /// the class type currently being defined. If so, update it to the identifier
2438 /// that should have been used.
2439 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2440   assert(getLangOpts().CPlusPlus && "No class names in C!");
2441 
2442   if (!getLangOpts().SpellChecking)
2443     return false;
2444 
2445   CXXRecordDecl *CurDecl;
2446   if (SS && SS->isSet() && !SS->isInvalid()) {
2447     DeclContext *DC = computeDeclContext(*SS, true);
2448     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2449   } else
2450     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2451 
2452   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2453       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2454           < II->getLength()) {
2455     II = CurDecl->getIdentifier();
2456     return true;
2457   }
2458 
2459   return false;
2460 }
2461 
2462 /// Determine whether the given class is a base class of the given
2463 /// class, including looking at dependent bases.
2464 static bool findCircularInheritance(const CXXRecordDecl *Class,
2465                                     const CXXRecordDecl *Current) {
2466   SmallVector<const CXXRecordDecl*, 8> Queue;
2467 
2468   Class = Class->getCanonicalDecl();
2469   while (true) {
2470     for (const auto &I : Current->bases()) {
2471       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2472       if (!Base)
2473         continue;
2474 
2475       Base = Base->getDefinition();
2476       if (!Base)
2477         continue;
2478 
2479       if (Base->getCanonicalDecl() == Class)
2480         return true;
2481 
2482       Queue.push_back(Base);
2483     }
2484 
2485     if (Queue.empty())
2486       return false;
2487 
2488     Current = Queue.pop_back_val();
2489   }
2490 
2491   return false;
2492 }
2493 
2494 /// Check the validity of a C++ base class specifier.
2495 ///
2496 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2497 /// and returns NULL otherwise.
2498 CXXBaseSpecifier *
2499 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2500                          SourceRange SpecifierRange,
2501                          bool Virtual, AccessSpecifier Access,
2502                          TypeSourceInfo *TInfo,
2503                          SourceLocation EllipsisLoc) {
2504   // In HLSL, unspecified class access is public rather than private.
2505   if (getLangOpts().HLSL && Class->getTagKind() == TTK_Class &&
2506       Access == AS_none)
2507     Access = AS_public;
2508 
2509   QualType BaseType = TInfo->getType();
2510   if (BaseType->containsErrors()) {
2511     // Already emitted a diagnostic when parsing the error type.
2512     return nullptr;
2513   }
2514   // C++ [class.union]p1:
2515   //   A union shall not have base classes.
2516   if (Class->isUnion()) {
2517     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2518       << SpecifierRange;
2519     return nullptr;
2520   }
2521 
2522   if (EllipsisLoc.isValid() &&
2523       !TInfo->getType()->containsUnexpandedParameterPack()) {
2524     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2525       << TInfo->getTypeLoc().getSourceRange();
2526     EllipsisLoc = SourceLocation();
2527   }
2528 
2529   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2530 
2531   if (BaseType->isDependentType()) {
2532     // Make sure that we don't have circular inheritance among our dependent
2533     // bases. For non-dependent bases, the check for completeness below handles
2534     // this.
2535     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2536       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2537           ((BaseDecl = BaseDecl->getDefinition()) &&
2538            findCircularInheritance(Class, BaseDecl))) {
2539         Diag(BaseLoc, diag::err_circular_inheritance)
2540           << BaseType << Context.getTypeDeclType(Class);
2541 
2542         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2543           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2544             << BaseType;
2545 
2546         return nullptr;
2547       }
2548     }
2549 
2550     // Make sure that we don't make an ill-formed AST where the type of the
2551     // Class is non-dependent and its attached base class specifier is an
2552     // dependent type, which violates invariants in many clang code paths (e.g.
2553     // constexpr evaluator). If this case happens (in errory-recovery mode), we
2554     // explicitly mark the Class decl invalid. The diagnostic was already
2555     // emitted.
2556     if (!Class->getTypeForDecl()->isDependentType())
2557       Class->setInvalidDecl();
2558     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2559                                           Class->getTagKind() == TTK_Class,
2560                                           Access, TInfo, EllipsisLoc);
2561   }
2562 
2563   // Base specifiers must be record types.
2564   if (!BaseType->isRecordType()) {
2565     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2566     return nullptr;
2567   }
2568 
2569   // C++ [class.union]p1:
2570   //   A union shall not be used as a base class.
2571   if (BaseType->isUnionType()) {
2572     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2573     return nullptr;
2574   }
2575 
2576   // For the MS ABI, propagate DLL attributes to base class templates.
2577   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2578     if (Attr *ClassAttr = getDLLAttr(Class)) {
2579       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2580               BaseType->getAsCXXRecordDecl())) {
2581         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2582                                             BaseLoc);
2583       }
2584     }
2585   }
2586 
2587   // C++ [class.derived]p2:
2588   //   The class-name in a base-specifier shall not be an incompletely
2589   //   defined class.
2590   if (RequireCompleteType(BaseLoc, BaseType,
2591                           diag::err_incomplete_base_class, SpecifierRange)) {
2592     Class->setInvalidDecl();
2593     return nullptr;
2594   }
2595 
2596   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2597   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2598   assert(BaseDecl && "Record type has no declaration");
2599   BaseDecl = BaseDecl->getDefinition();
2600   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2601   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2602   assert(CXXBaseDecl && "Base type is not a C++ type");
2603 
2604   // Microsoft docs say:
2605   // "If a base-class has a code_seg attribute, derived classes must have the
2606   // same attribute."
2607   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2608   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2609   if ((DerivedCSA || BaseCSA) &&
2610       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2611     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2612     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2613       << CXXBaseDecl;
2614     return nullptr;
2615   }
2616 
2617   // A class which contains a flexible array member is not suitable for use as a
2618   // base class:
2619   //   - If the layout determines that a base comes before another base,
2620   //     the flexible array member would index into the subsequent base.
2621   //   - If the layout determines that base comes before the derived class,
2622   //     the flexible array member would index into the derived class.
2623   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2624     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2625       << CXXBaseDecl->getDeclName();
2626     return nullptr;
2627   }
2628 
2629   // C++ [class]p3:
2630   //   If a class is marked final and it appears as a base-type-specifier in
2631   //   base-clause, the program is ill-formed.
2632   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2633     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2634       << CXXBaseDecl->getDeclName()
2635       << FA->isSpelledAsSealed();
2636     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2637         << CXXBaseDecl->getDeclName() << FA->getRange();
2638     return nullptr;
2639   }
2640 
2641   if (BaseDecl->isInvalidDecl())
2642     Class->setInvalidDecl();
2643 
2644   // Create the base specifier.
2645   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2646                                         Class->getTagKind() == TTK_Class,
2647                                         Access, TInfo, EllipsisLoc);
2648 }
2649 
2650 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2651 /// one entry in the base class list of a class specifier, for
2652 /// example:
2653 ///    class foo : public bar, virtual private baz {
2654 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2655 BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2656                                     const ParsedAttributesView &Attributes,
2657                                     bool Virtual, AccessSpecifier Access,
2658                                     ParsedType basetype, SourceLocation BaseLoc,
2659                                     SourceLocation EllipsisLoc) {
2660   if (!classdecl)
2661     return true;
2662 
2663   AdjustDeclIfTemplate(classdecl);
2664   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2665   if (!Class)
2666     return true;
2667 
2668   // We haven't yet attached the base specifiers.
2669   Class->setIsParsingBaseSpecifiers();
2670 
2671   // We do not support any C++11 attributes on base-specifiers yet.
2672   // Diagnose any attributes we see.
2673   for (const ParsedAttr &AL : Attributes) {
2674     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2675       continue;
2676     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2677                           ? (unsigned)diag::warn_unknown_attribute_ignored
2678                           : (unsigned)diag::err_base_specifier_attribute)
2679         << AL << AL.getRange();
2680   }
2681 
2682   TypeSourceInfo *TInfo = nullptr;
2683   GetTypeFromParser(basetype, &TInfo);
2684 
2685   if (EllipsisLoc.isInvalid() &&
2686       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2687                                       UPPC_BaseType))
2688     return true;
2689 
2690   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2691                                                       Virtual, Access, TInfo,
2692                                                       EllipsisLoc))
2693     return BaseSpec;
2694   else
2695     Class->setInvalidDecl();
2696 
2697   return true;
2698 }
2699 
2700 /// Use small set to collect indirect bases.  As this is only used
2701 /// locally, there's no need to abstract the small size parameter.
2702 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2703 
2704 /// Recursively add the bases of Type.  Don't add Type itself.
2705 static void
2706 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2707                   const QualType &Type)
2708 {
2709   // Even though the incoming type is a base, it might not be
2710   // a class -- it could be a template parm, for instance.
2711   if (auto Rec = Type->getAs<RecordType>()) {
2712     auto Decl = Rec->getAsCXXRecordDecl();
2713 
2714     // Iterate over its bases.
2715     for (const auto &BaseSpec : Decl->bases()) {
2716       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2717         .getUnqualifiedType();
2718       if (Set.insert(Base).second)
2719         // If we've not already seen it, recurse.
2720         NoteIndirectBases(Context, Set, Base);
2721     }
2722   }
2723 }
2724 
2725 /// Performs the actual work of attaching the given base class
2726 /// specifiers to a C++ class.
2727 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2728                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2729  if (Bases.empty())
2730     return false;
2731 
2732   // Used to keep track of which base types we have already seen, so
2733   // that we can properly diagnose redundant direct base types. Note
2734   // that the key is always the unqualified canonical type of the base
2735   // class.
2736   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2737 
2738   // Used to track indirect bases so we can see if a direct base is
2739   // ambiguous.
2740   IndirectBaseSet IndirectBaseTypes;
2741 
2742   // Copy non-redundant base specifiers into permanent storage.
2743   unsigned NumGoodBases = 0;
2744   bool Invalid = false;
2745   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2746     QualType NewBaseType
2747       = Context.getCanonicalType(Bases[idx]->getType());
2748     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2749 
2750     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2751     if (KnownBase) {
2752       // C++ [class.mi]p3:
2753       //   A class shall not be specified as a direct base class of a
2754       //   derived class more than once.
2755       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2756           << KnownBase->getType() << Bases[idx]->getSourceRange();
2757 
2758       // Delete the duplicate base class specifier; we're going to
2759       // overwrite its pointer later.
2760       Context.Deallocate(Bases[idx]);
2761 
2762       Invalid = true;
2763     } else {
2764       // Okay, add this new base class.
2765       KnownBase = Bases[idx];
2766       Bases[NumGoodBases++] = Bases[idx];
2767 
2768       if (NewBaseType->isDependentType())
2769         continue;
2770       // Note this base's direct & indirect bases, if there could be ambiguity.
2771       if (Bases.size() > 1)
2772         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2773 
2774       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2775         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2776         if (Class->isInterface() &&
2777               (!RD->isInterfaceLike() ||
2778                KnownBase->getAccessSpecifier() != AS_public)) {
2779           // The Microsoft extension __interface does not permit bases that
2780           // are not themselves public interfaces.
2781           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2782               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2783               << RD->getSourceRange();
2784           Invalid = true;
2785         }
2786         if (RD->hasAttr<WeakAttr>())
2787           Class->addAttr(WeakAttr::CreateImplicit(Context));
2788       }
2789     }
2790   }
2791 
2792   // Attach the remaining base class specifiers to the derived class.
2793   Class->setBases(Bases.data(), NumGoodBases);
2794 
2795   // Check that the only base classes that are duplicate are virtual.
2796   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2797     // Check whether this direct base is inaccessible due to ambiguity.
2798     QualType BaseType = Bases[idx]->getType();
2799 
2800     // Skip all dependent types in templates being used as base specifiers.
2801     // Checks below assume that the base specifier is a CXXRecord.
2802     if (BaseType->isDependentType())
2803       continue;
2804 
2805     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2806       .getUnqualifiedType();
2807 
2808     if (IndirectBaseTypes.count(CanonicalBase)) {
2809       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2810                          /*DetectVirtual=*/true);
2811       bool found
2812         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2813       assert(found);
2814       (void)found;
2815 
2816       if (Paths.isAmbiguous(CanonicalBase))
2817         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2818             << BaseType << getAmbiguousPathsDisplayString(Paths)
2819             << Bases[idx]->getSourceRange();
2820       else
2821         assert(Bases[idx]->isVirtual());
2822     }
2823 
2824     // Delete the base class specifier, since its data has been copied
2825     // into the CXXRecordDecl.
2826     Context.Deallocate(Bases[idx]);
2827   }
2828 
2829   return Invalid;
2830 }
2831 
2832 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2833 /// class, after checking whether there are any duplicate base
2834 /// classes.
2835 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2836                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2837   if (!ClassDecl || Bases.empty())
2838     return;
2839 
2840   AdjustDeclIfTemplate(ClassDecl);
2841   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2842 }
2843 
2844 /// Determine whether the type \p Derived is a C++ class that is
2845 /// derived from the type \p Base.
2846 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2847   if (!getLangOpts().CPlusPlus)
2848     return false;
2849 
2850   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2851   if (!DerivedRD)
2852     return false;
2853 
2854   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2855   if (!BaseRD)
2856     return false;
2857 
2858   // If either the base or the derived type is invalid, don't try to
2859   // check whether one is derived from the other.
2860   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2861     return false;
2862 
2863   // FIXME: In a modules build, do we need the entire path to be visible for us
2864   // to be able to use the inheritance relationship?
2865   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2866     return false;
2867 
2868   return DerivedRD->isDerivedFrom(BaseRD);
2869 }
2870 
2871 /// Determine whether the type \p Derived is a C++ class that is
2872 /// derived from the type \p Base.
2873 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2874                          CXXBasePaths &Paths) {
2875   if (!getLangOpts().CPlusPlus)
2876     return false;
2877 
2878   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2879   if (!DerivedRD)
2880     return false;
2881 
2882   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2883   if (!BaseRD)
2884     return false;
2885 
2886   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2887     return false;
2888 
2889   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2890 }
2891 
2892 static void BuildBasePathArray(const CXXBasePath &Path,
2893                                CXXCastPath &BasePathArray) {
2894   // We first go backward and check if we have a virtual base.
2895   // FIXME: It would be better if CXXBasePath had the base specifier for
2896   // the nearest virtual base.
2897   unsigned Start = 0;
2898   for (unsigned I = Path.size(); I != 0; --I) {
2899     if (Path[I - 1].Base->isVirtual()) {
2900       Start = I - 1;
2901       break;
2902     }
2903   }
2904 
2905   // Now add all bases.
2906   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2907     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2908 }
2909 
2910 
2911 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2912                               CXXCastPath &BasePathArray) {
2913   assert(BasePathArray.empty() && "Base path array must be empty!");
2914   assert(Paths.isRecordingPaths() && "Must record paths!");
2915   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2916 }
2917 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2918 /// conversion (where Derived and Base are class types) is
2919 /// well-formed, meaning that the conversion is unambiguous (and
2920 /// that all of the base classes are accessible). Returns true
2921 /// and emits a diagnostic if the code is ill-formed, returns false
2922 /// otherwise. Loc is the location where this routine should point to
2923 /// if there is an error, and Range is the source range to highlight
2924 /// if there is an error.
2925 ///
2926 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2927 /// diagnostic for the respective type of error will be suppressed, but the
2928 /// check for ill-formed code will still be performed.
2929 bool
2930 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2931                                    unsigned InaccessibleBaseID,
2932                                    unsigned AmbiguousBaseConvID,
2933                                    SourceLocation Loc, SourceRange Range,
2934                                    DeclarationName Name,
2935                                    CXXCastPath *BasePath,
2936                                    bool IgnoreAccess) {
2937   // First, determine whether the path from Derived to Base is
2938   // ambiguous. This is slightly more expensive than checking whether
2939   // the Derived to Base conversion exists, because here we need to
2940   // explore multiple paths to determine if there is an ambiguity.
2941   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2942                      /*DetectVirtual=*/false);
2943   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2944   if (!DerivationOkay)
2945     return true;
2946 
2947   const CXXBasePath *Path = nullptr;
2948   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2949     Path = &Paths.front();
2950 
2951   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2952   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2953   // user to access such bases.
2954   if (!Path && getLangOpts().MSVCCompat) {
2955     for (const CXXBasePath &PossiblePath : Paths) {
2956       if (PossiblePath.size() == 1) {
2957         Path = &PossiblePath;
2958         if (AmbiguousBaseConvID)
2959           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2960               << Base << Derived << Range;
2961         break;
2962       }
2963     }
2964   }
2965 
2966   if (Path) {
2967     if (!IgnoreAccess) {
2968       // Check that the base class can be accessed.
2969       switch (
2970           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2971       case AR_inaccessible:
2972         return true;
2973       case AR_accessible:
2974       case AR_dependent:
2975       case AR_delayed:
2976         break;
2977       }
2978     }
2979 
2980     // Build a base path if necessary.
2981     if (BasePath)
2982       ::BuildBasePathArray(*Path, *BasePath);
2983     return false;
2984   }
2985 
2986   if (AmbiguousBaseConvID) {
2987     // We know that the derived-to-base conversion is ambiguous, and
2988     // we're going to produce a diagnostic. Perform the derived-to-base
2989     // search just one more time to compute all of the possible paths so
2990     // that we can print them out. This is more expensive than any of
2991     // the previous derived-to-base checks we've done, but at this point
2992     // performance isn't as much of an issue.
2993     Paths.clear();
2994     Paths.setRecordingPaths(true);
2995     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2996     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2997     (void)StillOkay;
2998 
2999     // Build up a textual representation of the ambiguous paths, e.g.,
3000     // D -> B -> A, that will be used to illustrate the ambiguous
3001     // conversions in the diagnostic. We only print one of the paths
3002     // to each base class subobject.
3003     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3004 
3005     Diag(Loc, AmbiguousBaseConvID)
3006     << Derived << Base << PathDisplayStr << Range << Name;
3007   }
3008   return true;
3009 }
3010 
3011 bool
3012 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3013                                    SourceLocation Loc, SourceRange Range,
3014                                    CXXCastPath *BasePath,
3015                                    bool IgnoreAccess) {
3016   return CheckDerivedToBaseConversion(
3017       Derived, Base, diag::err_upcast_to_inaccessible_base,
3018       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3019       BasePath, IgnoreAccess);
3020 }
3021 
3022 
3023 /// Builds a string representing ambiguous paths from a
3024 /// specific derived class to different subobjects of the same base
3025 /// class.
3026 ///
3027 /// This function builds a string that can be used in error messages
3028 /// to show the different paths that one can take through the
3029 /// inheritance hierarchy to go from the derived class to different
3030 /// subobjects of a base class. The result looks something like this:
3031 /// @code
3032 /// struct D -> struct B -> struct A
3033 /// struct D -> struct C -> struct A
3034 /// @endcode
3035 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3036   std::string PathDisplayStr;
3037   std::set<unsigned> DisplayedPaths;
3038   for (CXXBasePaths::paths_iterator Path = Paths.begin();
3039        Path != Paths.end(); ++Path) {
3040     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3041       // We haven't displayed a path to this particular base
3042       // class subobject yet.
3043       PathDisplayStr += "\n    ";
3044       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3045       for (CXXBasePath::const_iterator Element = Path->begin();
3046            Element != Path->end(); ++Element)
3047         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3048     }
3049   }
3050 
3051   return PathDisplayStr;
3052 }
3053 
3054 //===----------------------------------------------------------------------===//
3055 // C++ class member Handling
3056 //===----------------------------------------------------------------------===//
3057 
3058 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3059 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3060                                 SourceLocation ColonLoc,
3061                                 const ParsedAttributesView &Attrs) {
3062   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3063   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3064                                                   ASLoc, ColonLoc);
3065   CurContext->addHiddenDecl(ASDecl);
3066   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3067 }
3068 
3069 /// CheckOverrideControl - Check C++11 override control semantics.
3070 void Sema::CheckOverrideControl(NamedDecl *D) {
3071   if (D->isInvalidDecl())
3072     return;
3073 
3074   // We only care about "override" and "final" declarations.
3075   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3076     return;
3077 
3078   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3079 
3080   // We can't check dependent instance methods.
3081   if (MD && MD->isInstance() &&
3082       (MD->getParent()->hasAnyDependentBases() ||
3083        MD->getType()->isDependentType()))
3084     return;
3085 
3086   if (MD && !MD->isVirtual()) {
3087     // If we have a non-virtual method, check if if hides a virtual method.
3088     // (In that case, it's most likely the method has the wrong type.)
3089     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3090     FindHiddenVirtualMethods(MD, OverloadedMethods);
3091 
3092     if (!OverloadedMethods.empty()) {
3093       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3094         Diag(OA->getLocation(),
3095              diag::override_keyword_hides_virtual_member_function)
3096           << "override" << (OverloadedMethods.size() > 1);
3097       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3098         Diag(FA->getLocation(),
3099              diag::override_keyword_hides_virtual_member_function)
3100           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3101           << (OverloadedMethods.size() > 1);
3102       }
3103       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3104       MD->setInvalidDecl();
3105       return;
3106     }
3107     // Fall through into the general case diagnostic.
3108     // FIXME: We might want to attempt typo correction here.
3109   }
3110 
3111   if (!MD || !MD->isVirtual()) {
3112     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3113       Diag(OA->getLocation(),
3114            diag::override_keyword_only_allowed_on_virtual_member_functions)
3115         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3116       D->dropAttr<OverrideAttr>();
3117     }
3118     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3119       Diag(FA->getLocation(),
3120            diag::override_keyword_only_allowed_on_virtual_member_functions)
3121         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3122         << FixItHint::CreateRemoval(FA->getLocation());
3123       D->dropAttr<FinalAttr>();
3124     }
3125     return;
3126   }
3127 
3128   // C++11 [class.virtual]p5:
3129   //   If a function is marked with the virt-specifier override and
3130   //   does not override a member function of a base class, the program is
3131   //   ill-formed.
3132   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3133   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3134     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3135       << MD->getDeclName();
3136 }
3137 
3138 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3139   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3140     return;
3141   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3142   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3143     return;
3144 
3145   SourceLocation Loc = MD->getLocation();
3146   SourceLocation SpellingLoc = Loc;
3147   if (getSourceManager().isMacroArgExpansion(Loc))
3148     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3149   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3150   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3151       return;
3152 
3153   if (MD->size_overridden_methods() > 0) {
3154     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3155       unsigned DiagID =
3156           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3157               ? DiagInconsistent
3158               : DiagSuggest;
3159       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3160       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3161       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3162     };
3163     if (isa<CXXDestructorDecl>(MD))
3164       EmitDiag(
3165           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3166           diag::warn_suggest_destructor_marked_not_override_overriding);
3167     else
3168       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3169                diag::warn_suggest_function_marked_not_override_overriding);
3170   }
3171 }
3172 
3173 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3174 /// function overrides a virtual member function marked 'final', according to
3175 /// C++11 [class.virtual]p4.
3176 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3177                                                   const CXXMethodDecl *Old) {
3178   FinalAttr *FA = Old->getAttr<FinalAttr>();
3179   if (!FA)
3180     return false;
3181 
3182   Diag(New->getLocation(), diag::err_final_function_overridden)
3183     << New->getDeclName()
3184     << FA->isSpelledAsSealed();
3185   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3186   return true;
3187 }
3188 
3189 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3190   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3191   // FIXME: Destruction of ObjC lifetime types has side-effects.
3192   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3193     return !RD->isCompleteDefinition() ||
3194            !RD->hasTrivialDefaultConstructor() ||
3195            !RD->hasTrivialDestructor();
3196   return false;
3197 }
3198 
3199 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3200   ParsedAttributesView::const_iterator Itr =
3201       llvm::find_if(list, [](const ParsedAttr &AL) {
3202         return AL.isDeclspecPropertyAttribute();
3203       });
3204   if (Itr != list.end())
3205     return &*Itr;
3206   return nullptr;
3207 }
3208 
3209 // Check if there is a field shadowing.
3210 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3211                                       DeclarationName FieldName,
3212                                       const CXXRecordDecl *RD,
3213                                       bool DeclIsField) {
3214   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3215     return;
3216 
3217   // To record a shadowed field in a base
3218   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3219   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3220                            CXXBasePath &Path) {
3221     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3222     // Record an ambiguous path directly
3223     if (Bases.find(Base) != Bases.end())
3224       return true;
3225     for (const auto Field : Base->lookup(FieldName)) {
3226       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3227           Field->getAccess() != AS_private) {
3228         assert(Field->getAccess() != AS_none);
3229         assert(Bases.find(Base) == Bases.end());
3230         Bases[Base] = Field;
3231         return true;
3232       }
3233     }
3234     return false;
3235   };
3236 
3237   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3238                      /*DetectVirtual=*/true);
3239   if (!RD->lookupInBases(FieldShadowed, Paths))
3240     return;
3241 
3242   for (const auto &P : Paths) {
3243     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3244     auto It = Bases.find(Base);
3245     // Skip duplicated bases
3246     if (It == Bases.end())
3247       continue;
3248     auto BaseField = It->second;
3249     assert(BaseField->getAccess() != AS_private);
3250     if (AS_none !=
3251         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3252       Diag(Loc, diag::warn_shadow_field)
3253         << FieldName << RD << Base << DeclIsField;
3254       Diag(BaseField->getLocation(), diag::note_shadow_field);
3255       Bases.erase(It);
3256     }
3257   }
3258 }
3259 
3260 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3261 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3262 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3263 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3264 /// present (but parsing it has been deferred).
3265 NamedDecl *
3266 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3267                                MultiTemplateParamsArg TemplateParameterLists,
3268                                Expr *BW, const VirtSpecifiers &VS,
3269                                InClassInitStyle InitStyle) {
3270   const DeclSpec &DS = D.getDeclSpec();
3271   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3272   DeclarationName Name = NameInfo.getName();
3273   SourceLocation Loc = NameInfo.getLoc();
3274 
3275   // For anonymous bitfields, the location should point to the type.
3276   if (Loc.isInvalid())
3277     Loc = D.getBeginLoc();
3278 
3279   Expr *BitWidth = static_cast<Expr*>(BW);
3280 
3281   assert(isa<CXXRecordDecl>(CurContext));
3282   assert(!DS.isFriendSpecified());
3283 
3284   bool isFunc = D.isDeclarationOfFunction();
3285   const ParsedAttr *MSPropertyAttr =
3286       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3287 
3288   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3289     // The Microsoft extension __interface only permits public member functions
3290     // and prohibits constructors, destructors, operators, non-public member
3291     // functions, static methods and data members.
3292     unsigned InvalidDecl;
3293     bool ShowDeclName = true;
3294     if (!isFunc &&
3295         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3296       InvalidDecl = 0;
3297     else if (!isFunc)
3298       InvalidDecl = 1;
3299     else if (AS != AS_public)
3300       InvalidDecl = 2;
3301     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3302       InvalidDecl = 3;
3303     else switch (Name.getNameKind()) {
3304       case DeclarationName::CXXConstructorName:
3305         InvalidDecl = 4;
3306         ShowDeclName = false;
3307         break;
3308 
3309       case DeclarationName::CXXDestructorName:
3310         InvalidDecl = 5;
3311         ShowDeclName = false;
3312         break;
3313 
3314       case DeclarationName::CXXOperatorName:
3315       case DeclarationName::CXXConversionFunctionName:
3316         InvalidDecl = 6;
3317         break;
3318 
3319       default:
3320         InvalidDecl = 0;
3321         break;
3322     }
3323 
3324     if (InvalidDecl) {
3325       if (ShowDeclName)
3326         Diag(Loc, diag::err_invalid_member_in_interface)
3327           << (InvalidDecl-1) << Name;
3328       else
3329         Diag(Loc, diag::err_invalid_member_in_interface)
3330           << (InvalidDecl-1) << "";
3331       return nullptr;
3332     }
3333   }
3334 
3335   // C++ 9.2p6: A member shall not be declared to have automatic storage
3336   // duration (auto, register) or with the extern storage-class-specifier.
3337   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3338   // data members and cannot be applied to names declared const or static,
3339   // and cannot be applied to reference members.
3340   switch (DS.getStorageClassSpec()) {
3341   case DeclSpec::SCS_unspecified:
3342   case DeclSpec::SCS_typedef:
3343   case DeclSpec::SCS_static:
3344     break;
3345   case DeclSpec::SCS_mutable:
3346     if (isFunc) {
3347       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3348 
3349       // FIXME: It would be nicer if the keyword was ignored only for this
3350       // declarator. Otherwise we could get follow-up errors.
3351       D.getMutableDeclSpec().ClearStorageClassSpecs();
3352     }
3353     break;
3354   default:
3355     Diag(DS.getStorageClassSpecLoc(),
3356          diag::err_storageclass_invalid_for_member);
3357     D.getMutableDeclSpec().ClearStorageClassSpecs();
3358     break;
3359   }
3360 
3361   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3362                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3363                       !isFunc);
3364 
3365   if (DS.hasConstexprSpecifier() && isInstField) {
3366     SemaDiagnosticBuilder B =
3367         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3368     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3369     if (InitStyle == ICIS_NoInit) {
3370       B << 0 << 0;
3371       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3372         B << FixItHint::CreateRemoval(ConstexprLoc);
3373       else {
3374         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3375         D.getMutableDeclSpec().ClearConstexprSpec();
3376         const char *PrevSpec;
3377         unsigned DiagID;
3378         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3379             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3380         (void)Failed;
3381         assert(!Failed && "Making a constexpr member const shouldn't fail");
3382       }
3383     } else {
3384       B << 1;
3385       const char *PrevSpec;
3386       unsigned DiagID;
3387       if (D.getMutableDeclSpec().SetStorageClassSpec(
3388           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3389           Context.getPrintingPolicy())) {
3390         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3391                "This is the only DeclSpec that should fail to be applied");
3392         B << 1;
3393       } else {
3394         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3395         isInstField = false;
3396       }
3397     }
3398   }
3399 
3400   NamedDecl *Member;
3401   if (isInstField) {
3402     CXXScopeSpec &SS = D.getCXXScopeSpec();
3403 
3404     // Data members must have identifiers for names.
3405     if (!Name.isIdentifier()) {
3406       Diag(Loc, diag::err_bad_variable_name)
3407         << Name;
3408       return nullptr;
3409     }
3410 
3411     IdentifierInfo *II = Name.getAsIdentifierInfo();
3412 
3413     // Member field could not be with "template" keyword.
3414     // So TemplateParameterLists should be empty in this case.
3415     if (TemplateParameterLists.size()) {
3416       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3417       if (TemplateParams->size()) {
3418         // There is no such thing as a member field template.
3419         Diag(D.getIdentifierLoc(), diag::err_template_member)
3420             << II
3421             << SourceRange(TemplateParams->getTemplateLoc(),
3422                 TemplateParams->getRAngleLoc());
3423       } else {
3424         // There is an extraneous 'template<>' for this member.
3425         Diag(TemplateParams->getTemplateLoc(),
3426             diag::err_template_member_noparams)
3427             << II
3428             << SourceRange(TemplateParams->getTemplateLoc(),
3429                 TemplateParams->getRAngleLoc());
3430       }
3431       return nullptr;
3432     }
3433 
3434     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3435       Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3436           << II
3437           << SourceRange(D.getName().TemplateId->LAngleLoc,
3438                          D.getName().TemplateId->RAngleLoc)
3439           << D.getName().TemplateId->LAngleLoc;
3440       D.SetIdentifier(II, Loc);
3441     }
3442 
3443     if (SS.isSet() && !SS.isInvalid()) {
3444       // The user provided a superfluous scope specifier inside a class
3445       // definition:
3446       //
3447       // class X {
3448       //   int X::member;
3449       // };
3450       if (DeclContext *DC = computeDeclContext(SS, false))
3451         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3452                                      D.getName().getKind() ==
3453                                          UnqualifiedIdKind::IK_TemplateId);
3454       else
3455         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3456           << Name << SS.getRange();
3457 
3458       SS.clear();
3459     }
3460 
3461     if (MSPropertyAttr) {
3462       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3463                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3464       if (!Member)
3465         return nullptr;
3466       isInstField = false;
3467     } else {
3468       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3469                                 BitWidth, InitStyle, AS);
3470       if (!Member)
3471         return nullptr;
3472     }
3473 
3474     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3475   } else {
3476     Member = HandleDeclarator(S, D, TemplateParameterLists);
3477     if (!Member)
3478       return nullptr;
3479 
3480     // Non-instance-fields can't have a bitfield.
3481     if (BitWidth) {
3482       if (Member->isInvalidDecl()) {
3483         // don't emit another diagnostic.
3484       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3485         // C++ 9.6p3: A bit-field shall not be a static member.
3486         // "static member 'A' cannot be a bit-field"
3487         Diag(Loc, diag::err_static_not_bitfield)
3488           << Name << BitWidth->getSourceRange();
3489       } else if (isa<TypedefDecl>(Member)) {
3490         // "typedef member 'x' cannot be a bit-field"
3491         Diag(Loc, diag::err_typedef_not_bitfield)
3492           << Name << BitWidth->getSourceRange();
3493       } else {
3494         // A function typedef ("typedef int f(); f a;").
3495         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3496         Diag(Loc, diag::err_not_integral_type_bitfield)
3497           << Name << cast<ValueDecl>(Member)->getType()
3498           << BitWidth->getSourceRange();
3499       }
3500 
3501       BitWidth = nullptr;
3502       Member->setInvalidDecl();
3503     }
3504 
3505     NamedDecl *NonTemplateMember = Member;
3506     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3507       NonTemplateMember = FunTmpl->getTemplatedDecl();
3508     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3509       NonTemplateMember = VarTmpl->getTemplatedDecl();
3510 
3511     Member->setAccess(AS);
3512 
3513     // If we have declared a member function template or static data member
3514     // template, set the access of the templated declaration as well.
3515     if (NonTemplateMember != Member)
3516       NonTemplateMember->setAccess(AS);
3517 
3518     // C++ [temp.deduct.guide]p3:
3519     //   A deduction guide [...] for a member class template [shall be
3520     //   declared] with the same access [as the template].
3521     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3522       auto *TD = DG->getDeducedTemplate();
3523       // Access specifiers are only meaningful if both the template and the
3524       // deduction guide are from the same scope.
3525       if (AS != TD->getAccess() &&
3526           TD->getDeclContext()->getRedeclContext()->Equals(
3527               DG->getDeclContext()->getRedeclContext())) {
3528         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3529         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3530             << TD->getAccess();
3531         const AccessSpecDecl *LastAccessSpec = nullptr;
3532         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3533           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3534             LastAccessSpec = AccessSpec;
3535         }
3536         assert(LastAccessSpec && "differing access with no access specifier");
3537         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3538             << AS;
3539       }
3540     }
3541   }
3542 
3543   if (VS.isOverrideSpecified())
3544     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3545                                          AttributeCommonInfo::AS_Keyword));
3546   if (VS.isFinalSpecified())
3547     Member->addAttr(FinalAttr::Create(
3548         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3549         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3550 
3551   if (VS.getLastLocation().isValid()) {
3552     // Update the end location of a method that has a virt-specifiers.
3553     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3554       MD->setRangeEnd(VS.getLastLocation());
3555   }
3556 
3557   CheckOverrideControl(Member);
3558 
3559   assert((Name || isInstField) && "No identifier for non-field ?");
3560 
3561   if (isInstField) {
3562     FieldDecl *FD = cast<FieldDecl>(Member);
3563     FieldCollector->Add(FD);
3564 
3565     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3566       // Remember all explicit private FieldDecls that have a name, no side
3567       // effects and are not part of a dependent type declaration.
3568       if (!FD->isImplicit() && FD->getDeclName() &&
3569           FD->getAccess() == AS_private &&
3570           !FD->hasAttr<UnusedAttr>() &&
3571           !FD->getParent()->isDependentContext() &&
3572           !InitializationHasSideEffects(*FD))
3573         UnusedPrivateFields.insert(FD);
3574     }
3575   }
3576 
3577   return Member;
3578 }
3579 
3580 namespace {
3581   class UninitializedFieldVisitor
3582       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3583     Sema &S;
3584     // List of Decls to generate a warning on.  Also remove Decls that become
3585     // initialized.
3586     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3587     // List of base classes of the record.  Classes are removed after their
3588     // initializers.
3589     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3590     // Vector of decls to be removed from the Decl set prior to visiting the
3591     // nodes.  These Decls may have been initialized in the prior initializer.
3592     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3593     // If non-null, add a note to the warning pointing back to the constructor.
3594     const CXXConstructorDecl *Constructor;
3595     // Variables to hold state when processing an initializer list.  When
3596     // InitList is true, special case initialization of FieldDecls matching
3597     // InitListFieldDecl.
3598     bool InitList;
3599     FieldDecl *InitListFieldDecl;
3600     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3601 
3602   public:
3603     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3604     UninitializedFieldVisitor(Sema &S,
3605                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3606                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3607       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3608         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3609 
3610     // Returns true if the use of ME is not an uninitialized use.
3611     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3612                                          bool CheckReferenceOnly) {
3613       llvm::SmallVector<FieldDecl*, 4> Fields;
3614       bool ReferenceField = false;
3615       while (ME) {
3616         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3617         if (!FD)
3618           return false;
3619         Fields.push_back(FD);
3620         if (FD->getType()->isReferenceType())
3621           ReferenceField = true;
3622         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3623       }
3624 
3625       // Binding a reference to an uninitialized field is not an
3626       // uninitialized use.
3627       if (CheckReferenceOnly && !ReferenceField)
3628         return true;
3629 
3630       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3631       // Discard the first field since it is the field decl that is being
3632       // initialized.
3633       for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3634         UsedFieldIndex.push_back(FD->getFieldIndex());
3635 
3636       for (auto UsedIter = UsedFieldIndex.begin(),
3637                 UsedEnd = UsedFieldIndex.end(),
3638                 OrigIter = InitFieldIndex.begin(),
3639                 OrigEnd = InitFieldIndex.end();
3640            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3641         if (*UsedIter < *OrigIter)
3642           return true;
3643         if (*UsedIter > *OrigIter)
3644           break;
3645       }
3646 
3647       return false;
3648     }
3649 
3650     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3651                           bool AddressOf) {
3652       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3653         return;
3654 
3655       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3656       // or union.
3657       MemberExpr *FieldME = ME;
3658 
3659       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3660 
3661       Expr *Base = ME;
3662       while (MemberExpr *SubME =
3663                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3664 
3665         if (isa<VarDecl>(SubME->getMemberDecl()))
3666           return;
3667 
3668         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3669           if (!FD->isAnonymousStructOrUnion())
3670             FieldME = SubME;
3671 
3672         if (!FieldME->getType().isPODType(S.Context))
3673           AllPODFields = false;
3674 
3675         Base = SubME->getBase();
3676       }
3677 
3678       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3679         Visit(Base);
3680         return;
3681       }
3682 
3683       if (AddressOf && AllPODFields)
3684         return;
3685 
3686       ValueDecl* FoundVD = FieldME->getMemberDecl();
3687 
3688       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3689         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3690           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3691         }
3692 
3693         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3694           QualType T = BaseCast->getType();
3695           if (T->isPointerType() &&
3696               BaseClasses.count(T->getPointeeType())) {
3697             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3698                 << T->getPointeeType() << FoundVD;
3699           }
3700         }
3701       }
3702 
3703       if (!Decls.count(FoundVD))
3704         return;
3705 
3706       const bool IsReference = FoundVD->getType()->isReferenceType();
3707 
3708       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3709         // Special checking for initializer lists.
3710         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3711           return;
3712         }
3713       } else {
3714         // Prevent double warnings on use of unbounded references.
3715         if (CheckReferenceOnly && !IsReference)
3716           return;
3717       }
3718 
3719       unsigned diag = IsReference
3720           ? diag::warn_reference_field_is_uninit
3721           : diag::warn_field_is_uninit;
3722       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3723       if (Constructor)
3724         S.Diag(Constructor->getLocation(),
3725                diag::note_uninit_in_this_constructor)
3726           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3727 
3728     }
3729 
3730     void HandleValue(Expr *E, bool AddressOf) {
3731       E = E->IgnoreParens();
3732 
3733       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3734         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3735                          AddressOf /*AddressOf*/);
3736         return;
3737       }
3738 
3739       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3740         Visit(CO->getCond());
3741         HandleValue(CO->getTrueExpr(), AddressOf);
3742         HandleValue(CO->getFalseExpr(), AddressOf);
3743         return;
3744       }
3745 
3746       if (BinaryConditionalOperator *BCO =
3747               dyn_cast<BinaryConditionalOperator>(E)) {
3748         Visit(BCO->getCond());
3749         HandleValue(BCO->getFalseExpr(), AddressOf);
3750         return;
3751       }
3752 
3753       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3754         HandleValue(OVE->getSourceExpr(), AddressOf);
3755         return;
3756       }
3757 
3758       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3759         switch (BO->getOpcode()) {
3760         default:
3761           break;
3762         case(BO_PtrMemD):
3763         case(BO_PtrMemI):
3764           HandleValue(BO->getLHS(), AddressOf);
3765           Visit(BO->getRHS());
3766           return;
3767         case(BO_Comma):
3768           Visit(BO->getLHS());
3769           HandleValue(BO->getRHS(), AddressOf);
3770           return;
3771         }
3772       }
3773 
3774       Visit(E);
3775     }
3776 
3777     void CheckInitListExpr(InitListExpr *ILE) {
3778       InitFieldIndex.push_back(0);
3779       for (auto Child : ILE->children()) {
3780         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3781           CheckInitListExpr(SubList);
3782         } else {
3783           Visit(Child);
3784         }
3785         ++InitFieldIndex.back();
3786       }
3787       InitFieldIndex.pop_back();
3788     }
3789 
3790     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3791                           FieldDecl *Field, const Type *BaseClass) {
3792       // Remove Decls that may have been initialized in the previous
3793       // initializer.
3794       for (ValueDecl* VD : DeclsToRemove)
3795         Decls.erase(VD);
3796       DeclsToRemove.clear();
3797 
3798       Constructor = FieldConstructor;
3799       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3800 
3801       if (ILE && Field) {
3802         InitList = true;
3803         InitListFieldDecl = Field;
3804         InitFieldIndex.clear();
3805         CheckInitListExpr(ILE);
3806       } else {
3807         InitList = false;
3808         Visit(E);
3809       }
3810 
3811       if (Field)
3812         Decls.erase(Field);
3813       if (BaseClass)
3814         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3815     }
3816 
3817     void VisitMemberExpr(MemberExpr *ME) {
3818       // All uses of unbounded reference fields will warn.
3819       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3820     }
3821 
3822     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3823       if (E->getCastKind() == CK_LValueToRValue) {
3824         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3825         return;
3826       }
3827 
3828       Inherited::VisitImplicitCastExpr(E);
3829     }
3830 
3831     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3832       if (E->getConstructor()->isCopyConstructor()) {
3833         Expr *ArgExpr = E->getArg(0);
3834         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3835           if (ILE->getNumInits() == 1)
3836             ArgExpr = ILE->getInit(0);
3837         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3838           if (ICE->getCastKind() == CK_NoOp)
3839             ArgExpr = ICE->getSubExpr();
3840         HandleValue(ArgExpr, false /*AddressOf*/);
3841         return;
3842       }
3843       Inherited::VisitCXXConstructExpr(E);
3844     }
3845 
3846     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3847       Expr *Callee = E->getCallee();
3848       if (isa<MemberExpr>(Callee)) {
3849         HandleValue(Callee, false /*AddressOf*/);
3850         for (auto Arg : E->arguments())
3851           Visit(Arg);
3852         return;
3853       }
3854 
3855       Inherited::VisitCXXMemberCallExpr(E);
3856     }
3857 
3858     void VisitCallExpr(CallExpr *E) {
3859       // Treat std::move as a use.
3860       if (E->isCallToStdMove()) {
3861         HandleValue(E->getArg(0), /*AddressOf=*/false);
3862         return;
3863       }
3864 
3865       Inherited::VisitCallExpr(E);
3866     }
3867 
3868     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3869       Expr *Callee = E->getCallee();
3870 
3871       if (isa<UnresolvedLookupExpr>(Callee))
3872         return Inherited::VisitCXXOperatorCallExpr(E);
3873 
3874       Visit(Callee);
3875       for (auto Arg : E->arguments())
3876         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3877     }
3878 
3879     void VisitBinaryOperator(BinaryOperator *E) {
3880       // If a field assignment is detected, remove the field from the
3881       // uninitiailized field set.
3882       if (E->getOpcode() == BO_Assign)
3883         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3884           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3885             if (!FD->getType()->isReferenceType())
3886               DeclsToRemove.push_back(FD);
3887 
3888       if (E->isCompoundAssignmentOp()) {
3889         HandleValue(E->getLHS(), false /*AddressOf*/);
3890         Visit(E->getRHS());
3891         return;
3892       }
3893 
3894       Inherited::VisitBinaryOperator(E);
3895     }
3896 
3897     void VisitUnaryOperator(UnaryOperator *E) {
3898       if (E->isIncrementDecrementOp()) {
3899         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3900         return;
3901       }
3902       if (E->getOpcode() == UO_AddrOf) {
3903         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3904           HandleValue(ME->getBase(), true /*AddressOf*/);
3905           return;
3906         }
3907       }
3908 
3909       Inherited::VisitUnaryOperator(E);
3910     }
3911   };
3912 
3913   // Diagnose value-uses of fields to initialize themselves, e.g.
3914   //   foo(foo)
3915   // where foo is not also a parameter to the constructor.
3916   // Also diagnose across field uninitialized use such as
3917   //   x(y), y(x)
3918   // TODO: implement -Wuninitialized and fold this into that framework.
3919   static void DiagnoseUninitializedFields(
3920       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3921 
3922     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3923                                            Constructor->getLocation())) {
3924       return;
3925     }
3926 
3927     if (Constructor->isInvalidDecl())
3928       return;
3929 
3930     const CXXRecordDecl *RD = Constructor->getParent();
3931 
3932     if (RD->isDependentContext())
3933       return;
3934 
3935     // Holds fields that are uninitialized.
3936     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3937 
3938     // At the beginning, all fields are uninitialized.
3939     for (auto *I : RD->decls()) {
3940       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3941         UninitializedFields.insert(FD);
3942       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3943         UninitializedFields.insert(IFD->getAnonField());
3944       }
3945     }
3946 
3947     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3948     for (auto I : RD->bases())
3949       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3950 
3951     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3952       return;
3953 
3954     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3955                                                    UninitializedFields,
3956                                                    UninitializedBaseClasses);
3957 
3958     for (const auto *FieldInit : Constructor->inits()) {
3959       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3960         break;
3961 
3962       Expr *InitExpr = FieldInit->getInit();
3963       if (!InitExpr)
3964         continue;
3965 
3966       if (CXXDefaultInitExpr *Default =
3967               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3968         InitExpr = Default->getExpr();
3969         if (!InitExpr)
3970           continue;
3971         // In class initializers will point to the constructor.
3972         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3973                                               FieldInit->getAnyMember(),
3974                                               FieldInit->getBaseClass());
3975       } else {
3976         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3977                                               FieldInit->getAnyMember(),
3978                                               FieldInit->getBaseClass());
3979       }
3980     }
3981   }
3982 } // namespace
3983 
3984 /// Enter a new C++ default initializer scope. After calling this, the
3985 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3986 /// parsing or instantiating the initializer failed.
3987 void Sema::ActOnStartCXXInClassMemberInitializer() {
3988   // Create a synthetic function scope to represent the call to the constructor
3989   // that notionally surrounds a use of this initializer.
3990   PushFunctionScope();
3991 }
3992 
3993 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3994   if (!D.isFunctionDeclarator())
3995     return;
3996   auto &FTI = D.getFunctionTypeInfo();
3997   if (!FTI.Params)
3998     return;
3999   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4000                                                           FTI.NumParams)) {
4001     auto *ParamDecl = cast<NamedDecl>(Param.Param);
4002     if (ParamDecl->getDeclName())
4003       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4004   }
4005 }
4006 
4007 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4008   return ActOnRequiresClause(ConstraintExpr);
4009 }
4010 
4011 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4012   if (ConstraintExpr.isInvalid())
4013     return ExprError();
4014 
4015   ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4016   if (ConstraintExpr.isInvalid())
4017     return ExprError();
4018 
4019   if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4020                                       UPPC_RequiresClause))
4021     return ExprError();
4022 
4023   return ConstraintExpr;
4024 }
4025 
4026 /// This is invoked after parsing an in-class initializer for a
4027 /// non-static C++ class member, and after instantiating an in-class initializer
4028 /// in a class template. Such actions are deferred until the class is complete.
4029 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4030                                                   SourceLocation InitLoc,
4031                                                   Expr *InitExpr) {
4032   // Pop the notional constructor scope we created earlier.
4033   PopFunctionScopeInfo(nullptr, D);
4034 
4035   FieldDecl *FD = dyn_cast<FieldDecl>(D);
4036   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4037          "must set init style when field is created");
4038 
4039   if (!InitExpr) {
4040     D->setInvalidDecl();
4041     if (FD)
4042       FD->removeInClassInitializer();
4043     return;
4044   }
4045 
4046   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4047     FD->setInvalidDecl();
4048     FD->removeInClassInitializer();
4049     return;
4050   }
4051 
4052   ExprResult Init = InitExpr;
4053   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
4054     InitializedEntity Entity =
4055         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4056     InitializationKind Kind =
4057         FD->getInClassInitStyle() == ICIS_ListInit
4058             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4059                                                    InitExpr->getBeginLoc(),
4060                                                    InitExpr->getEndLoc())
4061             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4062     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4063     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4064     if (Init.isInvalid()) {
4065       FD->setInvalidDecl();
4066       return;
4067     }
4068   }
4069 
4070   // C++11 [class.base.init]p7:
4071   //   The initialization of each base and member constitutes a
4072   //   full-expression.
4073   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4074   if (Init.isInvalid()) {
4075     FD->setInvalidDecl();
4076     return;
4077   }
4078 
4079   InitExpr = Init.get();
4080 
4081   FD->setInClassInitializer(InitExpr);
4082 }
4083 
4084 /// Find the direct and/or virtual base specifiers that
4085 /// correspond to the given base type, for use in base initialization
4086 /// within a constructor.
4087 static bool FindBaseInitializer(Sema &SemaRef,
4088                                 CXXRecordDecl *ClassDecl,
4089                                 QualType BaseType,
4090                                 const CXXBaseSpecifier *&DirectBaseSpec,
4091                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4092   // First, check for a direct base class.
4093   DirectBaseSpec = nullptr;
4094   for (const auto &Base : ClassDecl->bases()) {
4095     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4096       // We found a direct base of this type. That's what we're
4097       // initializing.
4098       DirectBaseSpec = &Base;
4099       break;
4100     }
4101   }
4102 
4103   // Check for a virtual base class.
4104   // FIXME: We might be able to short-circuit this if we know in advance that
4105   // there are no virtual bases.
4106   VirtualBaseSpec = nullptr;
4107   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4108     // We haven't found a base yet; search the class hierarchy for a
4109     // virtual base class.
4110     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4111                        /*DetectVirtual=*/false);
4112     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4113                               SemaRef.Context.getTypeDeclType(ClassDecl),
4114                               BaseType, Paths)) {
4115       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4116            Path != Paths.end(); ++Path) {
4117         if (Path->back().Base->isVirtual()) {
4118           VirtualBaseSpec = Path->back().Base;
4119           break;
4120         }
4121       }
4122     }
4123   }
4124 
4125   return DirectBaseSpec || VirtualBaseSpec;
4126 }
4127 
4128 /// Handle a C++ member initializer using braced-init-list syntax.
4129 MemInitResult
4130 Sema::ActOnMemInitializer(Decl *ConstructorD,
4131                           Scope *S,
4132                           CXXScopeSpec &SS,
4133                           IdentifierInfo *MemberOrBase,
4134                           ParsedType TemplateTypeTy,
4135                           const DeclSpec &DS,
4136                           SourceLocation IdLoc,
4137                           Expr *InitList,
4138                           SourceLocation EllipsisLoc) {
4139   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4140                              DS, IdLoc, InitList,
4141                              EllipsisLoc);
4142 }
4143 
4144 /// Handle a C++ member initializer using parentheses syntax.
4145 MemInitResult
4146 Sema::ActOnMemInitializer(Decl *ConstructorD,
4147                           Scope *S,
4148                           CXXScopeSpec &SS,
4149                           IdentifierInfo *MemberOrBase,
4150                           ParsedType TemplateTypeTy,
4151                           const DeclSpec &DS,
4152                           SourceLocation IdLoc,
4153                           SourceLocation LParenLoc,
4154                           ArrayRef<Expr *> Args,
4155                           SourceLocation RParenLoc,
4156                           SourceLocation EllipsisLoc) {
4157   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4158   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4159                              DS, IdLoc, List, EllipsisLoc);
4160 }
4161 
4162 namespace {
4163 
4164 // Callback to only accept typo corrections that can be a valid C++ member
4165 // initializer: either a non-static field member or a base class.
4166 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4167 public:
4168   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4169       : ClassDecl(ClassDecl) {}
4170 
4171   bool ValidateCandidate(const TypoCorrection &candidate) override {
4172     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4173       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4174         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4175       return isa<TypeDecl>(ND);
4176     }
4177     return false;
4178   }
4179 
4180   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4181     return std::make_unique<MemInitializerValidatorCCC>(*this);
4182   }
4183 
4184 private:
4185   CXXRecordDecl *ClassDecl;
4186 };
4187 
4188 }
4189 
4190 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4191                                              CXXScopeSpec &SS,
4192                                              ParsedType TemplateTypeTy,
4193                                              IdentifierInfo *MemberOrBase) {
4194   if (SS.getScopeRep() || TemplateTypeTy)
4195     return nullptr;
4196   for (auto *D : ClassDecl->lookup(MemberOrBase))
4197     if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4198       return cast<ValueDecl>(D);
4199   return nullptr;
4200 }
4201 
4202 /// Handle a C++ member initializer.
4203 MemInitResult
4204 Sema::BuildMemInitializer(Decl *ConstructorD,
4205                           Scope *S,
4206                           CXXScopeSpec &SS,
4207                           IdentifierInfo *MemberOrBase,
4208                           ParsedType TemplateTypeTy,
4209                           const DeclSpec &DS,
4210                           SourceLocation IdLoc,
4211                           Expr *Init,
4212                           SourceLocation EllipsisLoc) {
4213   ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4214                                              /*RecoverUncorrectedTypos=*/true);
4215   if (!Res.isUsable())
4216     return true;
4217   Init = Res.get();
4218 
4219   if (!ConstructorD)
4220     return true;
4221 
4222   AdjustDeclIfTemplate(ConstructorD);
4223 
4224   CXXConstructorDecl *Constructor
4225     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4226   if (!Constructor) {
4227     // The user wrote a constructor initializer on a function that is
4228     // not a C++ constructor. Ignore the error for now, because we may
4229     // have more member initializers coming; we'll diagnose it just
4230     // once in ActOnMemInitializers.
4231     return true;
4232   }
4233 
4234   CXXRecordDecl *ClassDecl = Constructor->getParent();
4235 
4236   // C++ [class.base.init]p2:
4237   //   Names in a mem-initializer-id are looked up in the scope of the
4238   //   constructor's class and, if not found in that scope, are looked
4239   //   up in the scope containing the constructor's definition.
4240   //   [Note: if the constructor's class contains a member with the
4241   //   same name as a direct or virtual base class of the class, a
4242   //   mem-initializer-id naming the member or base class and composed
4243   //   of a single identifier refers to the class member. A
4244   //   mem-initializer-id for the hidden base class may be specified
4245   //   using a qualified name. ]
4246 
4247   // Look for a member, first.
4248   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4249           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4250     if (EllipsisLoc.isValid())
4251       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4252           << MemberOrBase
4253           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4254 
4255     return BuildMemberInitializer(Member, Init, IdLoc);
4256   }
4257   // It didn't name a member, so see if it names a class.
4258   QualType BaseType;
4259   TypeSourceInfo *TInfo = nullptr;
4260 
4261   if (TemplateTypeTy) {
4262     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4263     if (BaseType.isNull())
4264       return true;
4265   } else if (DS.getTypeSpecType() == TST_decltype) {
4266     BaseType = BuildDecltypeType(DS.getRepAsExpr());
4267   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4268     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4269     return true;
4270   } else {
4271     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4272     LookupParsedName(R, S, &SS);
4273 
4274     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4275     if (!TyD) {
4276       if (R.isAmbiguous()) return true;
4277 
4278       // We don't want access-control diagnostics here.
4279       R.suppressDiagnostics();
4280 
4281       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4282         bool NotUnknownSpecialization = false;
4283         DeclContext *DC = computeDeclContext(SS, false);
4284         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4285           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4286 
4287         if (!NotUnknownSpecialization) {
4288           // When the scope specifier can refer to a member of an unknown
4289           // specialization, we take it as a type name.
4290           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4291                                        SS.getWithLocInContext(Context),
4292                                        *MemberOrBase, IdLoc);
4293           if (BaseType.isNull())
4294             return true;
4295 
4296           TInfo = Context.CreateTypeSourceInfo(BaseType);
4297           DependentNameTypeLoc TL =
4298               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4299           if (!TL.isNull()) {
4300             TL.setNameLoc(IdLoc);
4301             TL.setElaboratedKeywordLoc(SourceLocation());
4302             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4303           }
4304 
4305           R.clear();
4306           R.setLookupName(MemberOrBase);
4307         }
4308       }
4309 
4310       if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4311         auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>();
4312         if (UnqualifiedBase) {
4313           Diag(IdLoc, diag::ext_unqualified_base_class)
4314               << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4315           BaseType = UnqualifiedBase->getInjectedClassNameSpecialization();
4316         }
4317       }
4318 
4319       // If no results were found, try to correct typos.
4320       TypoCorrection Corr;
4321       MemInitializerValidatorCCC CCC(ClassDecl);
4322       if (R.empty() && BaseType.isNull() &&
4323           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4324                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4325         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4326           // We have found a non-static data member with a similar
4327           // name to what was typed; complain and initialize that
4328           // member.
4329           diagnoseTypo(Corr,
4330                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4331                          << MemberOrBase << true);
4332           return BuildMemberInitializer(Member, Init, IdLoc);
4333         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4334           const CXXBaseSpecifier *DirectBaseSpec;
4335           const CXXBaseSpecifier *VirtualBaseSpec;
4336           if (FindBaseInitializer(*this, ClassDecl,
4337                                   Context.getTypeDeclType(Type),
4338                                   DirectBaseSpec, VirtualBaseSpec)) {
4339             // We have found a direct or virtual base class with a
4340             // similar name to what was typed; complain and initialize
4341             // that base class.
4342             diagnoseTypo(Corr,
4343                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4344                            << MemberOrBase << false,
4345                          PDiag() /*Suppress note, we provide our own.*/);
4346 
4347             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4348                                                               : VirtualBaseSpec;
4349             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4350                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4351 
4352             TyD = Type;
4353           }
4354         }
4355       }
4356 
4357       if (!TyD && BaseType.isNull()) {
4358         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4359           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4360         return true;
4361       }
4362     }
4363 
4364     if (BaseType.isNull()) {
4365       BaseType = Context.getTypeDeclType(TyD);
4366       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4367       if (SS.isSet()) {
4368         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4369                                              BaseType);
4370         TInfo = Context.CreateTypeSourceInfo(BaseType);
4371         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4372         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4373         TL.setElaboratedKeywordLoc(SourceLocation());
4374         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4375       }
4376     }
4377   }
4378 
4379   if (!TInfo)
4380     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4381 
4382   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4383 }
4384 
4385 MemInitResult
4386 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4387                              SourceLocation IdLoc) {
4388   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4389   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4390   assert((DirectMember || IndirectMember) &&
4391          "Member must be a FieldDecl or IndirectFieldDecl");
4392 
4393   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4394     return true;
4395 
4396   if (Member->isInvalidDecl())
4397     return true;
4398 
4399   MultiExprArg Args;
4400   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4401     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4402   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4403     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4404   } else {
4405     // Template instantiation doesn't reconstruct ParenListExprs for us.
4406     Args = Init;
4407   }
4408 
4409   SourceRange InitRange = Init->getSourceRange();
4410 
4411   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4412     // Can't check initialization for a member of dependent type or when
4413     // any of the arguments are type-dependent expressions.
4414     DiscardCleanupsInEvaluationContext();
4415   } else {
4416     bool InitList = false;
4417     if (isa<InitListExpr>(Init)) {
4418       InitList = true;
4419       Args = Init;
4420     }
4421 
4422     // Initialize the member.
4423     InitializedEntity MemberEntity =
4424       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4425                    : InitializedEntity::InitializeMember(IndirectMember,
4426                                                          nullptr);
4427     InitializationKind Kind =
4428         InitList ? InitializationKind::CreateDirectList(
4429                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4430                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4431                                                     InitRange.getEnd());
4432 
4433     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4434     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4435                                             nullptr);
4436     if (!MemberInit.isInvalid()) {
4437       // C++11 [class.base.init]p7:
4438       //   The initialization of each base and member constitutes a
4439       //   full-expression.
4440       MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4441                                        /*DiscardedValue*/ false);
4442     }
4443 
4444     if (MemberInit.isInvalid()) {
4445       // Args were sensible expressions but we couldn't initialize the member
4446       // from them. Preserve them in a RecoveryExpr instead.
4447       Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4448                                 Member->getType())
4449                  .get();
4450       if (!Init)
4451         return true;
4452     } else {
4453       Init = MemberInit.get();
4454     }
4455   }
4456 
4457   if (DirectMember) {
4458     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4459                                             InitRange.getBegin(), Init,
4460                                             InitRange.getEnd());
4461   } else {
4462     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4463                                             InitRange.getBegin(), Init,
4464                                             InitRange.getEnd());
4465   }
4466 }
4467 
4468 MemInitResult
4469 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4470                                  CXXRecordDecl *ClassDecl) {
4471   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4472   if (!LangOpts.CPlusPlus11)
4473     return Diag(NameLoc, diag::err_delegating_ctor)
4474       << TInfo->getTypeLoc().getLocalSourceRange();
4475   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4476 
4477   bool InitList = true;
4478   MultiExprArg Args = Init;
4479   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4480     InitList = false;
4481     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4482   }
4483 
4484   SourceRange InitRange = Init->getSourceRange();
4485   // Initialize the object.
4486   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4487                                      QualType(ClassDecl->getTypeForDecl(), 0));
4488   InitializationKind Kind =
4489       InitList ? InitializationKind::CreateDirectList(
4490                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4491                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4492                                                   InitRange.getEnd());
4493   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4494   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4495                                               Args, nullptr);
4496   if (!DelegationInit.isInvalid()) {
4497     assert((DelegationInit.get()->containsErrors() ||
4498             cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4499            "Delegating constructor with no target?");
4500 
4501     // C++11 [class.base.init]p7:
4502     //   The initialization of each base and member constitutes a
4503     //   full-expression.
4504     DelegationInit = ActOnFinishFullExpr(
4505         DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4506   }
4507 
4508   if (DelegationInit.isInvalid()) {
4509     DelegationInit =
4510         CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4511                            QualType(ClassDecl->getTypeForDecl(), 0));
4512     if (DelegationInit.isInvalid())
4513       return true;
4514   } else {
4515     // If we are in a dependent context, template instantiation will
4516     // perform this type-checking again. Just save the arguments that we
4517     // received in a ParenListExpr.
4518     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4519     // of the information that we have about the base
4520     // initializer. However, deconstructing the ASTs is a dicey process,
4521     // and this approach is far more likely to get the corner cases right.
4522     if (CurContext->isDependentContext())
4523       DelegationInit = Init;
4524   }
4525 
4526   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4527                                           DelegationInit.getAs<Expr>(),
4528                                           InitRange.getEnd());
4529 }
4530 
4531 MemInitResult
4532 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4533                            Expr *Init, CXXRecordDecl *ClassDecl,
4534                            SourceLocation EllipsisLoc) {
4535   SourceLocation BaseLoc
4536     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4537 
4538   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4539     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4540              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4541 
4542   // C++ [class.base.init]p2:
4543   //   [...] Unless the mem-initializer-id names a nonstatic data
4544   //   member of the constructor's class or a direct or virtual base
4545   //   of that class, the mem-initializer is ill-formed. A
4546   //   mem-initializer-list can initialize a base class using any
4547   //   name that denotes that base class type.
4548 
4549   // We can store the initializers in "as-written" form and delay analysis until
4550   // instantiation if the constructor is dependent. But not for dependent
4551   // (broken) code in a non-template! SetCtorInitializers does not expect this.
4552   bool Dependent = CurContext->isDependentContext() &&
4553                    (BaseType->isDependentType() || Init->isTypeDependent());
4554 
4555   SourceRange InitRange = Init->getSourceRange();
4556   if (EllipsisLoc.isValid()) {
4557     // This is a pack expansion.
4558     if (!BaseType->containsUnexpandedParameterPack())  {
4559       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4560         << SourceRange(BaseLoc, InitRange.getEnd());
4561 
4562       EllipsisLoc = SourceLocation();
4563     }
4564   } else {
4565     // Check for any unexpanded parameter packs.
4566     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4567       return true;
4568 
4569     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4570       return true;
4571   }
4572 
4573   // Check for direct and virtual base classes.
4574   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4575   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4576   if (!Dependent) {
4577     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4578                                        BaseType))
4579       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4580 
4581     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4582                         VirtualBaseSpec);
4583 
4584     // C++ [base.class.init]p2:
4585     // Unless the mem-initializer-id names a nonstatic data member of the
4586     // constructor's class or a direct or virtual base of that class, the
4587     // mem-initializer is ill-formed.
4588     if (!DirectBaseSpec && !VirtualBaseSpec) {
4589       // If the class has any dependent bases, then it's possible that
4590       // one of those types will resolve to the same type as
4591       // BaseType. Therefore, just treat this as a dependent base
4592       // class initialization.  FIXME: Should we try to check the
4593       // initialization anyway? It seems odd.
4594       if (ClassDecl->hasAnyDependentBases())
4595         Dependent = true;
4596       else
4597         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4598           << BaseType << Context.getTypeDeclType(ClassDecl)
4599           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4600     }
4601   }
4602 
4603   if (Dependent) {
4604     DiscardCleanupsInEvaluationContext();
4605 
4606     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4607                                             /*IsVirtual=*/false,
4608                                             InitRange.getBegin(), Init,
4609                                             InitRange.getEnd(), EllipsisLoc);
4610   }
4611 
4612   // C++ [base.class.init]p2:
4613   //   If a mem-initializer-id is ambiguous because it designates both
4614   //   a direct non-virtual base class and an inherited virtual base
4615   //   class, the mem-initializer is ill-formed.
4616   if (DirectBaseSpec && VirtualBaseSpec)
4617     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4618       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4619 
4620   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4621   if (!BaseSpec)
4622     BaseSpec = VirtualBaseSpec;
4623 
4624   // Initialize the base.
4625   bool InitList = true;
4626   MultiExprArg Args = Init;
4627   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4628     InitList = false;
4629     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4630   }
4631 
4632   InitializedEntity BaseEntity =
4633     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4634   InitializationKind Kind =
4635       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4636                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4637                                                   InitRange.getEnd());
4638   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4639   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4640   if (!BaseInit.isInvalid()) {
4641     // C++11 [class.base.init]p7:
4642     //   The initialization of each base and member constitutes a
4643     //   full-expression.
4644     BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4645                                    /*DiscardedValue*/ false);
4646   }
4647 
4648   if (BaseInit.isInvalid()) {
4649     BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4650                                   Args, BaseType);
4651     if (BaseInit.isInvalid())
4652       return true;
4653   } else {
4654     // If we are in a dependent context, template instantiation will
4655     // perform this type-checking again. Just save the arguments that we
4656     // received in a ParenListExpr.
4657     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4658     // of the information that we have about the base
4659     // initializer. However, deconstructing the ASTs is a dicey process,
4660     // and this approach is far more likely to get the corner cases right.
4661     if (CurContext->isDependentContext())
4662       BaseInit = Init;
4663   }
4664 
4665   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4666                                           BaseSpec->isVirtual(),
4667                                           InitRange.getBegin(),
4668                                           BaseInit.getAs<Expr>(),
4669                                           InitRange.getEnd(), EllipsisLoc);
4670 }
4671 
4672 // Create a static_cast\<T&&>(expr).
4673 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4674   if (T.isNull()) T = E->getType();
4675   QualType TargetType = SemaRef.BuildReferenceType(
4676       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4677   SourceLocation ExprLoc = E->getBeginLoc();
4678   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4679       TargetType, ExprLoc);
4680 
4681   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4682                                    SourceRange(ExprLoc, ExprLoc),
4683                                    E->getSourceRange()).get();
4684 }
4685 
4686 /// ImplicitInitializerKind - How an implicit base or member initializer should
4687 /// initialize its base or member.
4688 enum ImplicitInitializerKind {
4689   IIK_Default,
4690   IIK_Copy,
4691   IIK_Move,
4692   IIK_Inherit
4693 };
4694 
4695 static bool
4696 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4697                              ImplicitInitializerKind ImplicitInitKind,
4698                              CXXBaseSpecifier *BaseSpec,
4699                              bool IsInheritedVirtualBase,
4700                              CXXCtorInitializer *&CXXBaseInit) {
4701   InitializedEntity InitEntity
4702     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4703                                         IsInheritedVirtualBase);
4704 
4705   ExprResult BaseInit;
4706 
4707   switch (ImplicitInitKind) {
4708   case IIK_Inherit:
4709   case IIK_Default: {
4710     InitializationKind InitKind
4711       = InitializationKind::CreateDefault(Constructor->getLocation());
4712     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4713     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4714     break;
4715   }
4716 
4717   case IIK_Move:
4718   case IIK_Copy: {
4719     bool Moving = ImplicitInitKind == IIK_Move;
4720     ParmVarDecl *Param = Constructor->getParamDecl(0);
4721     QualType ParamType = Param->getType().getNonReferenceType();
4722 
4723     Expr *CopyCtorArg =
4724       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4725                           SourceLocation(), Param, false,
4726                           Constructor->getLocation(), ParamType,
4727                           VK_LValue, nullptr);
4728 
4729     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4730 
4731     // Cast to the base class to avoid ambiguities.
4732     QualType ArgTy =
4733       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4734                                        ParamType.getQualifiers());
4735 
4736     if (Moving) {
4737       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4738     }
4739 
4740     CXXCastPath BasePath;
4741     BasePath.push_back(BaseSpec);
4742     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4743                                             CK_UncheckedDerivedToBase,
4744                                             Moving ? VK_XValue : VK_LValue,
4745                                             &BasePath).get();
4746 
4747     InitializationKind InitKind
4748       = InitializationKind::CreateDirect(Constructor->getLocation(),
4749                                          SourceLocation(), SourceLocation());
4750     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4751     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4752     break;
4753   }
4754   }
4755 
4756   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4757   if (BaseInit.isInvalid())
4758     return true;
4759 
4760   CXXBaseInit =
4761     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4762                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4763                                                         SourceLocation()),
4764                                              BaseSpec->isVirtual(),
4765                                              SourceLocation(),
4766                                              BaseInit.getAs<Expr>(),
4767                                              SourceLocation(),
4768                                              SourceLocation());
4769 
4770   return false;
4771 }
4772 
4773 static bool RefersToRValueRef(Expr *MemRef) {
4774   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4775   return Referenced->getType()->isRValueReferenceType();
4776 }
4777 
4778 static bool
4779 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4780                                ImplicitInitializerKind ImplicitInitKind,
4781                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4782                                CXXCtorInitializer *&CXXMemberInit) {
4783   if (Field->isInvalidDecl())
4784     return true;
4785 
4786   SourceLocation Loc = Constructor->getLocation();
4787 
4788   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4789     bool Moving = ImplicitInitKind == IIK_Move;
4790     ParmVarDecl *Param = Constructor->getParamDecl(0);
4791     QualType ParamType = Param->getType().getNonReferenceType();
4792 
4793     // Suppress copying zero-width bitfields.
4794     if (Field->isZeroLengthBitField(SemaRef.Context))
4795       return false;
4796 
4797     Expr *MemberExprBase =
4798       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4799                           SourceLocation(), Param, false,
4800                           Loc, ParamType, VK_LValue, nullptr);
4801 
4802     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4803 
4804     if (Moving) {
4805       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4806     }
4807 
4808     // Build a reference to this field within the parameter.
4809     CXXScopeSpec SS;
4810     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4811                               Sema::LookupMemberName);
4812     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4813                                   : cast<ValueDecl>(Field), AS_public);
4814     MemberLookup.resolveKind();
4815     ExprResult CtorArg
4816       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4817                                          ParamType, Loc,
4818                                          /*IsArrow=*/false,
4819                                          SS,
4820                                          /*TemplateKWLoc=*/SourceLocation(),
4821                                          /*FirstQualifierInScope=*/nullptr,
4822                                          MemberLookup,
4823                                          /*TemplateArgs=*/nullptr,
4824                                          /*S*/nullptr);
4825     if (CtorArg.isInvalid())
4826       return true;
4827 
4828     // C++11 [class.copy]p15:
4829     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4830     //     with static_cast<T&&>(x.m);
4831     if (RefersToRValueRef(CtorArg.get())) {
4832       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4833     }
4834 
4835     InitializedEntity Entity =
4836         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4837                                                        /*Implicit*/ true)
4838                  : InitializedEntity::InitializeMember(Field, nullptr,
4839                                                        /*Implicit*/ true);
4840 
4841     // Direct-initialize to use the copy constructor.
4842     InitializationKind InitKind =
4843       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4844 
4845     Expr *CtorArgE = CtorArg.getAs<Expr>();
4846     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4847     ExprResult MemberInit =
4848         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4849     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4850     if (MemberInit.isInvalid())
4851       return true;
4852 
4853     if (Indirect)
4854       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4855           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4856     else
4857       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4858           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4859     return false;
4860   }
4861 
4862   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4863          "Unhandled implicit init kind!");
4864 
4865   QualType FieldBaseElementType =
4866     SemaRef.Context.getBaseElementType(Field->getType());
4867 
4868   if (FieldBaseElementType->isRecordType()) {
4869     InitializedEntity InitEntity =
4870         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4871                                                        /*Implicit*/ true)
4872                  : InitializedEntity::InitializeMember(Field, nullptr,
4873                                                        /*Implicit*/ true);
4874     InitializationKind InitKind =
4875       InitializationKind::CreateDefault(Loc);
4876 
4877     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4878     ExprResult MemberInit =
4879       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4880 
4881     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4882     if (MemberInit.isInvalid())
4883       return true;
4884 
4885     if (Indirect)
4886       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4887                                                                Indirect, Loc,
4888                                                                Loc,
4889                                                                MemberInit.get(),
4890                                                                Loc);
4891     else
4892       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4893                                                                Field, Loc, Loc,
4894                                                                MemberInit.get(),
4895                                                                Loc);
4896     return false;
4897   }
4898 
4899   if (!Field->getParent()->isUnion()) {
4900     if (FieldBaseElementType->isReferenceType()) {
4901       SemaRef.Diag(Constructor->getLocation(),
4902                    diag::err_uninitialized_member_in_ctor)
4903       << (int)Constructor->isImplicit()
4904       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4905       << 0 << Field->getDeclName();
4906       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4907       return true;
4908     }
4909 
4910     if (FieldBaseElementType.isConstQualified()) {
4911       SemaRef.Diag(Constructor->getLocation(),
4912                    diag::err_uninitialized_member_in_ctor)
4913       << (int)Constructor->isImplicit()
4914       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4915       << 1 << Field->getDeclName();
4916       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4917       return true;
4918     }
4919   }
4920 
4921   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4922     // ARC and Weak:
4923     //   Default-initialize Objective-C pointers to NULL.
4924     CXXMemberInit
4925       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4926                                                  Loc, Loc,
4927                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4928                                                  Loc);
4929     return false;
4930   }
4931 
4932   // Nothing to initialize.
4933   CXXMemberInit = nullptr;
4934   return false;
4935 }
4936 
4937 namespace {
4938 struct BaseAndFieldInfo {
4939   Sema &S;
4940   CXXConstructorDecl *Ctor;
4941   bool AnyErrorsInInits;
4942   ImplicitInitializerKind IIK;
4943   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4944   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4945   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4946 
4947   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4948     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4949     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4950     if (Ctor->getInheritedConstructor())
4951       IIK = IIK_Inherit;
4952     else if (Generated && Ctor->isCopyConstructor())
4953       IIK = IIK_Copy;
4954     else if (Generated && Ctor->isMoveConstructor())
4955       IIK = IIK_Move;
4956     else
4957       IIK = IIK_Default;
4958   }
4959 
4960   bool isImplicitCopyOrMove() const {
4961     switch (IIK) {
4962     case IIK_Copy:
4963     case IIK_Move:
4964       return true;
4965 
4966     case IIK_Default:
4967     case IIK_Inherit:
4968       return false;
4969     }
4970 
4971     llvm_unreachable("Invalid ImplicitInitializerKind!");
4972   }
4973 
4974   bool addFieldInitializer(CXXCtorInitializer *Init) {
4975     AllToInit.push_back(Init);
4976 
4977     // Check whether this initializer makes the field "used".
4978     if (Init->getInit()->HasSideEffects(S.Context))
4979       S.UnusedPrivateFields.remove(Init->getAnyMember());
4980 
4981     return false;
4982   }
4983 
4984   bool isInactiveUnionMember(FieldDecl *Field) {
4985     RecordDecl *Record = Field->getParent();
4986     if (!Record->isUnion())
4987       return false;
4988 
4989     if (FieldDecl *Active =
4990             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4991       return Active != Field->getCanonicalDecl();
4992 
4993     // In an implicit copy or move constructor, ignore any in-class initializer.
4994     if (isImplicitCopyOrMove())
4995       return true;
4996 
4997     // If there's no explicit initialization, the field is active only if it
4998     // has an in-class initializer...
4999     if (Field->hasInClassInitializer())
5000       return false;
5001     // ... or it's an anonymous struct or union whose class has an in-class
5002     // initializer.
5003     if (!Field->isAnonymousStructOrUnion())
5004       return true;
5005     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5006     return !FieldRD->hasInClassInitializer();
5007   }
5008 
5009   /// Determine whether the given field is, or is within, a union member
5010   /// that is inactive (because there was an initializer given for a different
5011   /// member of the union, or because the union was not initialized at all).
5012   bool isWithinInactiveUnionMember(FieldDecl *Field,
5013                                    IndirectFieldDecl *Indirect) {
5014     if (!Indirect)
5015       return isInactiveUnionMember(Field);
5016 
5017     for (auto *C : Indirect->chain()) {
5018       FieldDecl *Field = dyn_cast<FieldDecl>(C);
5019       if (Field && isInactiveUnionMember(Field))
5020         return true;
5021     }
5022     return false;
5023   }
5024 };
5025 }
5026 
5027 /// Determine whether the given type is an incomplete or zero-lenfgth
5028 /// array type.
5029 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5030   if (T->isIncompleteArrayType())
5031     return true;
5032 
5033   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5034     if (!ArrayT->getSize())
5035       return true;
5036 
5037     T = ArrayT->getElementType();
5038   }
5039 
5040   return false;
5041 }
5042 
5043 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5044                                     FieldDecl *Field,
5045                                     IndirectFieldDecl *Indirect = nullptr) {
5046   if (Field->isInvalidDecl())
5047     return false;
5048 
5049   // Overwhelmingly common case: we have a direct initializer for this field.
5050   if (CXXCtorInitializer *Init =
5051           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5052     return Info.addFieldInitializer(Init);
5053 
5054   // C++11 [class.base.init]p8:
5055   //   if the entity is a non-static data member that has a
5056   //   brace-or-equal-initializer and either
5057   //   -- the constructor's class is a union and no other variant member of that
5058   //      union is designated by a mem-initializer-id or
5059   //   -- the constructor's class is not a union, and, if the entity is a member
5060   //      of an anonymous union, no other member of that union is designated by
5061   //      a mem-initializer-id,
5062   //   the entity is initialized as specified in [dcl.init].
5063   //
5064   // We also apply the same rules to handle anonymous structs within anonymous
5065   // unions.
5066   if (Info.isWithinInactiveUnionMember(Field, Indirect))
5067     return false;
5068 
5069   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5070     ExprResult DIE =
5071         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5072     if (DIE.isInvalid())
5073       return true;
5074 
5075     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5076     SemaRef.checkInitializerLifetime(Entity, DIE.get());
5077 
5078     CXXCtorInitializer *Init;
5079     if (Indirect)
5080       Init = new (SemaRef.Context)
5081           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5082                              SourceLocation(), DIE.get(), SourceLocation());
5083     else
5084       Init = new (SemaRef.Context)
5085           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5086                              SourceLocation(), DIE.get(), SourceLocation());
5087     return Info.addFieldInitializer(Init);
5088   }
5089 
5090   // Don't initialize incomplete or zero-length arrays.
5091   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5092     return false;
5093 
5094   // Don't try to build an implicit initializer if there were semantic
5095   // errors in any of the initializers (and therefore we might be
5096   // missing some that the user actually wrote).
5097   if (Info.AnyErrorsInInits)
5098     return false;
5099 
5100   CXXCtorInitializer *Init = nullptr;
5101   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5102                                      Indirect, Init))
5103     return true;
5104 
5105   if (!Init)
5106     return false;
5107 
5108   return Info.addFieldInitializer(Init);
5109 }
5110 
5111 bool
5112 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5113                                CXXCtorInitializer *Initializer) {
5114   assert(Initializer->isDelegatingInitializer());
5115   Constructor->setNumCtorInitializers(1);
5116   CXXCtorInitializer **initializer =
5117     new (Context) CXXCtorInitializer*[1];
5118   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5119   Constructor->setCtorInitializers(initializer);
5120 
5121   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5122     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5123     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5124   }
5125 
5126   DelegatingCtorDecls.push_back(Constructor);
5127 
5128   DiagnoseUninitializedFields(*this, Constructor);
5129 
5130   return false;
5131 }
5132 
5133 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5134                                ArrayRef<CXXCtorInitializer *> Initializers) {
5135   if (Constructor->isDependentContext()) {
5136     // Just store the initializers as written, they will be checked during
5137     // instantiation.
5138     if (!Initializers.empty()) {
5139       Constructor->setNumCtorInitializers(Initializers.size());
5140       CXXCtorInitializer **baseOrMemberInitializers =
5141         new (Context) CXXCtorInitializer*[Initializers.size()];
5142       memcpy(baseOrMemberInitializers, Initializers.data(),
5143              Initializers.size() * sizeof(CXXCtorInitializer*));
5144       Constructor->setCtorInitializers(baseOrMemberInitializers);
5145     }
5146 
5147     // Let template instantiation know whether we had errors.
5148     if (AnyErrors)
5149       Constructor->setInvalidDecl();
5150 
5151     return false;
5152   }
5153 
5154   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5155 
5156   // We need to build the initializer AST according to order of construction
5157   // and not what user specified in the Initializers list.
5158   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5159   if (!ClassDecl)
5160     return true;
5161 
5162   bool HadError = false;
5163 
5164   for (unsigned i = 0; i < Initializers.size(); i++) {
5165     CXXCtorInitializer *Member = Initializers[i];
5166 
5167     if (Member->isBaseInitializer())
5168       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5169     else {
5170       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5171 
5172       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5173         for (auto *C : F->chain()) {
5174           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5175           if (FD && FD->getParent()->isUnion())
5176             Info.ActiveUnionMember.insert(std::make_pair(
5177                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5178         }
5179       } else if (FieldDecl *FD = Member->getMember()) {
5180         if (FD->getParent()->isUnion())
5181           Info.ActiveUnionMember.insert(std::make_pair(
5182               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5183       }
5184     }
5185   }
5186 
5187   // Keep track of the direct virtual bases.
5188   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5189   for (auto &I : ClassDecl->bases()) {
5190     if (I.isVirtual())
5191       DirectVBases.insert(&I);
5192   }
5193 
5194   // Push virtual bases before others.
5195   for (auto &VBase : ClassDecl->vbases()) {
5196     if (CXXCtorInitializer *Value
5197         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5198       // [class.base.init]p7, per DR257:
5199       //   A mem-initializer where the mem-initializer-id names a virtual base
5200       //   class is ignored during execution of a constructor of any class that
5201       //   is not the most derived class.
5202       if (ClassDecl->isAbstract()) {
5203         // FIXME: Provide a fixit to remove the base specifier. This requires
5204         // tracking the location of the associated comma for a base specifier.
5205         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5206           << VBase.getType() << ClassDecl;
5207         DiagnoseAbstractType(ClassDecl);
5208       }
5209 
5210       Info.AllToInit.push_back(Value);
5211     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5212       // [class.base.init]p8, per DR257:
5213       //   If a given [...] base class is not named by a mem-initializer-id
5214       //   [...] and the entity is not a virtual base class of an abstract
5215       //   class, then [...] the entity is default-initialized.
5216       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5217       CXXCtorInitializer *CXXBaseInit;
5218       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5219                                        &VBase, IsInheritedVirtualBase,
5220                                        CXXBaseInit)) {
5221         HadError = true;
5222         continue;
5223       }
5224 
5225       Info.AllToInit.push_back(CXXBaseInit);
5226     }
5227   }
5228 
5229   // Non-virtual bases.
5230   for (auto &Base : ClassDecl->bases()) {
5231     // Virtuals are in the virtual base list and already constructed.
5232     if (Base.isVirtual())
5233       continue;
5234 
5235     if (CXXCtorInitializer *Value
5236           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5237       Info.AllToInit.push_back(Value);
5238     } else if (!AnyErrors) {
5239       CXXCtorInitializer *CXXBaseInit;
5240       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5241                                        &Base, /*IsInheritedVirtualBase=*/false,
5242                                        CXXBaseInit)) {
5243         HadError = true;
5244         continue;
5245       }
5246 
5247       Info.AllToInit.push_back(CXXBaseInit);
5248     }
5249   }
5250 
5251   // Fields.
5252   for (auto *Mem : ClassDecl->decls()) {
5253     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5254       // C++ [class.bit]p2:
5255       //   A declaration for a bit-field that omits the identifier declares an
5256       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5257       //   initialized.
5258       if (F->isUnnamedBitfield())
5259         continue;
5260 
5261       // If we're not generating the implicit copy/move constructor, then we'll
5262       // handle anonymous struct/union fields based on their individual
5263       // indirect fields.
5264       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5265         continue;
5266 
5267       if (CollectFieldInitializer(*this, Info, F))
5268         HadError = true;
5269       continue;
5270     }
5271 
5272     // Beyond this point, we only consider default initialization.
5273     if (Info.isImplicitCopyOrMove())
5274       continue;
5275 
5276     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5277       if (F->getType()->isIncompleteArrayType()) {
5278         assert(ClassDecl->hasFlexibleArrayMember() &&
5279                "Incomplete array type is not valid");
5280         continue;
5281       }
5282 
5283       // Initialize each field of an anonymous struct individually.
5284       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5285         HadError = true;
5286 
5287       continue;
5288     }
5289   }
5290 
5291   unsigned NumInitializers = Info.AllToInit.size();
5292   if (NumInitializers > 0) {
5293     Constructor->setNumCtorInitializers(NumInitializers);
5294     CXXCtorInitializer **baseOrMemberInitializers =
5295       new (Context) CXXCtorInitializer*[NumInitializers];
5296     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5297            NumInitializers * sizeof(CXXCtorInitializer*));
5298     Constructor->setCtorInitializers(baseOrMemberInitializers);
5299 
5300     // Constructors implicitly reference the base and member
5301     // destructors.
5302     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5303                                            Constructor->getParent());
5304   }
5305 
5306   return HadError;
5307 }
5308 
5309 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5310   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5311     const RecordDecl *RD = RT->getDecl();
5312     if (RD->isAnonymousStructOrUnion()) {
5313       for (auto *Field : RD->fields())
5314         PopulateKeysForFields(Field, IdealInits);
5315       return;
5316     }
5317   }
5318   IdealInits.push_back(Field->getCanonicalDecl());
5319 }
5320 
5321 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5322   return Context.getCanonicalType(BaseType).getTypePtr();
5323 }
5324 
5325 static const void *GetKeyForMember(ASTContext &Context,
5326                                    CXXCtorInitializer *Member) {
5327   if (!Member->isAnyMemberInitializer())
5328     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5329 
5330   return Member->getAnyMember()->getCanonicalDecl();
5331 }
5332 
5333 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5334                                  const CXXCtorInitializer *Previous,
5335                                  const CXXCtorInitializer *Current) {
5336   if (Previous->isAnyMemberInitializer())
5337     Diag << 0 << Previous->getAnyMember();
5338   else
5339     Diag << 1 << Previous->getTypeSourceInfo()->getType();
5340 
5341   if (Current->isAnyMemberInitializer())
5342     Diag << 0 << Current->getAnyMember();
5343   else
5344     Diag << 1 << Current->getTypeSourceInfo()->getType();
5345 }
5346 
5347 static void DiagnoseBaseOrMemInitializerOrder(
5348     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5349     ArrayRef<CXXCtorInitializer *> Inits) {
5350   if (Constructor->getDeclContext()->isDependentContext())
5351     return;
5352 
5353   // Don't check initializers order unless the warning is enabled at the
5354   // location of at least one initializer.
5355   bool ShouldCheckOrder = false;
5356   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5357     CXXCtorInitializer *Init = Inits[InitIndex];
5358     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5359                                  Init->getSourceLocation())) {
5360       ShouldCheckOrder = true;
5361       break;
5362     }
5363   }
5364   if (!ShouldCheckOrder)
5365     return;
5366 
5367   // Build the list of bases and members in the order that they'll
5368   // actually be initialized.  The explicit initializers should be in
5369   // this same order but may be missing things.
5370   SmallVector<const void*, 32> IdealInitKeys;
5371 
5372   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5373 
5374   // 1. Virtual bases.
5375   for (const auto &VBase : ClassDecl->vbases())
5376     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5377 
5378   // 2. Non-virtual bases.
5379   for (const auto &Base : ClassDecl->bases()) {
5380     if (Base.isVirtual())
5381       continue;
5382     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5383   }
5384 
5385   // 3. Direct fields.
5386   for (auto *Field : ClassDecl->fields()) {
5387     if (Field->isUnnamedBitfield())
5388       continue;
5389 
5390     PopulateKeysForFields(Field, IdealInitKeys);
5391   }
5392 
5393   unsigned NumIdealInits = IdealInitKeys.size();
5394   unsigned IdealIndex = 0;
5395 
5396   // Track initializers that are in an incorrect order for either a warning or
5397   // note if multiple ones occur.
5398   SmallVector<unsigned> WarnIndexes;
5399   // Correlates the index of an initializer in the init-list to the index of
5400   // the field/base in the class.
5401   SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5402 
5403   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5404     const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5405 
5406     // Scan forward to try to find this initializer in the idealized
5407     // initializers list.
5408     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5409       if (InitKey == IdealInitKeys[IdealIndex])
5410         break;
5411 
5412     // If we didn't find this initializer, it must be because we
5413     // scanned past it on a previous iteration.  That can only
5414     // happen if we're out of order;  emit a warning.
5415     if (IdealIndex == NumIdealInits && InitIndex) {
5416       WarnIndexes.push_back(InitIndex);
5417 
5418       // Move back to the initializer's location in the ideal list.
5419       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5420         if (InitKey == IdealInitKeys[IdealIndex])
5421           break;
5422 
5423       assert(IdealIndex < NumIdealInits &&
5424              "initializer not found in initializer list");
5425     }
5426     CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5427   }
5428 
5429   if (WarnIndexes.empty())
5430     return;
5431 
5432   // Sort based on the ideal order, first in the pair.
5433   llvm::sort(CorrelatedInitOrder, llvm::less_first());
5434 
5435   // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5436   // emit the diagnostic before we can try adding notes.
5437   {
5438     Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5439         Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5440         WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5441                                 : diag::warn_some_initializers_out_of_order);
5442 
5443     for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5444       if (CorrelatedInitOrder[I].second == I)
5445         continue;
5446       // Ideally we would be using InsertFromRange here, but clang doesn't
5447       // appear to handle InsertFromRange correctly when the source range is
5448       // modified by another fix-it.
5449       D << FixItHint::CreateReplacement(
5450           Inits[I]->getSourceRange(),
5451           Lexer::getSourceText(
5452               CharSourceRange::getTokenRange(
5453                   Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5454               SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5455     }
5456 
5457     // If there is only 1 item out of order, the warning expects the name and
5458     // type of each being added to it.
5459     if (WarnIndexes.size() == 1) {
5460       AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5461                            Inits[WarnIndexes.front()]);
5462       return;
5463     }
5464   }
5465   // More than 1 item to warn, create notes letting the user know which ones
5466   // are bad.
5467   for (unsigned WarnIndex : WarnIndexes) {
5468     const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5469     auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5470                           diag::note_initializer_out_of_order);
5471     AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5472     D << PrevInit->getSourceRange();
5473   }
5474 }
5475 
5476 namespace {
5477 bool CheckRedundantInit(Sema &S,
5478                         CXXCtorInitializer *Init,
5479                         CXXCtorInitializer *&PrevInit) {
5480   if (!PrevInit) {
5481     PrevInit = Init;
5482     return false;
5483   }
5484 
5485   if (FieldDecl *Field = Init->getAnyMember())
5486     S.Diag(Init->getSourceLocation(),
5487            diag::err_multiple_mem_initialization)
5488       << Field->getDeclName()
5489       << Init->getSourceRange();
5490   else {
5491     const Type *BaseClass = Init->getBaseClass();
5492     assert(BaseClass && "neither field nor base");
5493     S.Diag(Init->getSourceLocation(),
5494            diag::err_multiple_base_initialization)
5495       << QualType(BaseClass, 0)
5496       << Init->getSourceRange();
5497   }
5498   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5499     << 0 << PrevInit->getSourceRange();
5500 
5501   return true;
5502 }
5503 
5504 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5505 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5506 
5507 bool CheckRedundantUnionInit(Sema &S,
5508                              CXXCtorInitializer *Init,
5509                              RedundantUnionMap &Unions) {
5510   FieldDecl *Field = Init->getAnyMember();
5511   RecordDecl *Parent = Field->getParent();
5512   NamedDecl *Child = Field;
5513 
5514   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5515     if (Parent->isUnion()) {
5516       UnionEntry &En = Unions[Parent];
5517       if (En.first && En.first != Child) {
5518         S.Diag(Init->getSourceLocation(),
5519                diag::err_multiple_mem_union_initialization)
5520           << Field->getDeclName()
5521           << Init->getSourceRange();
5522         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5523           << 0 << En.second->getSourceRange();
5524         return true;
5525       }
5526       if (!En.first) {
5527         En.first = Child;
5528         En.second = Init;
5529       }
5530       if (!Parent->isAnonymousStructOrUnion())
5531         return false;
5532     }
5533 
5534     Child = Parent;
5535     Parent = cast<RecordDecl>(Parent->getDeclContext());
5536   }
5537 
5538   return false;
5539 }
5540 } // namespace
5541 
5542 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5543 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5544                                 SourceLocation ColonLoc,
5545                                 ArrayRef<CXXCtorInitializer*> MemInits,
5546                                 bool AnyErrors) {
5547   if (!ConstructorDecl)
5548     return;
5549 
5550   AdjustDeclIfTemplate(ConstructorDecl);
5551 
5552   CXXConstructorDecl *Constructor
5553     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5554 
5555   if (!Constructor) {
5556     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5557     return;
5558   }
5559 
5560   // Mapping for the duplicate initializers check.
5561   // For member initializers, this is keyed with a FieldDecl*.
5562   // For base initializers, this is keyed with a Type*.
5563   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5564 
5565   // Mapping for the inconsistent anonymous-union initializers check.
5566   RedundantUnionMap MemberUnions;
5567 
5568   bool HadError = false;
5569   for (unsigned i = 0; i < MemInits.size(); i++) {
5570     CXXCtorInitializer *Init = MemInits[i];
5571 
5572     // Set the source order index.
5573     Init->setSourceOrder(i);
5574 
5575     if (Init->isAnyMemberInitializer()) {
5576       const void *Key = GetKeyForMember(Context, Init);
5577       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5578           CheckRedundantUnionInit(*this, Init, MemberUnions))
5579         HadError = true;
5580     } else if (Init->isBaseInitializer()) {
5581       const void *Key = GetKeyForMember(Context, Init);
5582       if (CheckRedundantInit(*this, Init, Members[Key]))
5583         HadError = true;
5584     } else {
5585       assert(Init->isDelegatingInitializer());
5586       // This must be the only initializer
5587       if (MemInits.size() != 1) {
5588         Diag(Init->getSourceLocation(),
5589              diag::err_delegating_initializer_alone)
5590           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5591         // We will treat this as being the only initializer.
5592       }
5593       SetDelegatingInitializer(Constructor, MemInits[i]);
5594       // Return immediately as the initializer is set.
5595       return;
5596     }
5597   }
5598 
5599   if (HadError)
5600     return;
5601 
5602   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5603 
5604   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5605 
5606   DiagnoseUninitializedFields(*this, Constructor);
5607 }
5608 
5609 void
5610 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5611                                              CXXRecordDecl *ClassDecl) {
5612   // Ignore dependent contexts. Also ignore unions, since their members never
5613   // have destructors implicitly called.
5614   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5615     return;
5616 
5617   // FIXME: all the access-control diagnostics are positioned on the
5618   // field/base declaration.  That's probably good; that said, the
5619   // user might reasonably want to know why the destructor is being
5620   // emitted, and we currently don't say.
5621 
5622   // Non-static data members.
5623   for (auto *Field : ClassDecl->fields()) {
5624     if (Field->isInvalidDecl())
5625       continue;
5626 
5627     // Don't destroy incomplete or zero-length arrays.
5628     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5629       continue;
5630 
5631     QualType FieldType = Context.getBaseElementType(Field->getType());
5632 
5633     const RecordType* RT = FieldType->getAs<RecordType>();
5634     if (!RT)
5635       continue;
5636 
5637     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5638     if (FieldClassDecl->isInvalidDecl())
5639       continue;
5640     if (FieldClassDecl->hasIrrelevantDestructor())
5641       continue;
5642     // The destructor for an implicit anonymous union member is never invoked.
5643     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5644       continue;
5645 
5646     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5647     assert(Dtor && "No dtor found for FieldClassDecl!");
5648     CheckDestructorAccess(Field->getLocation(), Dtor,
5649                           PDiag(diag::err_access_dtor_field)
5650                             << Field->getDeclName()
5651                             << FieldType);
5652 
5653     MarkFunctionReferenced(Location, Dtor);
5654     DiagnoseUseOfDecl(Dtor, Location);
5655   }
5656 
5657   // We only potentially invoke the destructors of potentially constructed
5658   // subobjects.
5659   bool VisitVirtualBases = !ClassDecl->isAbstract();
5660 
5661   // If the destructor exists and has already been marked used in the MS ABI,
5662   // then virtual base destructors have already been checked and marked used.
5663   // Skip checking them again to avoid duplicate diagnostics.
5664   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5665     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5666     if (Dtor && Dtor->isUsed())
5667       VisitVirtualBases = false;
5668   }
5669 
5670   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5671 
5672   // Bases.
5673   for (const auto &Base : ClassDecl->bases()) {
5674     const RecordType *RT = Base.getType()->getAs<RecordType>();
5675     if (!RT)
5676       continue;
5677 
5678     // Remember direct virtual bases.
5679     if (Base.isVirtual()) {
5680       if (!VisitVirtualBases)
5681         continue;
5682       DirectVirtualBases.insert(RT);
5683     }
5684 
5685     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5686     // If our base class is invalid, we probably can't get its dtor anyway.
5687     if (BaseClassDecl->isInvalidDecl())
5688       continue;
5689     if (BaseClassDecl->hasIrrelevantDestructor())
5690       continue;
5691 
5692     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5693     assert(Dtor && "No dtor found for BaseClassDecl!");
5694 
5695     // FIXME: caret should be on the start of the class name
5696     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5697                           PDiag(diag::err_access_dtor_base)
5698                               << Base.getType() << Base.getSourceRange(),
5699                           Context.getTypeDeclType(ClassDecl));
5700 
5701     MarkFunctionReferenced(Location, Dtor);
5702     DiagnoseUseOfDecl(Dtor, Location);
5703   }
5704 
5705   if (VisitVirtualBases)
5706     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5707                                          &DirectVirtualBases);
5708 }
5709 
5710 void Sema::MarkVirtualBaseDestructorsReferenced(
5711     SourceLocation Location, CXXRecordDecl *ClassDecl,
5712     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5713   // Virtual bases.
5714   for (const auto &VBase : ClassDecl->vbases()) {
5715     // Bases are always records in a well-formed non-dependent class.
5716     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5717 
5718     // Ignore already visited direct virtual bases.
5719     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5720       continue;
5721 
5722     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5723     // If our base class is invalid, we probably can't get its dtor anyway.
5724     if (BaseClassDecl->isInvalidDecl())
5725       continue;
5726     if (BaseClassDecl->hasIrrelevantDestructor())
5727       continue;
5728 
5729     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5730     assert(Dtor && "No dtor found for BaseClassDecl!");
5731     if (CheckDestructorAccess(
5732             ClassDecl->getLocation(), Dtor,
5733             PDiag(diag::err_access_dtor_vbase)
5734                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5735             Context.getTypeDeclType(ClassDecl)) ==
5736         AR_accessible) {
5737       CheckDerivedToBaseConversion(
5738           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5739           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5740           SourceRange(), DeclarationName(), nullptr);
5741     }
5742 
5743     MarkFunctionReferenced(Location, Dtor);
5744     DiagnoseUseOfDecl(Dtor, Location);
5745   }
5746 }
5747 
5748 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5749   if (!CDtorDecl)
5750     return;
5751 
5752   if (CXXConstructorDecl *Constructor
5753       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5754     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5755     DiagnoseUninitializedFields(*this, Constructor);
5756   }
5757 }
5758 
5759 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5760   if (!getLangOpts().CPlusPlus)
5761     return false;
5762 
5763   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5764   if (!RD)
5765     return false;
5766 
5767   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5768   // class template specialization here, but doing so breaks a lot of code.
5769 
5770   // We can't answer whether something is abstract until it has a
5771   // definition. If it's currently being defined, we'll walk back
5772   // over all the declarations when we have a full definition.
5773   const CXXRecordDecl *Def = RD->getDefinition();
5774   if (!Def || Def->isBeingDefined())
5775     return false;
5776 
5777   return RD->isAbstract();
5778 }
5779 
5780 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5781                                   TypeDiagnoser &Diagnoser) {
5782   if (!isAbstractType(Loc, T))
5783     return false;
5784 
5785   T = Context.getBaseElementType(T);
5786   Diagnoser.diagnose(*this, Loc, T);
5787   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5788   return true;
5789 }
5790 
5791 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5792   // Check if we've already emitted the list of pure virtual functions
5793   // for this class.
5794   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5795     return;
5796 
5797   // If the diagnostic is suppressed, don't emit the notes. We're only
5798   // going to emit them once, so try to attach them to a diagnostic we're
5799   // actually going to show.
5800   if (Diags.isLastDiagnosticIgnored())
5801     return;
5802 
5803   CXXFinalOverriderMap FinalOverriders;
5804   RD->getFinalOverriders(FinalOverriders);
5805 
5806   // Keep a set of seen pure methods so we won't diagnose the same method
5807   // more than once.
5808   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5809 
5810   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5811                                    MEnd = FinalOverriders.end();
5812        M != MEnd;
5813        ++M) {
5814     for (OverridingMethods::iterator SO = M->second.begin(),
5815                                   SOEnd = M->second.end();
5816          SO != SOEnd; ++SO) {
5817       // C++ [class.abstract]p4:
5818       //   A class is abstract if it contains or inherits at least one
5819       //   pure virtual function for which the final overrider is pure
5820       //   virtual.
5821 
5822       //
5823       if (SO->second.size() != 1)
5824         continue;
5825 
5826       if (!SO->second.front().Method->isPure())
5827         continue;
5828 
5829       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5830         continue;
5831 
5832       Diag(SO->second.front().Method->getLocation(),
5833            diag::note_pure_virtual_function)
5834         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5835     }
5836   }
5837 
5838   if (!PureVirtualClassDiagSet)
5839     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5840   PureVirtualClassDiagSet->insert(RD);
5841 }
5842 
5843 namespace {
5844 struct AbstractUsageInfo {
5845   Sema &S;
5846   CXXRecordDecl *Record;
5847   CanQualType AbstractType;
5848   bool Invalid;
5849 
5850   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5851     : S(S), Record(Record),
5852       AbstractType(S.Context.getCanonicalType(
5853                    S.Context.getTypeDeclType(Record))),
5854       Invalid(false) {}
5855 
5856   void DiagnoseAbstractType() {
5857     if (Invalid) return;
5858     S.DiagnoseAbstractType(Record);
5859     Invalid = true;
5860   }
5861 
5862   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5863 };
5864 
5865 struct CheckAbstractUsage {
5866   AbstractUsageInfo &Info;
5867   const NamedDecl *Ctx;
5868 
5869   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5870     : Info(Info), Ctx(Ctx) {}
5871 
5872   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5873     switch (TL.getTypeLocClass()) {
5874 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5875 #define TYPELOC(CLASS, PARENT) \
5876     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5877 #include "clang/AST/TypeLocNodes.def"
5878     }
5879   }
5880 
5881   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5882     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5883     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5884       if (!TL.getParam(I))
5885         continue;
5886 
5887       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5888       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5889     }
5890   }
5891 
5892   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5893     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5894   }
5895 
5896   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5897     // Visit the type parameters from a permissive context.
5898     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5899       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5900       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5901         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5902           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5903       // TODO: other template argument types?
5904     }
5905   }
5906 
5907   // Visit pointee types from a permissive context.
5908 #define CheckPolymorphic(Type) \
5909   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5910     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5911   }
5912   CheckPolymorphic(PointerTypeLoc)
5913   CheckPolymorphic(ReferenceTypeLoc)
5914   CheckPolymorphic(MemberPointerTypeLoc)
5915   CheckPolymorphic(BlockPointerTypeLoc)
5916   CheckPolymorphic(AtomicTypeLoc)
5917 
5918   /// Handle all the types we haven't given a more specific
5919   /// implementation for above.
5920   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5921     // Every other kind of type that we haven't called out already
5922     // that has an inner type is either (1) sugar or (2) contains that
5923     // inner type in some way as a subobject.
5924     if (TypeLoc Next = TL.getNextTypeLoc())
5925       return Visit(Next, Sel);
5926 
5927     // If there's no inner type and we're in a permissive context,
5928     // don't diagnose.
5929     if (Sel == Sema::AbstractNone) return;
5930 
5931     // Check whether the type matches the abstract type.
5932     QualType T = TL.getType();
5933     if (T->isArrayType()) {
5934       Sel = Sema::AbstractArrayType;
5935       T = Info.S.Context.getBaseElementType(T);
5936     }
5937     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5938     if (CT != Info.AbstractType) return;
5939 
5940     // It matched; do some magic.
5941     // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
5942     if (Sel == Sema::AbstractArrayType) {
5943       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5944         << T << TL.getSourceRange();
5945     } else {
5946       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5947         << Sel << T << TL.getSourceRange();
5948     }
5949     Info.DiagnoseAbstractType();
5950   }
5951 };
5952 
5953 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5954                                   Sema::AbstractDiagSelID Sel) {
5955   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5956 }
5957 
5958 }
5959 
5960 /// Check for invalid uses of an abstract type in a function declaration.
5961 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5962                                     FunctionDecl *FD) {
5963   // No need to do the check on definitions, which require that
5964   // the return/param types be complete.
5965   if (FD->doesThisDeclarationHaveABody())
5966     return;
5967 
5968   // For safety's sake, just ignore it if we don't have type source
5969   // information.  This should never happen for non-implicit methods,
5970   // but...
5971   if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5972     Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
5973 }
5974 
5975 /// Check for invalid uses of an abstract type in a variable0 declaration.
5976 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5977                                     VarDecl *VD) {
5978   // No need to do the check on definitions, which require that
5979   // the type is complete.
5980   if (VD->isThisDeclarationADefinition())
5981     return;
5982 
5983   Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
5984                  Sema::AbstractVariableType);
5985 }
5986 
5987 /// Check for invalid uses of an abstract type within a class definition.
5988 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5989                                     CXXRecordDecl *RD) {
5990   for (auto *D : RD->decls()) {
5991     if (D->isImplicit()) continue;
5992 
5993     // Step through friends to the befriended declaration.
5994     if (auto *FD = dyn_cast<FriendDecl>(D)) {
5995       D = FD->getFriendDecl();
5996       if (!D) continue;
5997     }
5998 
5999     // Functions and function templates.
6000     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6001       CheckAbstractClassUsage(Info, FD);
6002     } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6003       CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6004 
6005     // Fields and static variables.
6006     } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6007       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6008         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6009     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6010       CheckAbstractClassUsage(Info, VD);
6011     } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6012       CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6013 
6014     // Nested classes and class templates.
6015     } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6016       CheckAbstractClassUsage(Info, RD);
6017     } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6018       CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6019     }
6020   }
6021 }
6022 
6023 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6024   Attr *ClassAttr = getDLLAttr(Class);
6025   if (!ClassAttr)
6026     return;
6027 
6028   assert(ClassAttr->getKind() == attr::DLLExport);
6029 
6030   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6031 
6032   if (TSK == TSK_ExplicitInstantiationDeclaration)
6033     // Don't go any further if this is just an explicit instantiation
6034     // declaration.
6035     return;
6036 
6037   // Add a context note to explain how we got to any diagnostics produced below.
6038   struct MarkingClassDllexported {
6039     Sema &S;
6040     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6041                             SourceLocation AttrLoc)
6042         : S(S) {
6043       Sema::CodeSynthesisContext Ctx;
6044       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6045       Ctx.PointOfInstantiation = AttrLoc;
6046       Ctx.Entity = Class;
6047       S.pushCodeSynthesisContext(Ctx);
6048     }
6049     ~MarkingClassDllexported() {
6050       S.popCodeSynthesisContext();
6051     }
6052   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6053 
6054   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6055     S.MarkVTableUsed(Class->getLocation(), Class, true);
6056 
6057   for (Decl *Member : Class->decls()) {
6058     // Skip members that were not marked exported.
6059     if (!Member->hasAttr<DLLExportAttr>())
6060       continue;
6061 
6062     // Defined static variables that are members of an exported base
6063     // class must be marked export too.
6064     auto *VD = dyn_cast<VarDecl>(Member);
6065     if (VD && VD->getStorageClass() == SC_Static &&
6066         TSK == TSK_ImplicitInstantiation)
6067       S.MarkVariableReferenced(VD->getLocation(), VD);
6068 
6069     auto *MD = dyn_cast<CXXMethodDecl>(Member);
6070     if (!MD)
6071       continue;
6072 
6073     if (MD->isUserProvided()) {
6074       // Instantiate non-default class member functions ...
6075 
6076       // .. except for certain kinds of template specializations.
6077       if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6078         continue;
6079 
6080       // If this is an MS ABI dllexport default constructor, instantiate any
6081       // default arguments.
6082       if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6083         auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6084         if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6085           S.InstantiateDefaultCtorDefaultArgs(CD);
6086         }
6087       }
6088 
6089       S.MarkFunctionReferenced(Class->getLocation(), MD);
6090 
6091       // The function will be passed to the consumer when its definition is
6092       // encountered.
6093     } else if (MD->isExplicitlyDefaulted()) {
6094       // Synthesize and instantiate explicitly defaulted methods.
6095       S.MarkFunctionReferenced(Class->getLocation(), MD);
6096 
6097       if (TSK != TSK_ExplicitInstantiationDefinition) {
6098         // Except for explicit instantiation defs, we will not see the
6099         // definition again later, so pass it to the consumer now.
6100         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6101       }
6102     } else if (!MD->isTrivial() ||
6103                MD->isCopyAssignmentOperator() ||
6104                MD->isMoveAssignmentOperator()) {
6105       // Synthesize and instantiate non-trivial implicit methods, and the copy
6106       // and move assignment operators. The latter are exported even if they
6107       // are trivial, because the address of an operator can be taken and
6108       // should compare equal across libraries.
6109       S.MarkFunctionReferenced(Class->getLocation(), MD);
6110 
6111       // There is no later point when we will see the definition of this
6112       // function, so pass it to the consumer now.
6113       S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6114     }
6115   }
6116 }
6117 
6118 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6119                                                         CXXRecordDecl *Class) {
6120   // Only the MS ABI has default constructor closures, so we don't need to do
6121   // this semantic checking anywhere else.
6122   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6123     return;
6124 
6125   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6126   for (Decl *Member : Class->decls()) {
6127     // Look for exported default constructors.
6128     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6129     if (!CD || !CD->isDefaultConstructor())
6130       continue;
6131     auto *Attr = CD->getAttr<DLLExportAttr>();
6132     if (!Attr)
6133       continue;
6134 
6135     // If the class is non-dependent, mark the default arguments as ODR-used so
6136     // that we can properly codegen the constructor closure.
6137     if (!Class->isDependentContext()) {
6138       for (ParmVarDecl *PD : CD->parameters()) {
6139         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6140         S.DiscardCleanupsInEvaluationContext();
6141       }
6142     }
6143 
6144     if (LastExportedDefaultCtor) {
6145       S.Diag(LastExportedDefaultCtor->getLocation(),
6146              diag::err_attribute_dll_ambiguous_default_ctor)
6147           << Class;
6148       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6149           << CD->getDeclName();
6150       return;
6151     }
6152     LastExportedDefaultCtor = CD;
6153   }
6154 }
6155 
6156 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6157                                                        CXXRecordDecl *Class) {
6158   bool ErrorReported = false;
6159   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6160                                                      ClassTemplateDecl *TD) {
6161     if (ErrorReported)
6162       return;
6163     S.Diag(TD->getLocation(),
6164            diag::err_cuda_device_builtin_surftex_cls_template)
6165         << /*surface*/ 0 << TD;
6166     ErrorReported = true;
6167   };
6168 
6169   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6170   if (!TD) {
6171     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6172     if (!SD) {
6173       S.Diag(Class->getLocation(),
6174              diag::err_cuda_device_builtin_surftex_ref_decl)
6175           << /*surface*/ 0 << Class;
6176       S.Diag(Class->getLocation(),
6177              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6178           << Class;
6179       return;
6180     }
6181     TD = SD->getSpecializedTemplate();
6182   }
6183 
6184   TemplateParameterList *Params = TD->getTemplateParameters();
6185   unsigned N = Params->size();
6186 
6187   if (N != 2) {
6188     reportIllegalClassTemplate(S, TD);
6189     S.Diag(TD->getLocation(),
6190            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6191         << TD << 2;
6192   }
6193   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6194     reportIllegalClassTemplate(S, TD);
6195     S.Diag(TD->getLocation(),
6196            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6197         << TD << /*1st*/ 0 << /*type*/ 0;
6198   }
6199   if (N > 1) {
6200     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6201     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6202       reportIllegalClassTemplate(S, TD);
6203       S.Diag(TD->getLocation(),
6204              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6205           << TD << /*2nd*/ 1 << /*integer*/ 1;
6206     }
6207   }
6208 }
6209 
6210 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6211                                                        CXXRecordDecl *Class) {
6212   bool ErrorReported = false;
6213   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6214                                                      ClassTemplateDecl *TD) {
6215     if (ErrorReported)
6216       return;
6217     S.Diag(TD->getLocation(),
6218            diag::err_cuda_device_builtin_surftex_cls_template)
6219         << /*texture*/ 1 << TD;
6220     ErrorReported = true;
6221   };
6222 
6223   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6224   if (!TD) {
6225     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6226     if (!SD) {
6227       S.Diag(Class->getLocation(),
6228              diag::err_cuda_device_builtin_surftex_ref_decl)
6229           << /*texture*/ 1 << Class;
6230       S.Diag(Class->getLocation(),
6231              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6232           << Class;
6233       return;
6234     }
6235     TD = SD->getSpecializedTemplate();
6236   }
6237 
6238   TemplateParameterList *Params = TD->getTemplateParameters();
6239   unsigned N = Params->size();
6240 
6241   if (N != 3) {
6242     reportIllegalClassTemplate(S, TD);
6243     S.Diag(TD->getLocation(),
6244            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6245         << TD << 3;
6246   }
6247   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6248     reportIllegalClassTemplate(S, TD);
6249     S.Diag(TD->getLocation(),
6250            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6251         << TD << /*1st*/ 0 << /*type*/ 0;
6252   }
6253   if (N > 1) {
6254     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6255     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6256       reportIllegalClassTemplate(S, TD);
6257       S.Diag(TD->getLocation(),
6258              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6259           << TD << /*2nd*/ 1 << /*integer*/ 1;
6260     }
6261   }
6262   if (N > 2) {
6263     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6264     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6265       reportIllegalClassTemplate(S, TD);
6266       S.Diag(TD->getLocation(),
6267              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6268           << TD << /*3rd*/ 2 << /*integer*/ 1;
6269     }
6270   }
6271 }
6272 
6273 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6274   // Mark any compiler-generated routines with the implicit code_seg attribute.
6275   for (auto *Method : Class->methods()) {
6276     if (Method->isUserProvided())
6277       continue;
6278     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6279       Method->addAttr(A);
6280   }
6281 }
6282 
6283 /// Check class-level dllimport/dllexport attribute.
6284 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6285   Attr *ClassAttr = getDLLAttr(Class);
6286 
6287   // MSVC inherits DLL attributes to partial class template specializations.
6288   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6289     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6290       if (Attr *TemplateAttr =
6291               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6292         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6293         A->setInherited(true);
6294         ClassAttr = A;
6295       }
6296     }
6297   }
6298 
6299   if (!ClassAttr)
6300     return;
6301 
6302   if (!Class->isExternallyVisible()) {
6303     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6304         << Class << ClassAttr;
6305     return;
6306   }
6307 
6308   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6309       !ClassAttr->isInherited()) {
6310     // Diagnose dll attributes on members of class with dll attribute.
6311     for (Decl *Member : Class->decls()) {
6312       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6313         continue;
6314       InheritableAttr *MemberAttr = getDLLAttr(Member);
6315       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6316         continue;
6317 
6318       Diag(MemberAttr->getLocation(),
6319              diag::err_attribute_dll_member_of_dll_class)
6320           << MemberAttr << ClassAttr;
6321       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6322       Member->setInvalidDecl();
6323     }
6324   }
6325 
6326   if (Class->getDescribedClassTemplate())
6327     // Don't inherit dll attribute until the template is instantiated.
6328     return;
6329 
6330   // The class is either imported or exported.
6331   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6332 
6333   // Check if this was a dllimport attribute propagated from a derived class to
6334   // a base class template specialization. We don't apply these attributes to
6335   // static data members.
6336   const bool PropagatedImport =
6337       !ClassExported &&
6338       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6339 
6340   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6341 
6342   // Ignore explicit dllexport on explicit class template instantiation
6343   // declarations, except in MinGW mode.
6344   if (ClassExported && !ClassAttr->isInherited() &&
6345       TSK == TSK_ExplicitInstantiationDeclaration &&
6346       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6347     Class->dropAttr<DLLExportAttr>();
6348     return;
6349   }
6350 
6351   // Force declaration of implicit members so they can inherit the attribute.
6352   ForceDeclarationOfImplicitMembers(Class);
6353 
6354   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6355   // seem to be true in practice?
6356 
6357   for (Decl *Member : Class->decls()) {
6358     VarDecl *VD = dyn_cast<VarDecl>(Member);
6359     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6360 
6361     // Only methods and static fields inherit the attributes.
6362     if (!VD && !MD)
6363       continue;
6364 
6365     if (MD) {
6366       // Don't process deleted methods.
6367       if (MD->isDeleted())
6368         continue;
6369 
6370       if (MD->isInlined()) {
6371         // MinGW does not import or export inline methods. But do it for
6372         // template instantiations.
6373         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6374             TSK != TSK_ExplicitInstantiationDeclaration &&
6375             TSK != TSK_ExplicitInstantiationDefinition)
6376           continue;
6377 
6378         // MSVC versions before 2015 don't export the move assignment operators
6379         // and move constructor, so don't attempt to import/export them if
6380         // we have a definition.
6381         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6382         if ((MD->isMoveAssignmentOperator() ||
6383              (Ctor && Ctor->isMoveConstructor())) &&
6384             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6385           continue;
6386 
6387         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6388         // operator is exported anyway.
6389         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6390             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6391           continue;
6392       }
6393     }
6394 
6395     // Don't apply dllimport attributes to static data members of class template
6396     // instantiations when the attribute is propagated from a derived class.
6397     if (VD && PropagatedImport)
6398       continue;
6399 
6400     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6401       continue;
6402 
6403     if (!getDLLAttr(Member)) {
6404       InheritableAttr *NewAttr = nullptr;
6405 
6406       // Do not export/import inline function when -fno-dllexport-inlines is
6407       // passed. But add attribute for later local static var check.
6408       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6409           TSK != TSK_ExplicitInstantiationDeclaration &&
6410           TSK != TSK_ExplicitInstantiationDefinition) {
6411         if (ClassExported) {
6412           NewAttr = ::new (getASTContext())
6413               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6414         } else {
6415           NewAttr = ::new (getASTContext())
6416               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6417         }
6418       } else {
6419         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6420       }
6421 
6422       NewAttr->setInherited(true);
6423       Member->addAttr(NewAttr);
6424 
6425       if (MD) {
6426         // Propagate DLLAttr to friend re-declarations of MD that have already
6427         // been constructed.
6428         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6429              FD = FD->getPreviousDecl()) {
6430           if (FD->getFriendObjectKind() == Decl::FOK_None)
6431             continue;
6432           assert(!getDLLAttr(FD) &&
6433                  "friend re-decl should not already have a DLLAttr");
6434           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6435           NewAttr->setInherited(true);
6436           FD->addAttr(NewAttr);
6437         }
6438       }
6439     }
6440   }
6441 
6442   if (ClassExported)
6443     DelayedDllExportClasses.push_back(Class);
6444 }
6445 
6446 /// Perform propagation of DLL attributes from a derived class to a
6447 /// templated base class for MS compatibility.
6448 void Sema::propagateDLLAttrToBaseClassTemplate(
6449     CXXRecordDecl *Class, Attr *ClassAttr,
6450     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6451   if (getDLLAttr(
6452           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6453     // If the base class template has a DLL attribute, don't try to change it.
6454     return;
6455   }
6456 
6457   auto TSK = BaseTemplateSpec->getSpecializationKind();
6458   if (!getDLLAttr(BaseTemplateSpec) &&
6459       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6460        TSK == TSK_ImplicitInstantiation)) {
6461     // The template hasn't been instantiated yet (or it has, but only as an
6462     // explicit instantiation declaration or implicit instantiation, which means
6463     // we haven't codegenned any members yet), so propagate the attribute.
6464     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6465     NewAttr->setInherited(true);
6466     BaseTemplateSpec->addAttr(NewAttr);
6467 
6468     // If this was an import, mark that we propagated it from a derived class to
6469     // a base class template specialization.
6470     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6471       ImportAttr->setPropagatedToBaseTemplate();
6472 
6473     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6474     // needs to be run again to work see the new attribute. Otherwise this will
6475     // get run whenever the template is instantiated.
6476     if (TSK != TSK_Undeclared)
6477       checkClassLevelDLLAttribute(BaseTemplateSpec);
6478 
6479     return;
6480   }
6481 
6482   if (getDLLAttr(BaseTemplateSpec)) {
6483     // The template has already been specialized or instantiated with an
6484     // attribute, explicitly or through propagation. We should not try to change
6485     // it.
6486     return;
6487   }
6488 
6489   // The template was previously instantiated or explicitly specialized without
6490   // a dll attribute, It's too late for us to add an attribute, so warn that
6491   // this is unsupported.
6492   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6493       << BaseTemplateSpec->isExplicitSpecialization();
6494   Diag(ClassAttr->getLocation(), diag::note_attribute);
6495   if (BaseTemplateSpec->isExplicitSpecialization()) {
6496     Diag(BaseTemplateSpec->getLocation(),
6497            diag::note_template_class_explicit_specialization_was_here)
6498         << BaseTemplateSpec;
6499   } else {
6500     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6501            diag::note_template_class_instantiation_was_here)
6502         << BaseTemplateSpec;
6503   }
6504 }
6505 
6506 /// Determine the kind of defaulting that would be done for a given function.
6507 ///
6508 /// If the function is both a default constructor and a copy / move constructor
6509 /// (due to having a default argument for the first parameter), this picks
6510 /// CXXDefaultConstructor.
6511 ///
6512 /// FIXME: Check that case is properly handled by all callers.
6513 Sema::DefaultedFunctionKind
6514 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6515   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6516     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6517       if (Ctor->isDefaultConstructor())
6518         return Sema::CXXDefaultConstructor;
6519 
6520       if (Ctor->isCopyConstructor())
6521         return Sema::CXXCopyConstructor;
6522 
6523       if (Ctor->isMoveConstructor())
6524         return Sema::CXXMoveConstructor;
6525     }
6526 
6527     if (MD->isCopyAssignmentOperator())
6528       return Sema::CXXCopyAssignment;
6529 
6530     if (MD->isMoveAssignmentOperator())
6531       return Sema::CXXMoveAssignment;
6532 
6533     if (isa<CXXDestructorDecl>(FD))
6534       return Sema::CXXDestructor;
6535   }
6536 
6537   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6538   case OO_EqualEqual:
6539     return DefaultedComparisonKind::Equal;
6540 
6541   case OO_ExclaimEqual:
6542     return DefaultedComparisonKind::NotEqual;
6543 
6544   case OO_Spaceship:
6545     // No point allowing this if <=> doesn't exist in the current language mode.
6546     if (!getLangOpts().CPlusPlus20)
6547       break;
6548     return DefaultedComparisonKind::ThreeWay;
6549 
6550   case OO_Less:
6551   case OO_LessEqual:
6552   case OO_Greater:
6553   case OO_GreaterEqual:
6554     // No point allowing this if <=> doesn't exist in the current language mode.
6555     if (!getLangOpts().CPlusPlus20)
6556       break;
6557     return DefaultedComparisonKind::Relational;
6558 
6559   default:
6560     break;
6561   }
6562 
6563   // Not defaultable.
6564   return DefaultedFunctionKind();
6565 }
6566 
6567 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6568                                     SourceLocation DefaultLoc) {
6569   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6570   if (DFK.isComparison())
6571     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6572 
6573   switch (DFK.asSpecialMember()) {
6574   case Sema::CXXDefaultConstructor:
6575     S.DefineImplicitDefaultConstructor(DefaultLoc,
6576                                        cast<CXXConstructorDecl>(FD));
6577     break;
6578   case Sema::CXXCopyConstructor:
6579     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6580     break;
6581   case Sema::CXXCopyAssignment:
6582     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6583     break;
6584   case Sema::CXXDestructor:
6585     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6586     break;
6587   case Sema::CXXMoveConstructor:
6588     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6589     break;
6590   case Sema::CXXMoveAssignment:
6591     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6592     break;
6593   case Sema::CXXInvalid:
6594     llvm_unreachable("Invalid special member.");
6595   }
6596 }
6597 
6598 /// Determine whether a type is permitted to be passed or returned in
6599 /// registers, per C++ [class.temporary]p3.
6600 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6601                                TargetInfo::CallingConvKind CCK) {
6602   if (D->isDependentType() || D->isInvalidDecl())
6603     return false;
6604 
6605   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6606   // The PS4 platform ABI follows the behavior of Clang 3.2.
6607   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6608     return !D->hasNonTrivialDestructorForCall() &&
6609            !D->hasNonTrivialCopyConstructorForCall();
6610 
6611   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6612     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6613     bool DtorIsTrivialForCall = false;
6614 
6615     // If a class has at least one non-deleted, trivial copy constructor, it
6616     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6617     //
6618     // Note: This permits classes with non-trivial copy or move ctors to be
6619     // passed in registers, so long as they *also* have a trivial copy ctor,
6620     // which is non-conforming.
6621     if (D->needsImplicitCopyConstructor()) {
6622       if (!D->defaultedCopyConstructorIsDeleted()) {
6623         if (D->hasTrivialCopyConstructor())
6624           CopyCtorIsTrivial = true;
6625         if (D->hasTrivialCopyConstructorForCall())
6626           CopyCtorIsTrivialForCall = true;
6627       }
6628     } else {
6629       for (const CXXConstructorDecl *CD : D->ctors()) {
6630         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6631           if (CD->isTrivial())
6632             CopyCtorIsTrivial = true;
6633           if (CD->isTrivialForCall())
6634             CopyCtorIsTrivialForCall = true;
6635         }
6636       }
6637     }
6638 
6639     if (D->needsImplicitDestructor()) {
6640       if (!D->defaultedDestructorIsDeleted() &&
6641           D->hasTrivialDestructorForCall())
6642         DtorIsTrivialForCall = true;
6643     } else if (const auto *DD = D->getDestructor()) {
6644       if (!DD->isDeleted() && DD->isTrivialForCall())
6645         DtorIsTrivialForCall = true;
6646     }
6647 
6648     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6649     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6650       return true;
6651 
6652     // If a class has a destructor, we'd really like to pass it indirectly
6653     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6654     // impossible for small types, which it will pass in a single register or
6655     // stack slot. Most objects with dtors are large-ish, so handle that early.
6656     // We can't call out all large objects as being indirect because there are
6657     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6658     // how we pass large POD types.
6659 
6660     // Note: This permits small classes with nontrivial destructors to be
6661     // passed in registers, which is non-conforming.
6662     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6663     uint64_t TypeSize = isAArch64 ? 128 : 64;
6664 
6665     if (CopyCtorIsTrivial &&
6666         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6667       return true;
6668     return false;
6669   }
6670 
6671   // Per C++ [class.temporary]p3, the relevant condition is:
6672   //   each copy constructor, move constructor, and destructor of X is
6673   //   either trivial or deleted, and X has at least one non-deleted copy
6674   //   or move constructor
6675   bool HasNonDeletedCopyOrMove = false;
6676 
6677   if (D->needsImplicitCopyConstructor() &&
6678       !D->defaultedCopyConstructorIsDeleted()) {
6679     if (!D->hasTrivialCopyConstructorForCall())
6680       return false;
6681     HasNonDeletedCopyOrMove = true;
6682   }
6683 
6684   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6685       !D->defaultedMoveConstructorIsDeleted()) {
6686     if (!D->hasTrivialMoveConstructorForCall())
6687       return false;
6688     HasNonDeletedCopyOrMove = true;
6689   }
6690 
6691   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6692       !D->hasTrivialDestructorForCall())
6693     return false;
6694 
6695   for (const CXXMethodDecl *MD : D->methods()) {
6696     if (MD->isDeleted())
6697       continue;
6698 
6699     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6700     if (CD && CD->isCopyOrMoveConstructor())
6701       HasNonDeletedCopyOrMove = true;
6702     else if (!isa<CXXDestructorDecl>(MD))
6703       continue;
6704 
6705     if (!MD->isTrivialForCall())
6706       return false;
6707   }
6708 
6709   return HasNonDeletedCopyOrMove;
6710 }
6711 
6712 /// Report an error regarding overriding, along with any relevant
6713 /// overridden methods.
6714 ///
6715 /// \param DiagID the primary error to report.
6716 /// \param MD the overriding method.
6717 static bool
6718 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6719                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6720   bool IssuedDiagnostic = false;
6721   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6722     if (Report(O)) {
6723       if (!IssuedDiagnostic) {
6724         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6725         IssuedDiagnostic = true;
6726       }
6727       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6728     }
6729   }
6730   return IssuedDiagnostic;
6731 }
6732 
6733 /// Perform semantic checks on a class definition that has been
6734 /// completing, introducing implicitly-declared members, checking for
6735 /// abstract types, etc.
6736 ///
6737 /// \param S The scope in which the class was parsed. Null if we didn't just
6738 ///        parse a class definition.
6739 /// \param Record The completed class.
6740 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6741   if (!Record)
6742     return;
6743 
6744   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6745     AbstractUsageInfo Info(*this, Record);
6746     CheckAbstractClassUsage(Info, Record);
6747   }
6748 
6749   // If this is not an aggregate type and has no user-declared constructor,
6750   // complain about any non-static data members of reference or const scalar
6751   // type, since they will never get initializers.
6752   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6753       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6754       !Record->isLambda()) {
6755     bool Complained = false;
6756     for (const auto *F : Record->fields()) {
6757       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6758         continue;
6759 
6760       if (F->getType()->isReferenceType() ||
6761           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6762         if (!Complained) {
6763           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6764             << Record->getTagKind() << Record;
6765           Complained = true;
6766         }
6767 
6768         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6769           << F->getType()->isReferenceType()
6770           << F->getDeclName();
6771       }
6772     }
6773   }
6774 
6775   if (Record->getIdentifier()) {
6776     // C++ [class.mem]p13:
6777     //   If T is the name of a class, then each of the following shall have a
6778     //   name different from T:
6779     //     - every member of every anonymous union that is a member of class T.
6780     //
6781     // C++ [class.mem]p14:
6782     //   In addition, if class T has a user-declared constructor (12.1), every
6783     //   non-static data member of class T shall have a name different from T.
6784     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6785     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6786          ++I) {
6787       NamedDecl *D = (*I)->getUnderlyingDecl();
6788       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6789            Record->hasUserDeclaredConstructor()) ||
6790           isa<IndirectFieldDecl>(D)) {
6791         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6792           << D->getDeclName();
6793         break;
6794       }
6795     }
6796   }
6797 
6798   // Warn if the class has virtual methods but non-virtual public destructor.
6799   if (Record->isPolymorphic() && !Record->isDependentType()) {
6800     CXXDestructorDecl *dtor = Record->getDestructor();
6801     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6802         !Record->hasAttr<FinalAttr>())
6803       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6804            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6805   }
6806 
6807   if (Record->isAbstract()) {
6808     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6809       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6810         << FA->isSpelledAsSealed();
6811       DiagnoseAbstractType(Record);
6812     }
6813   }
6814 
6815   // Warn if the class has a final destructor but is not itself marked final.
6816   if (!Record->hasAttr<FinalAttr>()) {
6817     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6818       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6819         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6820             << FA->isSpelledAsSealed()
6821             << FixItHint::CreateInsertion(
6822                    getLocForEndOfToken(Record->getLocation()),
6823                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6824         Diag(Record->getLocation(),
6825              diag::note_final_dtor_non_final_class_silence)
6826             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6827       }
6828     }
6829   }
6830 
6831   // See if trivial_abi has to be dropped.
6832   if (Record->hasAttr<TrivialABIAttr>())
6833     checkIllFormedTrivialABIStruct(*Record);
6834 
6835   // Set HasTrivialSpecialMemberForCall if the record has attribute
6836   // "trivial_abi".
6837   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6838 
6839   if (HasTrivialABI)
6840     Record->setHasTrivialSpecialMemberForCall();
6841 
6842   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6843   // We check these last because they can depend on the properties of the
6844   // primary comparison functions (==, <=>).
6845   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6846 
6847   // Perform checks that can't be done until we know all the properties of a
6848   // member function (whether it's defaulted, deleted, virtual, overriding,
6849   // ...).
6850   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6851     // A static function cannot override anything.
6852     if (MD->getStorageClass() == SC_Static) {
6853       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6854                           [](const CXXMethodDecl *) { return true; }))
6855         return;
6856     }
6857 
6858     // A deleted function cannot override a non-deleted function and vice
6859     // versa.
6860     if (ReportOverrides(*this,
6861                         MD->isDeleted() ? diag::err_deleted_override
6862                                         : diag::err_non_deleted_override,
6863                         MD, [&](const CXXMethodDecl *V) {
6864                           return MD->isDeleted() != V->isDeleted();
6865                         })) {
6866       if (MD->isDefaulted() && MD->isDeleted())
6867         // Explain why this defaulted function was deleted.
6868         DiagnoseDeletedDefaultedFunction(MD);
6869       return;
6870     }
6871 
6872     // A consteval function cannot override a non-consteval function and vice
6873     // versa.
6874     if (ReportOverrides(*this,
6875                         MD->isConsteval() ? diag::err_consteval_override
6876                                           : diag::err_non_consteval_override,
6877                         MD, [&](const CXXMethodDecl *V) {
6878                           return MD->isConsteval() != V->isConsteval();
6879                         })) {
6880       if (MD->isDefaulted() && MD->isDeleted())
6881         // Explain why this defaulted function was deleted.
6882         DiagnoseDeletedDefaultedFunction(MD);
6883       return;
6884     }
6885   };
6886 
6887   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6888     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6889       return false;
6890 
6891     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6892     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6893         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6894       DefaultedSecondaryComparisons.push_back(FD);
6895       return true;
6896     }
6897 
6898     CheckExplicitlyDefaultedFunction(S, FD);
6899     return false;
6900   };
6901 
6902   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6903     // Check whether the explicitly-defaulted members are valid.
6904     bool Incomplete = CheckForDefaultedFunction(M);
6905 
6906     // Skip the rest of the checks for a member of a dependent class.
6907     if (Record->isDependentType())
6908       return;
6909 
6910     // For an explicitly defaulted or deleted special member, we defer
6911     // determining triviality until the class is complete. That time is now!
6912     CXXSpecialMember CSM = getSpecialMember(M);
6913     if (!M->isImplicit() && !M->isUserProvided()) {
6914       if (CSM != CXXInvalid) {
6915         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6916         // Inform the class that we've finished declaring this member.
6917         Record->finishedDefaultedOrDeletedMember(M);
6918         M->setTrivialForCall(
6919             HasTrivialABI ||
6920             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6921         Record->setTrivialForCallFlags(M);
6922       }
6923     }
6924 
6925     // Set triviality for the purpose of calls if this is a user-provided
6926     // copy/move constructor or destructor.
6927     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6928          CSM == CXXDestructor) && M->isUserProvided()) {
6929       M->setTrivialForCall(HasTrivialABI);
6930       Record->setTrivialForCallFlags(M);
6931     }
6932 
6933     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6934         M->hasAttr<DLLExportAttr>()) {
6935       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6936           M->isTrivial() &&
6937           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6938            CSM == CXXDestructor))
6939         M->dropAttr<DLLExportAttr>();
6940 
6941       if (M->hasAttr<DLLExportAttr>()) {
6942         // Define after any fields with in-class initializers have been parsed.
6943         DelayedDllExportMemberFunctions.push_back(M);
6944       }
6945     }
6946 
6947     // Define defaulted constexpr virtual functions that override a base class
6948     // function right away.
6949     // FIXME: We can defer doing this until the vtable is marked as used.
6950     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6951       DefineDefaultedFunction(*this, M, M->getLocation());
6952 
6953     if (!Incomplete)
6954       CheckCompletedMemberFunction(M);
6955   };
6956 
6957   // Check the destructor before any other member function. We need to
6958   // determine whether it's trivial in order to determine whether the claas
6959   // type is a literal type, which is a prerequisite for determining whether
6960   // other special member functions are valid and whether they're implicitly
6961   // 'constexpr'.
6962   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6963     CompleteMemberFunction(Dtor);
6964 
6965   bool HasMethodWithOverrideControl = false,
6966        HasOverridingMethodWithoutOverrideControl = false;
6967   for (auto *D : Record->decls()) {
6968     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6969       // FIXME: We could do this check for dependent types with non-dependent
6970       // bases.
6971       if (!Record->isDependentType()) {
6972         // See if a method overloads virtual methods in a base
6973         // class without overriding any.
6974         if (!M->isStatic())
6975           DiagnoseHiddenVirtualMethods(M);
6976         if (M->hasAttr<OverrideAttr>())
6977           HasMethodWithOverrideControl = true;
6978         else if (M->size_overridden_methods() > 0)
6979           HasOverridingMethodWithoutOverrideControl = true;
6980       }
6981 
6982       if (!isa<CXXDestructorDecl>(M))
6983         CompleteMemberFunction(M);
6984     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6985       CheckForDefaultedFunction(
6986           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6987     }
6988   }
6989 
6990   if (HasOverridingMethodWithoutOverrideControl) {
6991     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6992     for (auto *M : Record->methods())
6993       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6994   }
6995 
6996   // Check the defaulted secondary comparisons after any other member functions.
6997   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6998     CheckExplicitlyDefaultedFunction(S, FD);
6999 
7000     // If this is a member function, we deferred checking it until now.
7001     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7002       CheckCompletedMemberFunction(MD);
7003   }
7004 
7005   // ms_struct is a request to use the same ABI rules as MSVC.  Check
7006   // whether this class uses any C++ features that are implemented
7007   // completely differently in MSVC, and if so, emit a diagnostic.
7008   // That diagnostic defaults to an error, but we allow projects to
7009   // map it down to a warning (or ignore it).  It's a fairly common
7010   // practice among users of the ms_struct pragma to mass-annotate
7011   // headers, sweeping up a bunch of types that the project doesn't
7012   // really rely on MSVC-compatible layout for.  We must therefore
7013   // support "ms_struct except for C++ stuff" as a secondary ABI.
7014   // Don't emit this diagnostic if the feature was enabled as a
7015   // language option (as opposed to via a pragma or attribute), as
7016   // the option -mms-bitfields otherwise essentially makes it impossible
7017   // to build C++ code, unless this diagnostic is turned off.
7018   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7019       (Record->isPolymorphic() || Record->getNumBases())) {
7020     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7021   }
7022 
7023   checkClassLevelDLLAttribute(Record);
7024   checkClassLevelCodeSegAttribute(Record);
7025 
7026   bool ClangABICompat4 =
7027       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7028   TargetInfo::CallingConvKind CCK =
7029       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7030   bool CanPass = canPassInRegisters(*this, Record, CCK);
7031 
7032   // Do not change ArgPassingRestrictions if it has already been set to
7033   // APK_CanNeverPassInRegs.
7034   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
7035     Record->setArgPassingRestrictions(CanPass
7036                                           ? RecordDecl::APK_CanPassInRegs
7037                                           : RecordDecl::APK_CannotPassInRegs);
7038 
7039   // If canPassInRegisters returns true despite the record having a non-trivial
7040   // destructor, the record is destructed in the callee. This happens only when
7041   // the record or one of its subobjects has a field annotated with trivial_abi
7042   // or a field qualified with ObjC __strong/__weak.
7043   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7044     Record->setParamDestroyedInCallee(true);
7045   else if (Record->hasNonTrivialDestructor())
7046     Record->setParamDestroyedInCallee(CanPass);
7047 
7048   if (getLangOpts().ForceEmitVTables) {
7049     // If we want to emit all the vtables, we need to mark it as used.  This
7050     // is especially required for cases like vtable assumption loads.
7051     MarkVTableUsed(Record->getInnerLocStart(), Record);
7052   }
7053 
7054   if (getLangOpts().CUDA) {
7055     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7056       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7057     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7058       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7059   }
7060 }
7061 
7062 /// Look up the special member function that would be called by a special
7063 /// member function for a subobject of class type.
7064 ///
7065 /// \param Class The class type of the subobject.
7066 /// \param CSM The kind of special member function.
7067 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7068 /// \param ConstRHS True if this is a copy operation with a const object
7069 ///        on its RHS, that is, if the argument to the outer special member
7070 ///        function is 'const' and this is not a field marked 'mutable'.
7071 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7072     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7073     unsigned FieldQuals, bool ConstRHS) {
7074   unsigned LHSQuals = 0;
7075   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7076     LHSQuals = FieldQuals;
7077 
7078   unsigned RHSQuals = FieldQuals;
7079   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7080     RHSQuals = 0;
7081   else if (ConstRHS)
7082     RHSQuals |= Qualifiers::Const;
7083 
7084   return S.LookupSpecialMember(Class, CSM,
7085                                RHSQuals & Qualifiers::Const,
7086                                RHSQuals & Qualifiers::Volatile,
7087                                false,
7088                                LHSQuals & Qualifiers::Const,
7089                                LHSQuals & Qualifiers::Volatile);
7090 }
7091 
7092 class Sema::InheritedConstructorInfo {
7093   Sema &S;
7094   SourceLocation UseLoc;
7095 
7096   /// A mapping from the base classes through which the constructor was
7097   /// inherited to the using shadow declaration in that base class (or a null
7098   /// pointer if the constructor was declared in that base class).
7099   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7100       InheritedFromBases;
7101 
7102 public:
7103   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7104                            ConstructorUsingShadowDecl *Shadow)
7105       : S(S), UseLoc(UseLoc) {
7106     bool DiagnosedMultipleConstructedBases = false;
7107     CXXRecordDecl *ConstructedBase = nullptr;
7108     BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7109 
7110     // Find the set of such base class subobjects and check that there's a
7111     // unique constructed subobject.
7112     for (auto *D : Shadow->redecls()) {
7113       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7114       auto *DNominatedBase = DShadow->getNominatedBaseClass();
7115       auto *DConstructedBase = DShadow->getConstructedBaseClass();
7116 
7117       InheritedFromBases.insert(
7118           std::make_pair(DNominatedBase->getCanonicalDecl(),
7119                          DShadow->getNominatedBaseClassShadowDecl()));
7120       if (DShadow->constructsVirtualBase())
7121         InheritedFromBases.insert(
7122             std::make_pair(DConstructedBase->getCanonicalDecl(),
7123                            DShadow->getConstructedBaseClassShadowDecl()));
7124       else
7125         assert(DNominatedBase == DConstructedBase);
7126 
7127       // [class.inhctor.init]p2:
7128       //   If the constructor was inherited from multiple base class subobjects
7129       //   of type B, the program is ill-formed.
7130       if (!ConstructedBase) {
7131         ConstructedBase = DConstructedBase;
7132         ConstructedBaseIntroducer = D->getIntroducer();
7133       } else if (ConstructedBase != DConstructedBase &&
7134                  !Shadow->isInvalidDecl()) {
7135         if (!DiagnosedMultipleConstructedBases) {
7136           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7137               << Shadow->getTargetDecl();
7138           S.Diag(ConstructedBaseIntroducer->getLocation(),
7139                  diag::note_ambiguous_inherited_constructor_using)
7140               << ConstructedBase;
7141           DiagnosedMultipleConstructedBases = true;
7142         }
7143         S.Diag(D->getIntroducer()->getLocation(),
7144                diag::note_ambiguous_inherited_constructor_using)
7145             << DConstructedBase;
7146       }
7147     }
7148 
7149     if (DiagnosedMultipleConstructedBases)
7150       Shadow->setInvalidDecl();
7151   }
7152 
7153   /// Find the constructor to use for inherited construction of a base class,
7154   /// and whether that base class constructor inherits the constructor from a
7155   /// virtual base class (in which case it won't actually invoke it).
7156   std::pair<CXXConstructorDecl *, bool>
7157   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7158     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7159     if (It == InheritedFromBases.end())
7160       return std::make_pair(nullptr, false);
7161 
7162     // This is an intermediary class.
7163     if (It->second)
7164       return std::make_pair(
7165           S.findInheritingConstructor(UseLoc, Ctor, It->second),
7166           It->second->constructsVirtualBase());
7167 
7168     // This is the base class from which the constructor was inherited.
7169     return std::make_pair(Ctor, false);
7170   }
7171 };
7172 
7173 /// Is the special member function which would be selected to perform the
7174 /// specified operation on the specified class type a constexpr constructor?
7175 static bool
7176 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7177                          Sema::CXXSpecialMember CSM, unsigned Quals,
7178                          bool ConstRHS,
7179                          CXXConstructorDecl *InheritedCtor = nullptr,
7180                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7181   // If we're inheriting a constructor, see if we need to call it for this base
7182   // class.
7183   if (InheritedCtor) {
7184     assert(CSM == Sema::CXXDefaultConstructor);
7185     auto BaseCtor =
7186         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7187     if (BaseCtor)
7188       return BaseCtor->isConstexpr();
7189   }
7190 
7191   if (CSM == Sema::CXXDefaultConstructor)
7192     return ClassDecl->hasConstexprDefaultConstructor();
7193   if (CSM == Sema::CXXDestructor)
7194     return ClassDecl->hasConstexprDestructor();
7195 
7196   Sema::SpecialMemberOverloadResult SMOR =
7197       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7198   if (!SMOR.getMethod())
7199     // A constructor we wouldn't select can't be "involved in initializing"
7200     // anything.
7201     return true;
7202   return SMOR.getMethod()->isConstexpr();
7203 }
7204 
7205 /// Determine whether the specified special member function would be constexpr
7206 /// if it were implicitly defined.
7207 static bool defaultedSpecialMemberIsConstexpr(
7208     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7209     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7210     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7211   if (!S.getLangOpts().CPlusPlus11)
7212     return false;
7213 
7214   // C++11 [dcl.constexpr]p4:
7215   // In the definition of a constexpr constructor [...]
7216   bool Ctor = true;
7217   switch (CSM) {
7218   case Sema::CXXDefaultConstructor:
7219     if (Inherited)
7220       break;
7221     // Since default constructor lookup is essentially trivial (and cannot
7222     // involve, for instance, template instantiation), we compute whether a
7223     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7224     //
7225     // This is important for performance; we need to know whether the default
7226     // constructor is constexpr to determine whether the type is a literal type.
7227     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7228 
7229   case Sema::CXXCopyConstructor:
7230   case Sema::CXXMoveConstructor:
7231     // For copy or move constructors, we need to perform overload resolution.
7232     break;
7233 
7234   case Sema::CXXCopyAssignment:
7235   case Sema::CXXMoveAssignment:
7236     if (!S.getLangOpts().CPlusPlus14)
7237       return false;
7238     // In C++1y, we need to perform overload resolution.
7239     Ctor = false;
7240     break;
7241 
7242   case Sema::CXXDestructor:
7243     return ClassDecl->defaultedDestructorIsConstexpr();
7244 
7245   case Sema::CXXInvalid:
7246     return false;
7247   }
7248 
7249   //   -- if the class is a non-empty union, or for each non-empty anonymous
7250   //      union member of a non-union class, exactly one non-static data member
7251   //      shall be initialized; [DR1359]
7252   //
7253   // If we squint, this is guaranteed, since exactly one non-static data member
7254   // will be initialized (if the constructor isn't deleted), we just don't know
7255   // which one.
7256   if (Ctor && ClassDecl->isUnion())
7257     return CSM == Sema::CXXDefaultConstructor
7258                ? ClassDecl->hasInClassInitializer() ||
7259                      !ClassDecl->hasVariantMembers()
7260                : true;
7261 
7262   //   -- the class shall not have any virtual base classes;
7263   if (Ctor && ClassDecl->getNumVBases())
7264     return false;
7265 
7266   // C++1y [class.copy]p26:
7267   //   -- [the class] is a literal type, and
7268   if (!Ctor && !ClassDecl->isLiteral())
7269     return false;
7270 
7271   //   -- every constructor involved in initializing [...] base class
7272   //      sub-objects shall be a constexpr constructor;
7273   //   -- the assignment operator selected to copy/move each direct base
7274   //      class is a constexpr function, and
7275   for (const auto &B : ClassDecl->bases()) {
7276     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7277     if (!BaseType) continue;
7278 
7279     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7280     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7281                                   InheritedCtor, Inherited))
7282       return false;
7283   }
7284 
7285   //   -- every constructor involved in initializing non-static data members
7286   //      [...] shall be a constexpr constructor;
7287   //   -- every non-static data member and base class sub-object shall be
7288   //      initialized
7289   //   -- for each non-static data member of X that is of class type (or array
7290   //      thereof), the assignment operator selected to copy/move that member is
7291   //      a constexpr function
7292   for (const auto *F : ClassDecl->fields()) {
7293     if (F->isInvalidDecl())
7294       continue;
7295     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7296       continue;
7297     QualType BaseType = S.Context.getBaseElementType(F->getType());
7298     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7299       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7300       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7301                                     BaseType.getCVRQualifiers(),
7302                                     ConstArg && !F->isMutable()))
7303         return false;
7304     } else if (CSM == Sema::CXXDefaultConstructor) {
7305       return false;
7306     }
7307   }
7308 
7309   // All OK, it's constexpr!
7310   return true;
7311 }
7312 
7313 namespace {
7314 /// RAII object to register a defaulted function as having its exception
7315 /// specification computed.
7316 struct ComputingExceptionSpec {
7317   Sema &S;
7318 
7319   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7320       : S(S) {
7321     Sema::CodeSynthesisContext Ctx;
7322     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7323     Ctx.PointOfInstantiation = Loc;
7324     Ctx.Entity = FD;
7325     S.pushCodeSynthesisContext(Ctx);
7326   }
7327   ~ComputingExceptionSpec() {
7328     S.popCodeSynthesisContext();
7329   }
7330 };
7331 }
7332 
7333 static Sema::ImplicitExceptionSpecification
7334 ComputeDefaultedSpecialMemberExceptionSpec(
7335     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7336     Sema::InheritedConstructorInfo *ICI);
7337 
7338 static Sema::ImplicitExceptionSpecification
7339 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7340                                         FunctionDecl *FD,
7341                                         Sema::DefaultedComparisonKind DCK);
7342 
7343 static Sema::ImplicitExceptionSpecification
7344 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7345   auto DFK = S.getDefaultedFunctionKind(FD);
7346   if (DFK.isSpecialMember())
7347     return ComputeDefaultedSpecialMemberExceptionSpec(
7348         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7349   if (DFK.isComparison())
7350     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7351                                                    DFK.asComparison());
7352 
7353   auto *CD = cast<CXXConstructorDecl>(FD);
7354   assert(CD->getInheritedConstructor() &&
7355          "only defaulted functions and inherited constructors have implicit "
7356          "exception specs");
7357   Sema::InheritedConstructorInfo ICI(
7358       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7359   return ComputeDefaultedSpecialMemberExceptionSpec(
7360       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7361 }
7362 
7363 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7364                                                             CXXMethodDecl *MD) {
7365   FunctionProtoType::ExtProtoInfo EPI;
7366 
7367   // Build an exception specification pointing back at this member.
7368   EPI.ExceptionSpec.Type = EST_Unevaluated;
7369   EPI.ExceptionSpec.SourceDecl = MD;
7370 
7371   // Set the calling convention to the default for C++ instance methods.
7372   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7373       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7374                                             /*IsCXXMethod=*/true));
7375   return EPI;
7376 }
7377 
7378 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7379   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7380   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7381     return;
7382 
7383   // Evaluate the exception specification.
7384   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7385   auto ESI = IES.getExceptionSpec();
7386 
7387   // Update the type of the special member to use it.
7388   UpdateExceptionSpec(FD, ESI);
7389 }
7390 
7391 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7392   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7393 
7394   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7395   if (!DefKind) {
7396     assert(FD->getDeclContext()->isDependentContext());
7397     return;
7398   }
7399 
7400   if (DefKind.isComparison())
7401     UnusedPrivateFields.clear();
7402 
7403   if (DefKind.isSpecialMember()
7404           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7405                                                   DefKind.asSpecialMember())
7406           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7407     FD->setInvalidDecl();
7408 }
7409 
7410 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7411                                                  CXXSpecialMember CSM) {
7412   CXXRecordDecl *RD = MD->getParent();
7413 
7414   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7415          "not an explicitly-defaulted special member");
7416 
7417   // Defer all checking for special members of a dependent type.
7418   if (RD->isDependentType())
7419     return false;
7420 
7421   // Whether this was the first-declared instance of the constructor.
7422   // This affects whether we implicitly add an exception spec and constexpr.
7423   bool First = MD == MD->getCanonicalDecl();
7424 
7425   bool HadError = false;
7426 
7427   // C++11 [dcl.fct.def.default]p1:
7428   //   A function that is explicitly defaulted shall
7429   //     -- be a special member function [...] (checked elsewhere),
7430   //     -- have the same type (except for ref-qualifiers, and except that a
7431   //        copy operation can take a non-const reference) as an implicit
7432   //        declaration, and
7433   //     -- not have default arguments.
7434   // C++2a changes the second bullet to instead delete the function if it's
7435   // defaulted on its first declaration, unless it's "an assignment operator,
7436   // and its return type differs or its parameter type is not a reference".
7437   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7438   bool ShouldDeleteForTypeMismatch = false;
7439   unsigned ExpectedParams = 1;
7440   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7441     ExpectedParams = 0;
7442   if (MD->getNumParams() != ExpectedParams) {
7443     // This checks for default arguments: a copy or move constructor with a
7444     // default argument is classified as a default constructor, and assignment
7445     // operations and destructors can't have default arguments.
7446     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7447       << CSM << MD->getSourceRange();
7448     HadError = true;
7449   } else if (MD->isVariadic()) {
7450     if (DeleteOnTypeMismatch)
7451       ShouldDeleteForTypeMismatch = true;
7452     else {
7453       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7454         << CSM << MD->getSourceRange();
7455       HadError = true;
7456     }
7457   }
7458 
7459   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7460 
7461   bool CanHaveConstParam = false;
7462   if (CSM == CXXCopyConstructor)
7463     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7464   else if (CSM == CXXCopyAssignment)
7465     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7466 
7467   QualType ReturnType = Context.VoidTy;
7468   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7469     // Check for return type matching.
7470     ReturnType = Type->getReturnType();
7471 
7472     QualType DeclType = Context.getTypeDeclType(RD);
7473     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7474     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7475 
7476     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7477       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7478         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7479       HadError = true;
7480     }
7481 
7482     // A defaulted special member cannot have cv-qualifiers.
7483     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7484       if (DeleteOnTypeMismatch)
7485         ShouldDeleteForTypeMismatch = true;
7486       else {
7487         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7488           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7489         HadError = true;
7490       }
7491     }
7492   }
7493 
7494   // Check for parameter type matching.
7495   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7496   bool HasConstParam = false;
7497   if (ExpectedParams && ArgType->isReferenceType()) {
7498     // Argument must be reference to possibly-const T.
7499     QualType ReferentType = ArgType->getPointeeType();
7500     HasConstParam = ReferentType.isConstQualified();
7501 
7502     if (ReferentType.isVolatileQualified()) {
7503       if (DeleteOnTypeMismatch)
7504         ShouldDeleteForTypeMismatch = true;
7505       else {
7506         Diag(MD->getLocation(),
7507              diag::err_defaulted_special_member_volatile_param) << CSM;
7508         HadError = true;
7509       }
7510     }
7511 
7512     if (HasConstParam && !CanHaveConstParam) {
7513       if (DeleteOnTypeMismatch)
7514         ShouldDeleteForTypeMismatch = true;
7515       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7516         Diag(MD->getLocation(),
7517              diag::err_defaulted_special_member_copy_const_param)
7518           << (CSM == CXXCopyAssignment);
7519         // FIXME: Explain why this special member can't be const.
7520         HadError = true;
7521       } else {
7522         Diag(MD->getLocation(),
7523              diag::err_defaulted_special_member_move_const_param)
7524           << (CSM == CXXMoveAssignment);
7525         HadError = true;
7526       }
7527     }
7528   } else if (ExpectedParams) {
7529     // A copy assignment operator can take its argument by value, but a
7530     // defaulted one cannot.
7531     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7532     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7533     HadError = true;
7534   }
7535 
7536   // C++11 [dcl.fct.def.default]p2:
7537   //   An explicitly-defaulted function may be declared constexpr only if it
7538   //   would have been implicitly declared as constexpr,
7539   // Do not apply this rule to members of class templates, since core issue 1358
7540   // makes such functions always instantiate to constexpr functions. For
7541   // functions which cannot be constexpr (for non-constructors in C++11 and for
7542   // destructors in C++14 and C++17), this is checked elsewhere.
7543   //
7544   // FIXME: This should not apply if the member is deleted.
7545   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7546                                                      HasConstParam);
7547   if ((getLangOpts().CPlusPlus20 ||
7548        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7549                                   : isa<CXXConstructorDecl>(MD))) &&
7550       MD->isConstexpr() && !Constexpr &&
7551       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7552     Diag(MD->getBeginLoc(), MD->isConsteval()
7553                                 ? diag::err_incorrect_defaulted_consteval
7554                                 : diag::err_incorrect_defaulted_constexpr)
7555         << CSM;
7556     // FIXME: Explain why the special member can't be constexpr.
7557     HadError = true;
7558   }
7559 
7560   if (First) {
7561     // C++2a [dcl.fct.def.default]p3:
7562     //   If a function is explicitly defaulted on its first declaration, it is
7563     //   implicitly considered to be constexpr if the implicit declaration
7564     //   would be.
7565     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7566                                           ? ConstexprSpecKind::Consteval
7567                                           : ConstexprSpecKind::Constexpr)
7568                                    : ConstexprSpecKind::Unspecified);
7569 
7570     if (!Type->hasExceptionSpec()) {
7571       // C++2a [except.spec]p3:
7572       //   If a declaration of a function does not have a noexcept-specifier
7573       //   [and] is defaulted on its first declaration, [...] the exception
7574       //   specification is as specified below
7575       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7576       EPI.ExceptionSpec.Type = EST_Unevaluated;
7577       EPI.ExceptionSpec.SourceDecl = MD;
7578       MD->setType(Context.getFunctionType(ReturnType,
7579                                           llvm::makeArrayRef(&ArgType,
7580                                                              ExpectedParams),
7581                                           EPI));
7582     }
7583   }
7584 
7585   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7586     if (First) {
7587       SetDeclDeleted(MD, MD->getLocation());
7588       if (!inTemplateInstantiation() && !HadError) {
7589         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7590         if (ShouldDeleteForTypeMismatch) {
7591           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7592         } else {
7593           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7594         }
7595       }
7596       if (ShouldDeleteForTypeMismatch && !HadError) {
7597         Diag(MD->getLocation(),
7598              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7599       }
7600     } else {
7601       // C++11 [dcl.fct.def.default]p4:
7602       //   [For a] user-provided explicitly-defaulted function [...] if such a
7603       //   function is implicitly defined as deleted, the program is ill-formed.
7604       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7605       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7606       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7607       HadError = true;
7608     }
7609   }
7610 
7611   return HadError;
7612 }
7613 
7614 namespace {
7615 /// Helper class for building and checking a defaulted comparison.
7616 ///
7617 /// Defaulted functions are built in two phases:
7618 ///
7619 ///  * First, the set of operations that the function will perform are
7620 ///    identified, and some of them are checked. If any of the checked
7621 ///    operations is invalid in certain ways, the comparison function is
7622 ///    defined as deleted and no body is built.
7623 ///  * Then, if the function is not defined as deleted, the body is built.
7624 ///
7625 /// This is accomplished by performing two visitation steps over the eventual
7626 /// body of the function.
7627 template<typename Derived, typename ResultList, typename Result,
7628          typename Subobject>
7629 class DefaultedComparisonVisitor {
7630 public:
7631   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7632 
7633   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7634                              DefaultedComparisonKind DCK)
7635       : S(S), RD(RD), FD(FD), DCK(DCK) {
7636     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7637       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7638       // UnresolvedSet to avoid this copy.
7639       Fns.assign(Info->getUnqualifiedLookups().begin(),
7640                  Info->getUnqualifiedLookups().end());
7641     }
7642   }
7643 
7644   ResultList visit() {
7645     // The type of an lvalue naming a parameter of this function.
7646     QualType ParamLvalType =
7647         FD->getParamDecl(0)->getType().getNonReferenceType();
7648 
7649     ResultList Results;
7650 
7651     switch (DCK) {
7652     case DefaultedComparisonKind::None:
7653       llvm_unreachable("not a defaulted comparison");
7654 
7655     case DefaultedComparisonKind::Equal:
7656     case DefaultedComparisonKind::ThreeWay:
7657       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7658       return Results;
7659 
7660     case DefaultedComparisonKind::NotEqual:
7661     case DefaultedComparisonKind::Relational:
7662       Results.add(getDerived().visitExpandedSubobject(
7663           ParamLvalType, getDerived().getCompleteObject()));
7664       return Results;
7665     }
7666     llvm_unreachable("");
7667   }
7668 
7669 protected:
7670   Derived &getDerived() { return static_cast<Derived&>(*this); }
7671 
7672   /// Visit the expanded list of subobjects of the given type, as specified in
7673   /// C++2a [class.compare.default].
7674   ///
7675   /// \return \c true if the ResultList object said we're done, \c false if not.
7676   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7677                        Qualifiers Quals) {
7678     // C++2a [class.compare.default]p4:
7679     //   The direct base class subobjects of C
7680     for (CXXBaseSpecifier &Base : Record->bases())
7681       if (Results.add(getDerived().visitSubobject(
7682               S.Context.getQualifiedType(Base.getType(), Quals),
7683               getDerived().getBase(&Base))))
7684         return true;
7685 
7686     //   followed by the non-static data members of C
7687     for (FieldDecl *Field : Record->fields()) {
7688       // Recursively expand anonymous structs.
7689       if (Field->isAnonymousStructOrUnion()) {
7690         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7691                             Quals))
7692           return true;
7693         continue;
7694       }
7695 
7696       // Figure out the type of an lvalue denoting this field.
7697       Qualifiers FieldQuals = Quals;
7698       if (Field->isMutable())
7699         FieldQuals.removeConst();
7700       QualType FieldType =
7701           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7702 
7703       if (Results.add(getDerived().visitSubobject(
7704               FieldType, getDerived().getField(Field))))
7705         return true;
7706     }
7707 
7708     //   form a list of subobjects.
7709     return false;
7710   }
7711 
7712   Result visitSubobject(QualType Type, Subobject Subobj) {
7713     //   In that list, any subobject of array type is recursively expanded
7714     const ArrayType *AT = S.Context.getAsArrayType(Type);
7715     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7716       return getDerived().visitSubobjectArray(CAT->getElementType(),
7717                                               CAT->getSize(), Subobj);
7718     return getDerived().visitExpandedSubobject(Type, Subobj);
7719   }
7720 
7721   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7722                              Subobject Subobj) {
7723     return getDerived().visitSubobject(Type, Subobj);
7724   }
7725 
7726 protected:
7727   Sema &S;
7728   CXXRecordDecl *RD;
7729   FunctionDecl *FD;
7730   DefaultedComparisonKind DCK;
7731   UnresolvedSet<16> Fns;
7732 };
7733 
7734 /// Information about a defaulted comparison, as determined by
7735 /// DefaultedComparisonAnalyzer.
7736 struct DefaultedComparisonInfo {
7737   bool Deleted = false;
7738   bool Constexpr = true;
7739   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7740 
7741   static DefaultedComparisonInfo deleted() {
7742     DefaultedComparisonInfo Deleted;
7743     Deleted.Deleted = true;
7744     return Deleted;
7745   }
7746 
7747   bool add(const DefaultedComparisonInfo &R) {
7748     Deleted |= R.Deleted;
7749     Constexpr &= R.Constexpr;
7750     Category = commonComparisonType(Category, R.Category);
7751     return Deleted;
7752   }
7753 };
7754 
7755 /// An element in the expanded list of subobjects of a defaulted comparison, as
7756 /// specified in C++2a [class.compare.default]p4.
7757 struct DefaultedComparisonSubobject {
7758   enum { CompleteObject, Member, Base } Kind;
7759   NamedDecl *Decl;
7760   SourceLocation Loc;
7761 };
7762 
7763 /// A visitor over the notional body of a defaulted comparison that determines
7764 /// whether that body would be deleted or constexpr.
7765 class DefaultedComparisonAnalyzer
7766     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7767                                         DefaultedComparisonInfo,
7768                                         DefaultedComparisonInfo,
7769                                         DefaultedComparisonSubobject> {
7770 public:
7771   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7772 
7773 private:
7774   DiagnosticKind Diagnose;
7775 
7776 public:
7777   using Base = DefaultedComparisonVisitor;
7778   using Result = DefaultedComparisonInfo;
7779   using Subobject = DefaultedComparisonSubobject;
7780 
7781   friend Base;
7782 
7783   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7784                               DefaultedComparisonKind DCK,
7785                               DiagnosticKind Diagnose = NoDiagnostics)
7786       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7787 
7788   Result visit() {
7789     if ((DCK == DefaultedComparisonKind::Equal ||
7790          DCK == DefaultedComparisonKind::ThreeWay) &&
7791         RD->hasVariantMembers()) {
7792       // C++2a [class.compare.default]p2 [P2002R0]:
7793       //   A defaulted comparison operator function for class C is defined as
7794       //   deleted if [...] C has variant members.
7795       if (Diagnose == ExplainDeleted) {
7796         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7797           << FD << RD->isUnion() << RD;
7798       }
7799       return Result::deleted();
7800     }
7801 
7802     return Base::visit();
7803   }
7804 
7805 private:
7806   Subobject getCompleteObject() {
7807     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7808   }
7809 
7810   Subobject getBase(CXXBaseSpecifier *Base) {
7811     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7812                      Base->getBaseTypeLoc()};
7813   }
7814 
7815   Subobject getField(FieldDecl *Field) {
7816     return Subobject{Subobject::Member, Field, Field->getLocation()};
7817   }
7818 
7819   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7820     // C++2a [class.compare.default]p2 [P2002R0]:
7821     //   A defaulted <=> or == operator function for class C is defined as
7822     //   deleted if any non-static data member of C is of reference type
7823     if (Type->isReferenceType()) {
7824       if (Diagnose == ExplainDeleted) {
7825         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7826             << FD << RD;
7827       }
7828       return Result::deleted();
7829     }
7830 
7831     // [...] Let xi be an lvalue denoting the ith element [...]
7832     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7833     Expr *Args[] = {&Xi, &Xi};
7834 
7835     // All operators start by trying to apply that same operator recursively.
7836     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7837     assert(OO != OO_None && "not an overloaded operator!");
7838     return visitBinaryOperator(OO, Args, Subobj);
7839   }
7840 
7841   Result
7842   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7843                       Subobject Subobj,
7844                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7845     // Note that there is no need to consider rewritten candidates here if
7846     // we've already found there is no viable 'operator<=>' candidate (and are
7847     // considering synthesizing a '<=>' from '==' and '<').
7848     OverloadCandidateSet CandidateSet(
7849         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7850         OverloadCandidateSet::OperatorRewriteInfo(
7851             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7852 
7853     /// C++2a [class.compare.default]p1 [P2002R0]:
7854     ///   [...] the defaulted function itself is never a candidate for overload
7855     ///   resolution [...]
7856     CandidateSet.exclude(FD);
7857 
7858     if (Args[0]->getType()->isOverloadableType())
7859       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7860     else
7861       // FIXME: We determine whether this is a valid expression by checking to
7862       // see if there's a viable builtin operator candidate for it. That isn't
7863       // really what the rules ask us to do, but should give the right results.
7864       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7865 
7866     Result R;
7867 
7868     OverloadCandidateSet::iterator Best;
7869     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7870     case OR_Success: {
7871       // C++2a [class.compare.secondary]p2 [P2002R0]:
7872       //   The operator function [...] is defined as deleted if [...] the
7873       //   candidate selected by overload resolution is not a rewritten
7874       //   candidate.
7875       if ((DCK == DefaultedComparisonKind::NotEqual ||
7876            DCK == DefaultedComparisonKind::Relational) &&
7877           !Best->RewriteKind) {
7878         if (Diagnose == ExplainDeleted) {
7879           if (Best->Function) {
7880             S.Diag(Best->Function->getLocation(),
7881                    diag::note_defaulted_comparison_not_rewritten_callee)
7882                 << FD;
7883           } else {
7884             assert(Best->Conversions.size() == 2 &&
7885                    Best->Conversions[0].isUserDefined() &&
7886                    "non-user-defined conversion from class to built-in "
7887                    "comparison");
7888             S.Diag(Best->Conversions[0]
7889                        .UserDefined.FoundConversionFunction.getDecl()
7890                        ->getLocation(),
7891                    diag::note_defaulted_comparison_not_rewritten_conversion)
7892                 << FD;
7893           }
7894         }
7895         return Result::deleted();
7896       }
7897 
7898       // Throughout C++2a [class.compare]: if overload resolution does not
7899       // result in a usable function, the candidate function is defined as
7900       // deleted. This requires that we selected an accessible function.
7901       //
7902       // Note that this only considers the access of the function when named
7903       // within the type of the subobject, and not the access path for any
7904       // derived-to-base conversion.
7905       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7906       if (ArgClass && Best->FoundDecl.getDecl() &&
7907           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7908         QualType ObjectType = Subobj.Kind == Subobject::Member
7909                                   ? Args[0]->getType()
7910                                   : S.Context.getRecordType(RD);
7911         if (!S.isMemberAccessibleForDeletion(
7912                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7913                 Diagnose == ExplainDeleted
7914                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7915                           << FD << Subobj.Kind << Subobj.Decl
7916                     : S.PDiag()))
7917           return Result::deleted();
7918       }
7919 
7920       bool NeedsDeducing =
7921           OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7922 
7923       if (FunctionDecl *BestFD = Best->Function) {
7924         // C++2a [class.compare.default]p3 [P2002R0]:
7925         //   A defaulted comparison function is constexpr-compatible if
7926         //   [...] no overlod resolution performed [...] results in a
7927         //   non-constexpr function.
7928         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7929         // If it's not constexpr, explain why not.
7930         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7931           if (Subobj.Kind != Subobject::CompleteObject)
7932             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7933               << Subobj.Kind << Subobj.Decl;
7934           S.Diag(BestFD->getLocation(),
7935                  diag::note_defaulted_comparison_not_constexpr_here);
7936           // Bail out after explaining; we don't want any more notes.
7937           return Result::deleted();
7938         }
7939         R.Constexpr &= BestFD->isConstexpr();
7940 
7941         if (NeedsDeducing) {
7942           // If any callee has an undeduced return type, deduce it now.
7943           // FIXME: It's not clear how a failure here should be handled. For
7944           // now, we produce an eager diagnostic, because that is forward
7945           // compatible with most (all?) other reasonable options.
7946           if (BestFD->getReturnType()->isUndeducedType() &&
7947               S.DeduceReturnType(BestFD, FD->getLocation(),
7948                                  /*Diagnose=*/false)) {
7949             // Don't produce a duplicate error when asked to explain why the
7950             // comparison is deleted: we diagnosed that when initially checking
7951             // the defaulted operator.
7952             if (Diagnose == NoDiagnostics) {
7953               S.Diag(
7954                   FD->getLocation(),
7955                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7956                   << Subobj.Kind << Subobj.Decl;
7957               S.Diag(
7958                   Subobj.Loc,
7959                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7960                   << Subobj.Kind << Subobj.Decl;
7961               S.Diag(BestFD->getLocation(),
7962                      diag::note_defaulted_comparison_cannot_deduce_callee)
7963                   << Subobj.Kind << Subobj.Decl;
7964             }
7965             return Result::deleted();
7966           }
7967           auto *Info = S.Context.CompCategories.lookupInfoForType(
7968               BestFD->getCallResultType());
7969           if (!Info) {
7970             if (Diagnose == ExplainDeleted) {
7971               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7972                   << Subobj.Kind << Subobj.Decl
7973                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7974               S.Diag(BestFD->getLocation(),
7975                      diag::note_defaulted_comparison_cannot_deduce_callee)
7976                   << Subobj.Kind << Subobj.Decl;
7977             }
7978             return Result::deleted();
7979           }
7980           R.Category = Info->Kind;
7981         }
7982       } else {
7983         QualType T = Best->BuiltinParamTypes[0];
7984         assert(T == Best->BuiltinParamTypes[1] &&
7985                "builtin comparison for different types?");
7986         assert(Best->BuiltinParamTypes[2].isNull() &&
7987                "invalid builtin comparison");
7988 
7989         if (NeedsDeducing) {
7990           Optional<ComparisonCategoryType> Cat =
7991               getComparisonCategoryForBuiltinCmp(T);
7992           assert(Cat && "no category for builtin comparison?");
7993           R.Category = *Cat;
7994         }
7995       }
7996 
7997       // Note that we might be rewriting to a different operator. That call is
7998       // not considered until we come to actually build the comparison function.
7999       break;
8000     }
8001 
8002     case OR_Ambiguous:
8003       if (Diagnose == ExplainDeleted) {
8004         unsigned Kind = 0;
8005         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8006           Kind = OO == OO_EqualEqual ? 1 : 2;
8007         CandidateSet.NoteCandidates(
8008             PartialDiagnosticAt(
8009                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8010                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
8011             S, OCD_AmbiguousCandidates, Args);
8012       }
8013       R = Result::deleted();
8014       break;
8015 
8016     case OR_Deleted:
8017       if (Diagnose == ExplainDeleted) {
8018         if ((DCK == DefaultedComparisonKind::NotEqual ||
8019              DCK == DefaultedComparisonKind::Relational) &&
8020             !Best->RewriteKind) {
8021           S.Diag(Best->Function->getLocation(),
8022                  diag::note_defaulted_comparison_not_rewritten_callee)
8023               << FD;
8024         } else {
8025           S.Diag(Subobj.Loc,
8026                  diag::note_defaulted_comparison_calls_deleted)
8027               << FD << Subobj.Kind << Subobj.Decl;
8028           S.NoteDeletedFunction(Best->Function);
8029         }
8030       }
8031       R = Result::deleted();
8032       break;
8033 
8034     case OR_No_Viable_Function:
8035       // If there's no usable candidate, we're done unless we can rewrite a
8036       // '<=>' in terms of '==' and '<'.
8037       if (OO == OO_Spaceship &&
8038           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8039         // For any kind of comparison category return type, we need a usable
8040         // '==' and a usable '<'.
8041         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8042                                        &CandidateSet)))
8043           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8044         break;
8045       }
8046 
8047       if (Diagnose == ExplainDeleted) {
8048         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8049             << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
8050 
8051         // For a three-way comparison, list both the candidates for the
8052         // original operator and the candidates for the synthesized operator.
8053         if (SpaceshipCandidates) {
8054           SpaceshipCandidates->NoteCandidates(
8055               S, Args,
8056               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8057                                                       Args, FD->getLocation()));
8058           S.Diag(Subobj.Loc,
8059                  diag::note_defaulted_comparison_no_viable_function_synthesized)
8060               << (OO == OO_EqualEqual ? 0 : 1);
8061         }
8062 
8063         CandidateSet.NoteCandidates(
8064             S, Args,
8065             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8066                                             FD->getLocation()));
8067       }
8068       R = Result::deleted();
8069       break;
8070     }
8071 
8072     return R;
8073   }
8074 };
8075 
8076 /// A list of statements.
8077 struct StmtListResult {
8078   bool IsInvalid = false;
8079   llvm::SmallVector<Stmt*, 16> Stmts;
8080 
8081   bool add(const StmtResult &S) {
8082     IsInvalid |= S.isInvalid();
8083     if (IsInvalid)
8084       return true;
8085     Stmts.push_back(S.get());
8086     return false;
8087   }
8088 };
8089 
8090 /// A visitor over the notional body of a defaulted comparison that synthesizes
8091 /// the actual body.
8092 class DefaultedComparisonSynthesizer
8093     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8094                                         StmtListResult, StmtResult,
8095                                         std::pair<ExprResult, ExprResult>> {
8096   SourceLocation Loc;
8097   unsigned ArrayDepth = 0;
8098 
8099 public:
8100   using Base = DefaultedComparisonVisitor;
8101   using ExprPair = std::pair<ExprResult, ExprResult>;
8102 
8103   friend Base;
8104 
8105   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8106                                  DefaultedComparisonKind DCK,
8107                                  SourceLocation BodyLoc)
8108       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8109 
8110   /// Build a suitable function body for this defaulted comparison operator.
8111   StmtResult build() {
8112     Sema::CompoundScopeRAII CompoundScope(S);
8113 
8114     StmtListResult Stmts = visit();
8115     if (Stmts.IsInvalid)
8116       return StmtError();
8117 
8118     ExprResult RetVal;
8119     switch (DCK) {
8120     case DefaultedComparisonKind::None:
8121       llvm_unreachable("not a defaulted comparison");
8122 
8123     case DefaultedComparisonKind::Equal: {
8124       // C++2a [class.eq]p3:
8125       //   [...] compar[e] the corresponding elements [...] until the first
8126       //   index i where xi == yi yields [...] false. If no such index exists,
8127       //   V is true. Otherwise, V is false.
8128       //
8129       // Join the comparisons with '&&'s and return the result. Use a right
8130       // fold (traversing the conditions right-to-left), because that
8131       // short-circuits more naturally.
8132       auto OldStmts = std::move(Stmts.Stmts);
8133       Stmts.Stmts.clear();
8134       ExprResult CmpSoFar;
8135       // Finish a particular comparison chain.
8136       auto FinishCmp = [&] {
8137         if (Expr *Prior = CmpSoFar.get()) {
8138           // Convert the last expression to 'return ...;'
8139           if (RetVal.isUnset() && Stmts.Stmts.empty())
8140             RetVal = CmpSoFar;
8141           // Convert any prior comparison to 'if (!(...)) return false;'
8142           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8143             return true;
8144           CmpSoFar = ExprResult();
8145         }
8146         return false;
8147       };
8148       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8149         Expr *E = dyn_cast<Expr>(EAsStmt);
8150         if (!E) {
8151           // Found an array comparison.
8152           if (FinishCmp() || Stmts.add(EAsStmt))
8153             return StmtError();
8154           continue;
8155         }
8156 
8157         if (CmpSoFar.isUnset()) {
8158           CmpSoFar = E;
8159           continue;
8160         }
8161         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8162         if (CmpSoFar.isInvalid())
8163           return StmtError();
8164       }
8165       if (FinishCmp())
8166         return StmtError();
8167       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8168       //   If no such index exists, V is true.
8169       if (RetVal.isUnset())
8170         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8171       break;
8172     }
8173 
8174     case DefaultedComparisonKind::ThreeWay: {
8175       // Per C++2a [class.spaceship]p3, as a fallback add:
8176       // return static_cast<R>(std::strong_ordering::equal);
8177       QualType StrongOrdering = S.CheckComparisonCategoryType(
8178           ComparisonCategoryType::StrongOrdering, Loc,
8179           Sema::ComparisonCategoryUsage::DefaultedOperator);
8180       if (StrongOrdering.isNull())
8181         return StmtError();
8182       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8183                              .getValueInfo(ComparisonCategoryResult::Equal)
8184                              ->VD;
8185       RetVal = getDecl(EqualVD);
8186       if (RetVal.isInvalid())
8187         return StmtError();
8188       RetVal = buildStaticCastToR(RetVal.get());
8189       break;
8190     }
8191 
8192     case DefaultedComparisonKind::NotEqual:
8193     case DefaultedComparisonKind::Relational:
8194       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8195       break;
8196     }
8197 
8198     // Build the final return statement.
8199     if (RetVal.isInvalid())
8200       return StmtError();
8201     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8202     if (ReturnStmt.isInvalid())
8203       return StmtError();
8204     Stmts.Stmts.push_back(ReturnStmt.get());
8205 
8206     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8207   }
8208 
8209 private:
8210   ExprResult getDecl(ValueDecl *VD) {
8211     return S.BuildDeclarationNameExpr(
8212         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8213   }
8214 
8215   ExprResult getParam(unsigned I) {
8216     ParmVarDecl *PD = FD->getParamDecl(I);
8217     return getDecl(PD);
8218   }
8219 
8220   ExprPair getCompleteObject() {
8221     unsigned Param = 0;
8222     ExprResult LHS;
8223     if (isa<CXXMethodDecl>(FD)) {
8224       // LHS is '*this'.
8225       LHS = S.ActOnCXXThis(Loc);
8226       if (!LHS.isInvalid())
8227         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8228     } else {
8229       LHS = getParam(Param++);
8230     }
8231     ExprResult RHS = getParam(Param++);
8232     assert(Param == FD->getNumParams());
8233     return {LHS, RHS};
8234   }
8235 
8236   ExprPair getBase(CXXBaseSpecifier *Base) {
8237     ExprPair Obj = getCompleteObject();
8238     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8239       return {ExprError(), ExprError()};
8240     CXXCastPath Path = {Base};
8241     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8242                                 CK_DerivedToBase, VK_LValue, &Path),
8243             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8244                                 CK_DerivedToBase, VK_LValue, &Path)};
8245   }
8246 
8247   ExprPair getField(FieldDecl *Field) {
8248     ExprPair Obj = getCompleteObject();
8249     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8250       return {ExprError(), ExprError()};
8251 
8252     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8253     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8254     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8255                                       CXXScopeSpec(), Field, Found, NameInfo),
8256             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8257                                       CXXScopeSpec(), Field, Found, NameInfo)};
8258   }
8259 
8260   // FIXME: When expanding a subobject, register a note in the code synthesis
8261   // stack to say which subobject we're comparing.
8262 
8263   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8264     if (Cond.isInvalid())
8265       return StmtError();
8266 
8267     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8268     if (NotCond.isInvalid())
8269       return StmtError();
8270 
8271     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8272     assert(!False.isInvalid() && "should never fail");
8273     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8274     if (ReturnFalse.isInvalid())
8275       return StmtError();
8276 
8277     return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8278                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8279                                           Sema::ConditionKind::Boolean),
8280                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8281   }
8282 
8283   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8284                                  ExprPair Subobj) {
8285     QualType SizeType = S.Context.getSizeType();
8286     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8287 
8288     // Build 'size_t i$n = 0'.
8289     IdentifierInfo *IterationVarName = nullptr;
8290     {
8291       SmallString<8> Str;
8292       llvm::raw_svector_ostream OS(Str);
8293       OS << "i" << ArrayDepth;
8294       IterationVarName = &S.Context.Idents.get(OS.str());
8295     }
8296     VarDecl *IterationVar = VarDecl::Create(
8297         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8298         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8299     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8300     IterationVar->setInit(
8301         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8302     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8303 
8304     auto IterRef = [&] {
8305       ExprResult Ref = S.BuildDeclarationNameExpr(
8306           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8307           IterationVar);
8308       assert(!Ref.isInvalid() && "can't reference our own variable?");
8309       return Ref.get();
8310     };
8311 
8312     // Build 'i$n != Size'.
8313     ExprResult Cond = S.CreateBuiltinBinOp(
8314         Loc, BO_NE, IterRef(),
8315         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8316     assert(!Cond.isInvalid() && "should never fail");
8317 
8318     // Build '++i$n'.
8319     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8320     assert(!Inc.isInvalid() && "should never fail");
8321 
8322     // Build 'a[i$n]' and 'b[i$n]'.
8323     auto Index = [&](ExprResult E) {
8324       if (E.isInvalid())
8325         return ExprError();
8326       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8327     };
8328     Subobj.first = Index(Subobj.first);
8329     Subobj.second = Index(Subobj.second);
8330 
8331     // Compare the array elements.
8332     ++ArrayDepth;
8333     StmtResult Substmt = visitSubobject(Type, Subobj);
8334     --ArrayDepth;
8335 
8336     if (Substmt.isInvalid())
8337       return StmtError();
8338 
8339     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8340     // For outer levels or for an 'operator<=>' we already have a suitable
8341     // statement that returns as necessary.
8342     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8343       assert(DCK == DefaultedComparisonKind::Equal &&
8344              "should have non-expression statement");
8345       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8346       if (Substmt.isInvalid())
8347         return StmtError();
8348     }
8349 
8350     // Build 'for (...) ...'
8351     return S.ActOnForStmt(Loc, Loc, Init,
8352                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8353                                            Sema::ConditionKind::Boolean),
8354                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8355                           Substmt.get());
8356   }
8357 
8358   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8359     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8360       return StmtError();
8361 
8362     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8363     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8364     ExprResult Op;
8365     if (Type->isOverloadableType())
8366       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8367                                    Obj.second.get(), /*PerformADL=*/true,
8368                                    /*AllowRewrittenCandidates=*/true, FD);
8369     else
8370       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8371     if (Op.isInvalid())
8372       return StmtError();
8373 
8374     switch (DCK) {
8375     case DefaultedComparisonKind::None:
8376       llvm_unreachable("not a defaulted comparison");
8377 
8378     case DefaultedComparisonKind::Equal:
8379       // Per C++2a [class.eq]p2, each comparison is individually contextually
8380       // converted to bool.
8381       Op = S.PerformContextuallyConvertToBool(Op.get());
8382       if (Op.isInvalid())
8383         return StmtError();
8384       return Op.get();
8385 
8386     case DefaultedComparisonKind::ThreeWay: {
8387       // Per C++2a [class.spaceship]p3, form:
8388       //   if (R cmp = static_cast<R>(op); cmp != 0)
8389       //     return cmp;
8390       QualType R = FD->getReturnType();
8391       Op = buildStaticCastToR(Op.get());
8392       if (Op.isInvalid())
8393         return StmtError();
8394 
8395       // R cmp = ...;
8396       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8397       VarDecl *VD =
8398           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8399                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8400       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8401       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8402 
8403       // cmp != 0
8404       ExprResult VDRef = getDecl(VD);
8405       if (VDRef.isInvalid())
8406         return StmtError();
8407       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8408       Expr *Zero =
8409           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8410       ExprResult Comp;
8411       if (VDRef.get()->getType()->isOverloadableType())
8412         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8413                                        true, FD);
8414       else
8415         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8416       if (Comp.isInvalid())
8417         return StmtError();
8418       Sema::ConditionResult Cond = S.ActOnCondition(
8419           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8420       if (Cond.isInvalid())
8421         return StmtError();
8422 
8423       // return cmp;
8424       VDRef = getDecl(VD);
8425       if (VDRef.isInvalid())
8426         return StmtError();
8427       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8428       if (ReturnStmt.isInvalid())
8429         return StmtError();
8430 
8431       // if (...)
8432       return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8433                            Loc, ReturnStmt.get(),
8434                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8435     }
8436 
8437     case DefaultedComparisonKind::NotEqual:
8438     case DefaultedComparisonKind::Relational:
8439       // C++2a [class.compare.secondary]p2:
8440       //   Otherwise, the operator function yields x @ y.
8441       return Op.get();
8442     }
8443     llvm_unreachable("");
8444   }
8445 
8446   /// Build "static_cast<R>(E)".
8447   ExprResult buildStaticCastToR(Expr *E) {
8448     QualType R = FD->getReturnType();
8449     assert(!R->isUndeducedType() && "type should have been deduced already");
8450 
8451     // Don't bother forming a no-op cast in the common case.
8452     if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8453       return E;
8454     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8455                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8456                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8457   }
8458 };
8459 }
8460 
8461 /// Perform the unqualified lookups that might be needed to form a defaulted
8462 /// comparison function for the given operator.
8463 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8464                                                   UnresolvedSetImpl &Operators,
8465                                                   OverloadedOperatorKind Op) {
8466   auto Lookup = [&](OverloadedOperatorKind OO) {
8467     Self.LookupOverloadedOperatorName(OO, S, Operators);
8468   };
8469 
8470   // Every defaulted operator looks up itself.
8471   Lookup(Op);
8472   // ... and the rewritten form of itself, if any.
8473   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8474     Lookup(ExtraOp);
8475 
8476   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8477   // synthesize a three-way comparison from '<' and '=='. In a dependent
8478   // context, we also need to look up '==' in case we implicitly declare a
8479   // defaulted 'operator=='.
8480   if (Op == OO_Spaceship) {
8481     Lookup(OO_ExclaimEqual);
8482     Lookup(OO_Less);
8483     Lookup(OO_EqualEqual);
8484   }
8485 }
8486 
8487 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8488                                               DefaultedComparisonKind DCK) {
8489   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8490 
8491   // Perform any unqualified lookups we're going to need to default this
8492   // function.
8493   if (S) {
8494     UnresolvedSet<32> Operators;
8495     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8496                                           FD->getOverloadedOperator());
8497     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8498         Context, Operators.pairs()));
8499   }
8500 
8501   // C++2a [class.compare.default]p1:
8502   //   A defaulted comparison operator function for some class C shall be a
8503   //   non-template function declared in the member-specification of C that is
8504   //    -- a non-static const member of C having one parameter of type
8505   //       const C&, or
8506   //    -- a friend of C having two parameters of type const C& or two
8507   //       parameters of type C.
8508 
8509   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8510   bool IsMethod = isa<CXXMethodDecl>(FD);
8511   if (IsMethod) {
8512     auto *MD = cast<CXXMethodDecl>(FD);
8513     assert(!MD->isStatic() && "comparison function cannot be a static member");
8514 
8515     // If we're out-of-class, this is the class we're comparing.
8516     if (!RD)
8517       RD = MD->getParent();
8518 
8519     if (!MD->isConst()) {
8520       SourceLocation InsertLoc;
8521       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8522         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8523       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8524       // corresponding defaulted 'operator<=>' already.
8525       if (!MD->isImplicit()) {
8526         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8527             << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8528       }
8529 
8530       // Add the 'const' to the type to recover.
8531       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8532       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8533       EPI.TypeQuals.addConst();
8534       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8535                                           FPT->getParamTypes(), EPI));
8536     }
8537   }
8538 
8539   if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8540     // Let's not worry about using a variadic template pack here -- who would do
8541     // such a thing?
8542     Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8543         << int(IsMethod) << int(DCK);
8544     return true;
8545   }
8546 
8547   const ParmVarDecl *KnownParm = nullptr;
8548   for (const ParmVarDecl *Param : FD->parameters()) {
8549     QualType ParmTy = Param->getType();
8550     if (ParmTy->isDependentType())
8551       continue;
8552     if (!KnownParm) {
8553       auto CTy = ParmTy;
8554       // Is it `T const &`?
8555       bool Ok = !IsMethod;
8556       QualType ExpectedTy;
8557       if (RD)
8558         ExpectedTy = Context.getRecordType(RD);
8559       if (auto *Ref = CTy->getAs<ReferenceType>()) {
8560         CTy = Ref->getPointeeType();
8561         if (RD)
8562           ExpectedTy.addConst();
8563         Ok = true;
8564       }
8565 
8566       // Is T a class?
8567       if (!Ok) {
8568       } else if (RD) {
8569         if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8570           Ok = false;
8571       } else if (auto *CRD = CTy->getAsRecordDecl()) {
8572         RD = cast<CXXRecordDecl>(CRD);
8573       } else {
8574         Ok = false;
8575       }
8576 
8577       if (Ok) {
8578         KnownParm = Param;
8579       } else {
8580         // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8581         // corresponding defaulted 'operator<=>' already.
8582         if (!FD->isImplicit()) {
8583           if (RD) {
8584             QualType PlainTy = Context.getRecordType(RD);
8585             QualType RefTy =
8586                 Context.getLValueReferenceType(PlainTy.withConst());
8587             Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8588                 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8589                 << Param->getSourceRange();
8590           } else {
8591             assert(!IsMethod && "should know expected type for method");
8592             Diag(FD->getLocation(),
8593                  diag::err_defaulted_comparison_param_unknown)
8594                 << int(DCK) << ParmTy << Param->getSourceRange();
8595           }
8596         }
8597         return true;
8598       }
8599     } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8600       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8601           << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8602           << ParmTy << Param->getSourceRange();
8603       return true;
8604     }
8605   }
8606 
8607   assert(RD && "must have determined class");
8608   if (IsMethod) {
8609   } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8610     // In-class, must be a friend decl.
8611     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8612   } else {
8613     // Out of class, require the defaulted comparison to be a friend (of a
8614     // complete type).
8615     if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8616                             diag::err_defaulted_comparison_not_friend, int(DCK),
8617                             int(1)))
8618       return true;
8619 
8620     if (llvm::find_if(RD->friends(), [&](const FriendDecl *F) {
8621           return FD->getCanonicalDecl() ==
8622                  F->getFriendDecl()->getCanonicalDecl();
8623         }) == RD->friends().end()) {
8624       Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8625           << int(DCK) << int(0) << RD;
8626       Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8627       return true;
8628     }
8629   }
8630 
8631   // C++2a [class.eq]p1, [class.rel]p1:
8632   //   A [defaulted comparison other than <=>] shall have a declared return
8633   //   type bool.
8634   if (DCK != DefaultedComparisonKind::ThreeWay &&
8635       !FD->getDeclaredReturnType()->isDependentType() &&
8636       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8637     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8638         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8639         << FD->getReturnTypeSourceRange();
8640     return true;
8641   }
8642   // C++2a [class.spaceship]p2 [P2002R0]:
8643   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8644   //   R shall not contain a placeholder type.
8645   if (DCK == DefaultedComparisonKind::ThreeWay &&
8646       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8647       !Context.hasSameType(FD->getDeclaredReturnType(),
8648                            Context.getAutoDeductType())) {
8649     Diag(FD->getLocation(),
8650          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8651         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8652         << FD->getReturnTypeSourceRange();
8653     return true;
8654   }
8655 
8656   // For a defaulted function in a dependent class, defer all remaining checks
8657   // until instantiation.
8658   if (RD->isDependentType())
8659     return false;
8660 
8661   // Determine whether the function should be defined as deleted.
8662   DefaultedComparisonInfo Info =
8663       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8664 
8665   bool First = FD == FD->getCanonicalDecl();
8666 
8667   // If we want to delete the function, then do so; there's nothing else to
8668   // check in that case.
8669   if (Info.Deleted) {
8670     if (!First) {
8671       // C++11 [dcl.fct.def.default]p4:
8672       //   [For a] user-provided explicitly-defaulted function [...] if such a
8673       //   function is implicitly defined as deleted, the program is ill-formed.
8674       //
8675       // This is really just a consequence of the general rule that you can
8676       // only delete a function on its first declaration.
8677       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8678           << FD->isImplicit() << (int)DCK;
8679       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8680                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8681           .visit();
8682       return true;
8683     }
8684 
8685     SetDeclDeleted(FD, FD->getLocation());
8686     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8687       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8688           << (int)DCK;
8689       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8690                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8691           .visit();
8692     }
8693     return false;
8694   }
8695 
8696   // C++2a [class.spaceship]p2:
8697   //   The return type is deduced as the common comparison type of R0, R1, ...
8698   if (DCK == DefaultedComparisonKind::ThreeWay &&
8699       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8700     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8701     if (RetLoc.isInvalid())
8702       RetLoc = FD->getBeginLoc();
8703     // FIXME: Should we really care whether we have the complete type and the
8704     // 'enumerator' constants here? A forward declaration seems sufficient.
8705     QualType Cat = CheckComparisonCategoryType(
8706         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8707     if (Cat.isNull())
8708       return true;
8709     Context.adjustDeducedFunctionResultType(
8710         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8711   }
8712 
8713   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8714   //   An explicitly-defaulted function that is not defined as deleted may be
8715   //   declared constexpr or consteval only if it is constexpr-compatible.
8716   // C++2a [class.compare.default]p3 [P2002R0]:
8717   //   A defaulted comparison function is constexpr-compatible if it satisfies
8718   //   the requirements for a constexpr function [...]
8719   // The only relevant requirements are that the parameter and return types are
8720   // literal types. The remaining conditions are checked by the analyzer.
8721   if (FD->isConstexpr()) {
8722     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8723         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8724         !Info.Constexpr) {
8725       Diag(FD->getBeginLoc(),
8726            diag::err_incorrect_defaulted_comparison_constexpr)
8727           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8728       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8729                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8730           .visit();
8731     }
8732   }
8733 
8734   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8735   //   If a constexpr-compatible function is explicitly defaulted on its first
8736   //   declaration, it is implicitly considered to be constexpr.
8737   // FIXME: Only applying this to the first declaration seems problematic, as
8738   // simple reorderings can affect the meaning of the program.
8739   if (First && !FD->isConstexpr() && Info.Constexpr)
8740     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8741 
8742   // C++2a [except.spec]p3:
8743   //   If a declaration of a function does not have a noexcept-specifier
8744   //   [and] is defaulted on its first declaration, [...] the exception
8745   //   specification is as specified below
8746   if (FD->getExceptionSpecType() == EST_None) {
8747     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8748     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8749     EPI.ExceptionSpec.Type = EST_Unevaluated;
8750     EPI.ExceptionSpec.SourceDecl = FD;
8751     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8752                                         FPT->getParamTypes(), EPI));
8753   }
8754 
8755   return false;
8756 }
8757 
8758 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8759                                              FunctionDecl *Spaceship) {
8760   Sema::CodeSynthesisContext Ctx;
8761   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8762   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8763   Ctx.Entity = Spaceship;
8764   pushCodeSynthesisContext(Ctx);
8765 
8766   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8767     EqualEqual->setImplicit();
8768 
8769   popCodeSynthesisContext();
8770 }
8771 
8772 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8773                                      DefaultedComparisonKind DCK) {
8774   assert(FD->isDefaulted() && !FD->isDeleted() &&
8775          !FD->doesThisDeclarationHaveABody());
8776   if (FD->willHaveBody() || FD->isInvalidDecl())
8777     return;
8778 
8779   SynthesizedFunctionScope Scope(*this, FD);
8780 
8781   // Add a context note for diagnostics produced after this point.
8782   Scope.addContextNote(UseLoc);
8783 
8784   {
8785     // Build and set up the function body.
8786     // The first parameter has type maybe-ref-to maybe-const T, use that to get
8787     // the type of the class being compared.
8788     auto PT = FD->getParamDecl(0)->getType();
8789     CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
8790     SourceLocation BodyLoc =
8791         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8792     StmtResult Body =
8793         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8794     if (Body.isInvalid()) {
8795       FD->setInvalidDecl();
8796       return;
8797     }
8798     FD->setBody(Body.get());
8799     FD->markUsed(Context);
8800   }
8801 
8802   // The exception specification is needed because we are defining the
8803   // function. Note that this will reuse the body we just built.
8804   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8805 
8806   if (ASTMutationListener *L = getASTMutationListener())
8807     L->CompletedImplicitDefinition(FD);
8808 }
8809 
8810 static Sema::ImplicitExceptionSpecification
8811 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8812                                         FunctionDecl *FD,
8813                                         Sema::DefaultedComparisonKind DCK) {
8814   ComputingExceptionSpec CES(S, FD, Loc);
8815   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8816 
8817   if (FD->isInvalidDecl())
8818     return ExceptSpec;
8819 
8820   // The common case is that we just defined the comparison function. In that
8821   // case, just look at whether the body can throw.
8822   if (FD->hasBody()) {
8823     ExceptSpec.CalledStmt(FD->getBody());
8824   } else {
8825     // Otherwise, build a body so we can check it. This should ideally only
8826     // happen when we're not actually marking the function referenced. (This is
8827     // only really important for efficiency: we don't want to build and throw
8828     // away bodies for comparison functions more than we strictly need to.)
8829 
8830     // Pretend to synthesize the function body in an unevaluated context.
8831     // Note that we can't actually just go ahead and define the function here:
8832     // we are not permitted to mark its callees as referenced.
8833     Sema::SynthesizedFunctionScope Scope(S, FD);
8834     EnterExpressionEvaluationContext Context(
8835         S, Sema::ExpressionEvaluationContext::Unevaluated);
8836 
8837     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8838     SourceLocation BodyLoc =
8839         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8840     StmtResult Body =
8841         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8842     if (!Body.isInvalid())
8843       ExceptSpec.CalledStmt(Body.get());
8844 
8845     // FIXME: Can we hold onto this body and just transform it to potentially
8846     // evaluated when we're asked to define the function rather than rebuilding
8847     // it? Either that, or we should only build the bits of the body that we
8848     // need (the expressions, not the statements).
8849   }
8850 
8851   return ExceptSpec;
8852 }
8853 
8854 void Sema::CheckDelayedMemberExceptionSpecs() {
8855   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8856   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8857 
8858   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8859   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8860 
8861   // Perform any deferred checking of exception specifications for virtual
8862   // destructors.
8863   for (auto &Check : Overriding)
8864     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8865 
8866   // Perform any deferred checking of exception specifications for befriended
8867   // special members.
8868   for (auto &Check : Equivalent)
8869     CheckEquivalentExceptionSpec(Check.second, Check.first);
8870 }
8871 
8872 namespace {
8873 /// CRTP base class for visiting operations performed by a special member
8874 /// function (or inherited constructor).
8875 template<typename Derived>
8876 struct SpecialMemberVisitor {
8877   Sema &S;
8878   CXXMethodDecl *MD;
8879   Sema::CXXSpecialMember CSM;
8880   Sema::InheritedConstructorInfo *ICI;
8881 
8882   // Properties of the special member, computed for convenience.
8883   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8884 
8885   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8886                        Sema::InheritedConstructorInfo *ICI)
8887       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8888     switch (CSM) {
8889     case Sema::CXXDefaultConstructor:
8890     case Sema::CXXCopyConstructor:
8891     case Sema::CXXMoveConstructor:
8892       IsConstructor = true;
8893       break;
8894     case Sema::CXXCopyAssignment:
8895     case Sema::CXXMoveAssignment:
8896       IsAssignment = true;
8897       break;
8898     case Sema::CXXDestructor:
8899       break;
8900     case Sema::CXXInvalid:
8901       llvm_unreachable("invalid special member kind");
8902     }
8903 
8904     if (MD->getNumParams()) {
8905       if (const ReferenceType *RT =
8906               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8907         ConstArg = RT->getPointeeType().isConstQualified();
8908     }
8909   }
8910 
8911   Derived &getDerived() { return static_cast<Derived&>(*this); }
8912 
8913   /// Is this a "move" special member?
8914   bool isMove() const {
8915     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8916   }
8917 
8918   /// Look up the corresponding special member in the given class.
8919   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8920                                              unsigned Quals, bool IsMutable) {
8921     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8922                                        ConstArg && !IsMutable);
8923   }
8924 
8925   /// Look up the constructor for the specified base class to see if it's
8926   /// overridden due to this being an inherited constructor.
8927   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8928     if (!ICI)
8929       return {};
8930     assert(CSM == Sema::CXXDefaultConstructor);
8931     auto *BaseCtor =
8932       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8933     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8934       return MD;
8935     return {};
8936   }
8937 
8938   /// A base or member subobject.
8939   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8940 
8941   /// Get the location to use for a subobject in diagnostics.
8942   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8943     // FIXME: For an indirect virtual base, the direct base leading to
8944     // the indirect virtual base would be a more useful choice.
8945     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8946       return B->getBaseTypeLoc();
8947     else
8948       return Subobj.get<FieldDecl*>()->getLocation();
8949   }
8950 
8951   enum BasesToVisit {
8952     /// Visit all non-virtual (direct) bases.
8953     VisitNonVirtualBases,
8954     /// Visit all direct bases, virtual or not.
8955     VisitDirectBases,
8956     /// Visit all non-virtual bases, and all virtual bases if the class
8957     /// is not abstract.
8958     VisitPotentiallyConstructedBases,
8959     /// Visit all direct or virtual bases.
8960     VisitAllBases
8961   };
8962 
8963   // Visit the bases and members of the class.
8964   bool visit(BasesToVisit Bases) {
8965     CXXRecordDecl *RD = MD->getParent();
8966 
8967     if (Bases == VisitPotentiallyConstructedBases)
8968       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8969 
8970     for (auto &B : RD->bases())
8971       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8972           getDerived().visitBase(&B))
8973         return true;
8974 
8975     if (Bases == VisitAllBases)
8976       for (auto &B : RD->vbases())
8977         if (getDerived().visitBase(&B))
8978           return true;
8979 
8980     for (auto *F : RD->fields())
8981       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8982           getDerived().visitField(F))
8983         return true;
8984 
8985     return false;
8986   }
8987 };
8988 }
8989 
8990 namespace {
8991 struct SpecialMemberDeletionInfo
8992     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8993   bool Diagnose;
8994 
8995   SourceLocation Loc;
8996 
8997   bool AllFieldsAreConst;
8998 
8999   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9000                             Sema::CXXSpecialMember CSM,
9001                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9002       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9003         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9004 
9005   bool inUnion() const { return MD->getParent()->isUnion(); }
9006 
9007   Sema::CXXSpecialMember getEffectiveCSM() {
9008     return ICI ? Sema::CXXInvalid : CSM;
9009   }
9010 
9011   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9012 
9013   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9014   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9015 
9016   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9017   bool shouldDeleteForField(FieldDecl *FD);
9018   bool shouldDeleteForAllConstMembers();
9019 
9020   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9021                                      unsigned Quals);
9022   bool shouldDeleteForSubobjectCall(Subobject Subobj,
9023                                     Sema::SpecialMemberOverloadResult SMOR,
9024                                     bool IsDtorCallInCtor);
9025 
9026   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9027 };
9028 }
9029 
9030 /// Is the given special member inaccessible when used on the given
9031 /// sub-object.
9032 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9033                                              CXXMethodDecl *target) {
9034   /// If we're operating on a base class, the object type is the
9035   /// type of this special member.
9036   QualType objectTy;
9037   AccessSpecifier access = target->getAccess();
9038   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9039     objectTy = S.Context.getTypeDeclType(MD->getParent());
9040     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9041 
9042   // If we're operating on a field, the object type is the type of the field.
9043   } else {
9044     objectTy = S.Context.getTypeDeclType(target->getParent());
9045   }
9046 
9047   return S.isMemberAccessibleForDeletion(
9048       target->getParent(), DeclAccessPair::make(target, access), objectTy);
9049 }
9050 
9051 /// Check whether we should delete a special member due to the implicit
9052 /// definition containing a call to a special member of a subobject.
9053 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9054     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9055     bool IsDtorCallInCtor) {
9056   CXXMethodDecl *Decl = SMOR.getMethod();
9057   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9058 
9059   int DiagKind = -1;
9060 
9061   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9062     DiagKind = !Decl ? 0 : 1;
9063   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9064     DiagKind = 2;
9065   else if (!isAccessible(Subobj, Decl))
9066     DiagKind = 3;
9067   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9068            !Decl->isTrivial()) {
9069     // A member of a union must have a trivial corresponding special member.
9070     // As a weird special case, a destructor call from a union's constructor
9071     // must be accessible and non-deleted, but need not be trivial. Such a
9072     // destructor is never actually called, but is semantically checked as
9073     // if it were.
9074     DiagKind = 4;
9075   }
9076 
9077   if (DiagKind == -1)
9078     return false;
9079 
9080   if (Diagnose) {
9081     if (Field) {
9082       S.Diag(Field->getLocation(),
9083              diag::note_deleted_special_member_class_subobject)
9084         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9085         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9086     } else {
9087       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9088       S.Diag(Base->getBeginLoc(),
9089              diag::note_deleted_special_member_class_subobject)
9090           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9091           << Base->getType() << DiagKind << IsDtorCallInCtor
9092           << /*IsObjCPtr*/false;
9093     }
9094 
9095     if (DiagKind == 1)
9096       S.NoteDeletedFunction(Decl);
9097     // FIXME: Explain inaccessibility if DiagKind == 3.
9098   }
9099 
9100   return true;
9101 }
9102 
9103 /// Check whether we should delete a special member function due to having a
9104 /// direct or virtual base class or non-static data member of class type M.
9105 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9106     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9107   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9108   bool IsMutable = Field && Field->isMutable();
9109 
9110   // C++11 [class.ctor]p5:
9111   // -- any direct or virtual base class, or non-static data member with no
9112   //    brace-or-equal-initializer, has class type M (or array thereof) and
9113   //    either M has no default constructor or overload resolution as applied
9114   //    to M's default constructor results in an ambiguity or in a function
9115   //    that is deleted or inaccessible
9116   // C++11 [class.copy]p11, C++11 [class.copy]p23:
9117   // -- a direct or virtual base class B that cannot be copied/moved because
9118   //    overload resolution, as applied to B's corresponding special member,
9119   //    results in an ambiguity or a function that is deleted or inaccessible
9120   //    from the defaulted special member
9121   // C++11 [class.dtor]p5:
9122   // -- any direct or virtual base class [...] has a type with a destructor
9123   //    that is deleted or inaccessible
9124   if (!(CSM == Sema::CXXDefaultConstructor &&
9125         Field && Field->hasInClassInitializer()) &&
9126       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9127                                    false))
9128     return true;
9129 
9130   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9131   // -- any direct or virtual base class or non-static data member has a
9132   //    type with a destructor that is deleted or inaccessible
9133   if (IsConstructor) {
9134     Sema::SpecialMemberOverloadResult SMOR =
9135         S.LookupSpecialMember(Class, Sema::CXXDestructor,
9136                               false, false, false, false, false);
9137     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9138       return true;
9139   }
9140 
9141   return false;
9142 }
9143 
9144 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9145     FieldDecl *FD, QualType FieldType) {
9146   // The defaulted special functions are defined as deleted if this is a variant
9147   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9148   // type under ARC.
9149   if (!FieldType.hasNonTrivialObjCLifetime())
9150     return false;
9151 
9152   // Don't make the defaulted default constructor defined as deleted if the
9153   // member has an in-class initializer.
9154   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9155     return false;
9156 
9157   if (Diagnose) {
9158     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9159     S.Diag(FD->getLocation(),
9160            diag::note_deleted_special_member_class_subobject)
9161         << getEffectiveCSM() << ParentClass << /*IsField*/true
9162         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9163   }
9164 
9165   return true;
9166 }
9167 
9168 /// Check whether we should delete a special member function due to the class
9169 /// having a particular direct or virtual base class.
9170 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9171   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9172   // If program is correct, BaseClass cannot be null, but if it is, the error
9173   // must be reported elsewhere.
9174   if (!BaseClass)
9175     return false;
9176   // If we have an inheriting constructor, check whether we're calling an
9177   // inherited constructor instead of a default constructor.
9178   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9179   if (auto *BaseCtor = SMOR.getMethod()) {
9180     // Note that we do not check access along this path; other than that,
9181     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9182     // FIXME: Check that the base has a usable destructor! Sink this into
9183     // shouldDeleteForClassSubobject.
9184     if (BaseCtor->isDeleted() && Diagnose) {
9185       S.Diag(Base->getBeginLoc(),
9186              diag::note_deleted_special_member_class_subobject)
9187           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9188           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9189           << /*IsObjCPtr*/false;
9190       S.NoteDeletedFunction(BaseCtor);
9191     }
9192     return BaseCtor->isDeleted();
9193   }
9194   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9195 }
9196 
9197 /// Check whether we should delete a special member function due to the class
9198 /// having a particular non-static data member.
9199 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9200   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9201   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9202 
9203   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9204     return true;
9205 
9206   if (CSM == Sema::CXXDefaultConstructor) {
9207     // For a default constructor, all references must be initialized in-class
9208     // and, if a union, it must have a non-const member.
9209     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9210       if (Diagnose)
9211         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9212           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9213       return true;
9214     }
9215     // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9216     // data member of const-qualified type (or array thereof) with no
9217     // brace-or-equal-initializer is not const-default-constructible.
9218     if (!inUnion() && FieldType.isConstQualified() &&
9219         !FD->hasInClassInitializer() &&
9220         (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9221       if (Diagnose)
9222         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9223           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9224       return true;
9225     }
9226 
9227     if (inUnion() && !FieldType.isConstQualified())
9228       AllFieldsAreConst = false;
9229   } else if (CSM == Sema::CXXCopyConstructor) {
9230     // For a copy constructor, data members must not be of rvalue reference
9231     // type.
9232     if (FieldType->isRValueReferenceType()) {
9233       if (Diagnose)
9234         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9235           << MD->getParent() << FD << FieldType;
9236       return true;
9237     }
9238   } else if (IsAssignment) {
9239     // For an assignment operator, data members must not be of reference type.
9240     if (FieldType->isReferenceType()) {
9241       if (Diagnose)
9242         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9243           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9244       return true;
9245     }
9246     if (!FieldRecord && FieldType.isConstQualified()) {
9247       // C++11 [class.copy]p23:
9248       // -- a non-static data member of const non-class type (or array thereof)
9249       if (Diagnose)
9250         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9251           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9252       return true;
9253     }
9254   }
9255 
9256   if (FieldRecord) {
9257     // Some additional restrictions exist on the variant members.
9258     if (!inUnion() && FieldRecord->isUnion() &&
9259         FieldRecord->isAnonymousStructOrUnion()) {
9260       bool AllVariantFieldsAreConst = true;
9261 
9262       // FIXME: Handle anonymous unions declared within anonymous unions.
9263       for (auto *UI : FieldRecord->fields()) {
9264         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9265 
9266         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9267           return true;
9268 
9269         if (!UnionFieldType.isConstQualified())
9270           AllVariantFieldsAreConst = false;
9271 
9272         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9273         if (UnionFieldRecord &&
9274             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9275                                           UnionFieldType.getCVRQualifiers()))
9276           return true;
9277       }
9278 
9279       // At least one member in each anonymous union must be non-const
9280       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9281           !FieldRecord->field_empty()) {
9282         if (Diagnose)
9283           S.Diag(FieldRecord->getLocation(),
9284                  diag::note_deleted_default_ctor_all_const)
9285             << !!ICI << MD->getParent() << /*anonymous union*/1;
9286         return true;
9287       }
9288 
9289       // Don't check the implicit member of the anonymous union type.
9290       // This is technically non-conformant but supported, and we have a
9291       // diagnostic for this elsewhere.
9292       return false;
9293     }
9294 
9295     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9296                                       FieldType.getCVRQualifiers()))
9297       return true;
9298   }
9299 
9300   return false;
9301 }
9302 
9303 /// C++11 [class.ctor] p5:
9304 ///   A defaulted default constructor for a class X is defined as deleted if
9305 /// X is a union and all of its variant members are of const-qualified type.
9306 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9307   // This is a silly definition, because it gives an empty union a deleted
9308   // default constructor. Don't do that.
9309   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9310     bool AnyFields = false;
9311     for (auto *F : MD->getParent()->fields())
9312       if ((AnyFields = !F->isUnnamedBitfield()))
9313         break;
9314     if (!AnyFields)
9315       return false;
9316     if (Diagnose)
9317       S.Diag(MD->getParent()->getLocation(),
9318              diag::note_deleted_default_ctor_all_const)
9319         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9320     return true;
9321   }
9322   return false;
9323 }
9324 
9325 /// Determine whether a defaulted special member function should be defined as
9326 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9327 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9328 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9329                                      InheritedConstructorInfo *ICI,
9330                                      bool Diagnose) {
9331   if (MD->isInvalidDecl())
9332     return false;
9333   CXXRecordDecl *RD = MD->getParent();
9334   assert(!RD->isDependentType() && "do deletion after instantiation");
9335   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9336     return false;
9337 
9338   // C++11 [expr.lambda.prim]p19:
9339   //   The closure type associated with a lambda-expression has a
9340   //   deleted (8.4.3) default constructor and a deleted copy
9341   //   assignment operator.
9342   // C++2a adds back these operators if the lambda has no lambda-capture.
9343   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9344       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9345     if (Diagnose)
9346       Diag(RD->getLocation(), diag::note_lambda_decl);
9347     return true;
9348   }
9349 
9350   // For an anonymous struct or union, the copy and assignment special members
9351   // will never be used, so skip the check. For an anonymous union declared at
9352   // namespace scope, the constructor and destructor are used.
9353   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9354       RD->isAnonymousStructOrUnion())
9355     return false;
9356 
9357   // C++11 [class.copy]p7, p18:
9358   //   If the class definition declares a move constructor or move assignment
9359   //   operator, an implicitly declared copy constructor or copy assignment
9360   //   operator is defined as deleted.
9361   if (MD->isImplicit() &&
9362       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9363     CXXMethodDecl *UserDeclaredMove = nullptr;
9364 
9365     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9366     // deletion of the corresponding copy operation, not both copy operations.
9367     // MSVC 2015 has adopted the standards conforming behavior.
9368     bool DeletesOnlyMatchingCopy =
9369         getLangOpts().MSVCCompat &&
9370         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9371 
9372     if (RD->hasUserDeclaredMoveConstructor() &&
9373         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9374       if (!Diagnose) return true;
9375 
9376       // Find any user-declared move constructor.
9377       for (auto *I : RD->ctors()) {
9378         if (I->isMoveConstructor()) {
9379           UserDeclaredMove = I;
9380           break;
9381         }
9382       }
9383       assert(UserDeclaredMove);
9384     } else if (RD->hasUserDeclaredMoveAssignment() &&
9385                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9386       if (!Diagnose) return true;
9387 
9388       // Find any user-declared move assignment operator.
9389       for (auto *I : RD->methods()) {
9390         if (I->isMoveAssignmentOperator()) {
9391           UserDeclaredMove = I;
9392           break;
9393         }
9394       }
9395       assert(UserDeclaredMove);
9396     }
9397 
9398     if (UserDeclaredMove) {
9399       Diag(UserDeclaredMove->getLocation(),
9400            diag::note_deleted_copy_user_declared_move)
9401         << (CSM == CXXCopyAssignment) << RD
9402         << UserDeclaredMove->isMoveAssignmentOperator();
9403       return true;
9404     }
9405   }
9406 
9407   // Do access control from the special member function
9408   ContextRAII MethodContext(*this, MD);
9409 
9410   // C++11 [class.dtor]p5:
9411   // -- for a virtual destructor, lookup of the non-array deallocation function
9412   //    results in an ambiguity or in a function that is deleted or inaccessible
9413   if (CSM == CXXDestructor && MD->isVirtual()) {
9414     FunctionDecl *OperatorDelete = nullptr;
9415     DeclarationName Name =
9416       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9417     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9418                                  OperatorDelete, /*Diagnose*/false)) {
9419       if (Diagnose)
9420         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9421       return true;
9422     }
9423   }
9424 
9425   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9426 
9427   // Per DR1611, do not consider virtual bases of constructors of abstract
9428   // classes, since we are not going to construct them.
9429   // Per DR1658, do not consider virtual bases of destructors of abstract
9430   // classes either.
9431   // Per DR2180, for assignment operators we only assign (and thus only
9432   // consider) direct bases.
9433   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9434                                  : SMI.VisitPotentiallyConstructedBases))
9435     return true;
9436 
9437   if (SMI.shouldDeleteForAllConstMembers())
9438     return true;
9439 
9440   if (getLangOpts().CUDA) {
9441     // We should delete the special member in CUDA mode if target inference
9442     // failed.
9443     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9444     // is treated as certain special member, which may not reflect what special
9445     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9446     // expects CSM to match MD, therefore recalculate CSM.
9447     assert(ICI || CSM == getSpecialMember(MD));
9448     auto RealCSM = CSM;
9449     if (ICI)
9450       RealCSM = getSpecialMember(MD);
9451 
9452     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9453                                                    SMI.ConstArg, Diagnose);
9454   }
9455 
9456   return false;
9457 }
9458 
9459 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9460   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9461   assert(DFK && "not a defaultable function");
9462   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9463 
9464   if (DFK.isSpecialMember()) {
9465     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9466                               nullptr, /*Diagnose=*/true);
9467   } else {
9468     DefaultedComparisonAnalyzer(
9469         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9470         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9471         .visit();
9472   }
9473 }
9474 
9475 /// Perform lookup for a special member of the specified kind, and determine
9476 /// whether it is trivial. If the triviality can be determined without the
9477 /// lookup, skip it. This is intended for use when determining whether a
9478 /// special member of a containing object is trivial, and thus does not ever
9479 /// perform overload resolution for default constructors.
9480 ///
9481 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9482 /// member that was most likely to be intended to be trivial, if any.
9483 ///
9484 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9485 /// determine whether the special member is trivial.
9486 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9487                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9488                                      bool ConstRHS,
9489                                      Sema::TrivialABIHandling TAH,
9490                                      CXXMethodDecl **Selected) {
9491   if (Selected)
9492     *Selected = nullptr;
9493 
9494   switch (CSM) {
9495   case Sema::CXXInvalid:
9496     llvm_unreachable("not a special member");
9497 
9498   case Sema::CXXDefaultConstructor:
9499     // C++11 [class.ctor]p5:
9500     //   A default constructor is trivial if:
9501     //    - all the [direct subobjects] have trivial default constructors
9502     //
9503     // Note, no overload resolution is performed in this case.
9504     if (RD->hasTrivialDefaultConstructor())
9505       return true;
9506 
9507     if (Selected) {
9508       // If there's a default constructor which could have been trivial, dig it
9509       // out. Otherwise, if there's any user-provided default constructor, point
9510       // to that as an example of why there's not a trivial one.
9511       CXXConstructorDecl *DefCtor = nullptr;
9512       if (RD->needsImplicitDefaultConstructor())
9513         S.DeclareImplicitDefaultConstructor(RD);
9514       for (auto *CI : RD->ctors()) {
9515         if (!CI->isDefaultConstructor())
9516           continue;
9517         DefCtor = CI;
9518         if (!DefCtor->isUserProvided())
9519           break;
9520       }
9521 
9522       *Selected = DefCtor;
9523     }
9524 
9525     return false;
9526 
9527   case Sema::CXXDestructor:
9528     // C++11 [class.dtor]p5:
9529     //   A destructor is trivial if:
9530     //    - all the direct [subobjects] have trivial destructors
9531     if (RD->hasTrivialDestructor() ||
9532         (TAH == Sema::TAH_ConsiderTrivialABI &&
9533          RD->hasTrivialDestructorForCall()))
9534       return true;
9535 
9536     if (Selected) {
9537       if (RD->needsImplicitDestructor())
9538         S.DeclareImplicitDestructor(RD);
9539       *Selected = RD->getDestructor();
9540     }
9541 
9542     return false;
9543 
9544   case Sema::CXXCopyConstructor:
9545     // C++11 [class.copy]p12:
9546     //   A copy constructor is trivial if:
9547     //    - the constructor selected to copy each direct [subobject] is trivial
9548     if (RD->hasTrivialCopyConstructor() ||
9549         (TAH == Sema::TAH_ConsiderTrivialABI &&
9550          RD->hasTrivialCopyConstructorForCall())) {
9551       if (Quals == Qualifiers::Const)
9552         // We must either select the trivial copy constructor or reach an
9553         // ambiguity; no need to actually perform overload resolution.
9554         return true;
9555     } else if (!Selected) {
9556       return false;
9557     }
9558     // In C++98, we are not supposed to perform overload resolution here, but we
9559     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9560     // cases like B as having a non-trivial copy constructor:
9561     //   struct A { template<typename T> A(T&); };
9562     //   struct B { mutable A a; };
9563     goto NeedOverloadResolution;
9564 
9565   case Sema::CXXCopyAssignment:
9566     // C++11 [class.copy]p25:
9567     //   A copy assignment operator is trivial if:
9568     //    - the assignment operator selected to copy each direct [subobject] is
9569     //      trivial
9570     if (RD->hasTrivialCopyAssignment()) {
9571       if (Quals == Qualifiers::Const)
9572         return true;
9573     } else if (!Selected) {
9574       return false;
9575     }
9576     // In C++98, we are not supposed to perform overload resolution here, but we
9577     // treat that as a language defect.
9578     goto NeedOverloadResolution;
9579 
9580   case Sema::CXXMoveConstructor:
9581   case Sema::CXXMoveAssignment:
9582   NeedOverloadResolution:
9583     Sema::SpecialMemberOverloadResult SMOR =
9584         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9585 
9586     // The standard doesn't describe how to behave if the lookup is ambiguous.
9587     // We treat it as not making the member non-trivial, just like the standard
9588     // mandates for the default constructor. This should rarely matter, because
9589     // the member will also be deleted.
9590     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9591       return true;
9592 
9593     if (!SMOR.getMethod()) {
9594       assert(SMOR.getKind() ==
9595              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9596       return false;
9597     }
9598 
9599     // We deliberately don't check if we found a deleted special member. We're
9600     // not supposed to!
9601     if (Selected)
9602       *Selected = SMOR.getMethod();
9603 
9604     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9605         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9606       return SMOR.getMethod()->isTrivialForCall();
9607     return SMOR.getMethod()->isTrivial();
9608   }
9609 
9610   llvm_unreachable("unknown special method kind");
9611 }
9612 
9613 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9614   for (auto *CI : RD->ctors())
9615     if (!CI->isImplicit())
9616       return CI;
9617 
9618   // Look for constructor templates.
9619   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9620   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9621     if (CXXConstructorDecl *CD =
9622           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9623       return CD;
9624   }
9625 
9626   return nullptr;
9627 }
9628 
9629 /// The kind of subobject we are checking for triviality. The values of this
9630 /// enumeration are used in diagnostics.
9631 enum TrivialSubobjectKind {
9632   /// The subobject is a base class.
9633   TSK_BaseClass,
9634   /// The subobject is a non-static data member.
9635   TSK_Field,
9636   /// The object is actually the complete object.
9637   TSK_CompleteObject
9638 };
9639 
9640 /// Check whether the special member selected for a given type would be trivial.
9641 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9642                                       QualType SubType, bool ConstRHS,
9643                                       Sema::CXXSpecialMember CSM,
9644                                       TrivialSubobjectKind Kind,
9645                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9646   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9647   if (!SubRD)
9648     return true;
9649 
9650   CXXMethodDecl *Selected;
9651   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9652                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9653     return true;
9654 
9655   if (Diagnose) {
9656     if (ConstRHS)
9657       SubType.addConst();
9658 
9659     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9660       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9661         << Kind << SubType.getUnqualifiedType();
9662       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9663         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9664     } else if (!Selected)
9665       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9666         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9667     else if (Selected->isUserProvided()) {
9668       if (Kind == TSK_CompleteObject)
9669         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9670           << Kind << SubType.getUnqualifiedType() << CSM;
9671       else {
9672         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9673           << Kind << SubType.getUnqualifiedType() << CSM;
9674         S.Diag(Selected->getLocation(), diag::note_declared_at);
9675       }
9676     } else {
9677       if (Kind != TSK_CompleteObject)
9678         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9679           << Kind << SubType.getUnqualifiedType() << CSM;
9680 
9681       // Explain why the defaulted or deleted special member isn't trivial.
9682       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9683                                Diagnose);
9684     }
9685   }
9686 
9687   return false;
9688 }
9689 
9690 /// Check whether the members of a class type allow a special member to be
9691 /// trivial.
9692 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9693                                      Sema::CXXSpecialMember CSM,
9694                                      bool ConstArg,
9695                                      Sema::TrivialABIHandling TAH,
9696                                      bool Diagnose) {
9697   for (const auto *FI : RD->fields()) {
9698     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9699       continue;
9700 
9701     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9702 
9703     // Pretend anonymous struct or union members are members of this class.
9704     if (FI->isAnonymousStructOrUnion()) {
9705       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9706                                     CSM, ConstArg, TAH, Diagnose))
9707         return false;
9708       continue;
9709     }
9710 
9711     // C++11 [class.ctor]p5:
9712     //   A default constructor is trivial if [...]
9713     //    -- no non-static data member of its class has a
9714     //       brace-or-equal-initializer
9715     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9716       if (Diagnose)
9717         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9718             << FI;
9719       return false;
9720     }
9721 
9722     // Objective C ARC 4.3.5:
9723     //   [...] nontrivally ownership-qualified types are [...] not trivially
9724     //   default constructible, copy constructible, move constructible, copy
9725     //   assignable, move assignable, or destructible [...]
9726     if (FieldType.hasNonTrivialObjCLifetime()) {
9727       if (Diagnose)
9728         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9729           << RD << FieldType.getObjCLifetime();
9730       return false;
9731     }
9732 
9733     bool ConstRHS = ConstArg && !FI->isMutable();
9734     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9735                                    CSM, TSK_Field, TAH, Diagnose))
9736       return false;
9737   }
9738 
9739   return true;
9740 }
9741 
9742 /// Diagnose why the specified class does not have a trivial special member of
9743 /// the given kind.
9744 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9745   QualType Ty = Context.getRecordType(RD);
9746 
9747   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9748   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9749                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9750                             /*Diagnose*/true);
9751 }
9752 
9753 /// Determine whether a defaulted or deleted special member function is trivial,
9754 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9755 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9756 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9757                                   TrivialABIHandling TAH, bool Diagnose) {
9758   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9759 
9760   CXXRecordDecl *RD = MD->getParent();
9761 
9762   bool ConstArg = false;
9763 
9764   // C++11 [class.copy]p12, p25: [DR1593]
9765   //   A [special member] is trivial if [...] its parameter-type-list is
9766   //   equivalent to the parameter-type-list of an implicit declaration [...]
9767   switch (CSM) {
9768   case CXXDefaultConstructor:
9769   case CXXDestructor:
9770     // Trivial default constructors and destructors cannot have parameters.
9771     break;
9772 
9773   case CXXCopyConstructor:
9774   case CXXCopyAssignment: {
9775     // Trivial copy operations always have const, non-volatile parameter types.
9776     ConstArg = true;
9777     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9778     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9779     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9780       if (Diagnose)
9781         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9782           << Param0->getSourceRange() << Param0->getType()
9783           << Context.getLValueReferenceType(
9784                Context.getRecordType(RD).withConst());
9785       return false;
9786     }
9787     break;
9788   }
9789 
9790   case CXXMoveConstructor:
9791   case CXXMoveAssignment: {
9792     // Trivial move operations always have non-cv-qualified parameters.
9793     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9794     const RValueReferenceType *RT =
9795       Param0->getType()->getAs<RValueReferenceType>();
9796     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9797       if (Diagnose)
9798         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9799           << Param0->getSourceRange() << Param0->getType()
9800           << Context.getRValueReferenceType(Context.getRecordType(RD));
9801       return false;
9802     }
9803     break;
9804   }
9805 
9806   case CXXInvalid:
9807     llvm_unreachable("not a special member");
9808   }
9809 
9810   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9811     if (Diagnose)
9812       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9813            diag::note_nontrivial_default_arg)
9814         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9815     return false;
9816   }
9817   if (MD->isVariadic()) {
9818     if (Diagnose)
9819       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9820     return false;
9821   }
9822 
9823   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9824   //   A copy/move [constructor or assignment operator] is trivial if
9825   //    -- the [member] selected to copy/move each direct base class subobject
9826   //       is trivial
9827   //
9828   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9829   //   A [default constructor or destructor] is trivial if
9830   //    -- all the direct base classes have trivial [default constructors or
9831   //       destructors]
9832   for (const auto &BI : RD->bases())
9833     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9834                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9835       return false;
9836 
9837   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9838   //   A copy/move [constructor or assignment operator] for a class X is
9839   //   trivial if
9840   //    -- for each non-static data member of X that is of class type (or array
9841   //       thereof), the constructor selected to copy/move that member is
9842   //       trivial
9843   //
9844   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9845   //   A [default constructor or destructor] is trivial if
9846   //    -- for all of the non-static data members of its class that are of class
9847   //       type (or array thereof), each such class has a trivial [default
9848   //       constructor or destructor]
9849   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9850     return false;
9851 
9852   // C++11 [class.dtor]p5:
9853   //   A destructor is trivial if [...]
9854   //    -- the destructor is not virtual
9855   if (CSM == CXXDestructor && MD->isVirtual()) {
9856     if (Diagnose)
9857       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9858     return false;
9859   }
9860 
9861   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9862   //   A [special member] for class X is trivial if [...]
9863   //    -- class X has no virtual functions and no virtual base classes
9864   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9865     if (!Diagnose)
9866       return false;
9867 
9868     if (RD->getNumVBases()) {
9869       // Check for virtual bases. We already know that the corresponding
9870       // member in all bases is trivial, so vbases must all be direct.
9871       CXXBaseSpecifier &BS = *RD->vbases_begin();
9872       assert(BS.isVirtual());
9873       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9874       return false;
9875     }
9876 
9877     // Must have a virtual method.
9878     for (const auto *MI : RD->methods()) {
9879       if (MI->isVirtual()) {
9880         SourceLocation MLoc = MI->getBeginLoc();
9881         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9882         return false;
9883       }
9884     }
9885 
9886     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9887   }
9888 
9889   // Looks like it's trivial!
9890   return true;
9891 }
9892 
9893 namespace {
9894 struct FindHiddenVirtualMethod {
9895   Sema *S;
9896   CXXMethodDecl *Method;
9897   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9898   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9899 
9900 private:
9901   /// Check whether any most overridden method from MD in Methods
9902   static bool CheckMostOverridenMethods(
9903       const CXXMethodDecl *MD,
9904       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9905     if (MD->size_overridden_methods() == 0)
9906       return Methods.count(MD->getCanonicalDecl());
9907     for (const CXXMethodDecl *O : MD->overridden_methods())
9908       if (CheckMostOverridenMethods(O, Methods))
9909         return true;
9910     return false;
9911   }
9912 
9913 public:
9914   /// Member lookup function that determines whether a given C++
9915   /// method overloads virtual methods in a base class without overriding any,
9916   /// to be used with CXXRecordDecl::lookupInBases().
9917   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9918     RecordDecl *BaseRecord =
9919         Specifier->getType()->castAs<RecordType>()->getDecl();
9920 
9921     DeclarationName Name = Method->getDeclName();
9922     assert(Name.getNameKind() == DeclarationName::Identifier);
9923 
9924     bool foundSameNameMethod = false;
9925     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9926     for (Path.Decls = BaseRecord->lookup(Name).begin();
9927          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9928       NamedDecl *D = *Path.Decls;
9929       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9930         MD = MD->getCanonicalDecl();
9931         foundSameNameMethod = true;
9932         // Interested only in hidden virtual methods.
9933         if (!MD->isVirtual())
9934           continue;
9935         // If the method we are checking overrides a method from its base
9936         // don't warn about the other overloaded methods. Clang deviates from
9937         // GCC by only diagnosing overloads of inherited virtual functions that
9938         // do not override any other virtual functions in the base. GCC's
9939         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9940         // function from a base class. These cases may be better served by a
9941         // warning (not specific to virtual functions) on call sites when the
9942         // call would select a different function from the base class, were it
9943         // visible.
9944         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9945         if (!S->IsOverload(Method, MD, false))
9946           return true;
9947         // Collect the overload only if its hidden.
9948         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9949           overloadedMethods.push_back(MD);
9950       }
9951     }
9952 
9953     if (foundSameNameMethod)
9954       OverloadedMethods.append(overloadedMethods.begin(),
9955                                overloadedMethods.end());
9956     return foundSameNameMethod;
9957   }
9958 };
9959 } // end anonymous namespace
9960 
9961 /// Add the most overridden methods from MD to Methods
9962 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9963                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9964   if (MD->size_overridden_methods() == 0)
9965     Methods.insert(MD->getCanonicalDecl());
9966   else
9967     for (const CXXMethodDecl *O : MD->overridden_methods())
9968       AddMostOverridenMethods(O, Methods);
9969 }
9970 
9971 /// Check if a method overloads virtual methods in a base class without
9972 /// overriding any.
9973 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9974                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9975   if (!MD->getDeclName().isIdentifier())
9976     return;
9977 
9978   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9979                      /*bool RecordPaths=*/false,
9980                      /*bool DetectVirtual=*/false);
9981   FindHiddenVirtualMethod FHVM;
9982   FHVM.Method = MD;
9983   FHVM.S = this;
9984 
9985   // Keep the base methods that were overridden or introduced in the subclass
9986   // by 'using' in a set. A base method not in this set is hidden.
9987   CXXRecordDecl *DC = MD->getParent();
9988   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9989   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9990     NamedDecl *ND = *I;
9991     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9992       ND = shad->getTargetDecl();
9993     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9994       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9995   }
9996 
9997   if (DC->lookupInBases(FHVM, Paths))
9998     OverloadedMethods = FHVM.OverloadedMethods;
9999 }
10000 
10001 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10002                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10003   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10004     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10005     PartialDiagnostic PD = PDiag(
10006          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10007     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10008     Diag(overloadedMD->getLocation(), PD);
10009   }
10010 }
10011 
10012 /// Diagnose methods which overload virtual methods in a base class
10013 /// without overriding any.
10014 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10015   if (MD->isInvalidDecl())
10016     return;
10017 
10018   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10019     return;
10020 
10021   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10022   FindHiddenVirtualMethods(MD, OverloadedMethods);
10023   if (!OverloadedMethods.empty()) {
10024     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10025       << MD << (OverloadedMethods.size() > 1);
10026 
10027     NoteHiddenVirtualMethods(MD, OverloadedMethods);
10028   }
10029 }
10030 
10031 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10032   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10033     // No diagnostics if this is a template instantiation.
10034     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10035       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10036            diag::ext_cannot_use_trivial_abi) << &RD;
10037       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10038            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10039     }
10040     RD.dropAttr<TrivialABIAttr>();
10041   };
10042 
10043   // Ill-formed if the copy and move constructors are deleted.
10044   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10045     // If the type is dependent, then assume it might have
10046     // implicit copy or move ctor because we won't know yet at this point.
10047     if (RD.isDependentType())
10048       return true;
10049     if (RD.needsImplicitCopyConstructor() &&
10050         !RD.defaultedCopyConstructorIsDeleted())
10051       return true;
10052     if (RD.needsImplicitMoveConstructor() &&
10053         !RD.defaultedMoveConstructorIsDeleted())
10054       return true;
10055     for (const CXXConstructorDecl *CD : RD.ctors())
10056       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10057         return true;
10058     return false;
10059   };
10060 
10061   if (!HasNonDeletedCopyOrMoveConstructor()) {
10062     PrintDiagAndRemoveAttr(0);
10063     return;
10064   }
10065 
10066   // Ill-formed if the struct has virtual functions.
10067   if (RD.isPolymorphic()) {
10068     PrintDiagAndRemoveAttr(1);
10069     return;
10070   }
10071 
10072   for (const auto &B : RD.bases()) {
10073     // Ill-formed if the base class is non-trivial for the purpose of calls or a
10074     // virtual base.
10075     if (!B.getType()->isDependentType() &&
10076         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10077       PrintDiagAndRemoveAttr(2);
10078       return;
10079     }
10080 
10081     if (B.isVirtual()) {
10082       PrintDiagAndRemoveAttr(3);
10083       return;
10084     }
10085   }
10086 
10087   for (const auto *FD : RD.fields()) {
10088     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10089     // non-trivial for the purpose of calls.
10090     QualType FT = FD->getType();
10091     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10092       PrintDiagAndRemoveAttr(4);
10093       return;
10094     }
10095 
10096     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10097       if (!RT->isDependentType() &&
10098           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10099         PrintDiagAndRemoveAttr(5);
10100         return;
10101       }
10102   }
10103 }
10104 
10105 void Sema::ActOnFinishCXXMemberSpecification(
10106     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10107     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10108   if (!TagDecl)
10109     return;
10110 
10111   AdjustDeclIfTemplate(TagDecl);
10112 
10113   for (const ParsedAttr &AL : AttrList) {
10114     if (AL.getKind() != ParsedAttr::AT_Visibility)
10115       continue;
10116     AL.setInvalid();
10117     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10118   }
10119 
10120   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
10121               // strict aliasing violation!
10122               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
10123               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
10124 
10125   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10126 }
10127 
10128 /// Find the equality comparison functions that should be implicitly declared
10129 /// in a given class definition, per C++2a [class.compare.default]p3.
10130 static void findImplicitlyDeclaredEqualityComparisons(
10131     ASTContext &Ctx, CXXRecordDecl *RD,
10132     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10133   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10134   if (!RD->lookup(EqEq).empty())
10135     // Member operator== explicitly declared: no implicit operator==s.
10136     return;
10137 
10138   // Traverse friends looking for an '==' or a '<=>'.
10139   for (FriendDecl *Friend : RD->friends()) {
10140     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10141     if (!FD) continue;
10142 
10143     if (FD->getOverloadedOperator() == OO_EqualEqual) {
10144       // Friend operator== explicitly declared: no implicit operator==s.
10145       Spaceships.clear();
10146       return;
10147     }
10148 
10149     if (FD->getOverloadedOperator() == OO_Spaceship &&
10150         FD->isExplicitlyDefaulted())
10151       Spaceships.push_back(FD);
10152   }
10153 
10154   // Look for members named 'operator<=>'.
10155   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10156   for (NamedDecl *ND : RD->lookup(Cmp)) {
10157     // Note that we could find a non-function here (either a function template
10158     // or a using-declaration). Neither case results in an implicit
10159     // 'operator=='.
10160     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10161       if (FD->isExplicitlyDefaulted())
10162         Spaceships.push_back(FD);
10163   }
10164 }
10165 
10166 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10167 /// special functions, such as the default constructor, copy
10168 /// constructor, or destructor, to the given C++ class (C++
10169 /// [special]p1).  This routine can only be executed just before the
10170 /// definition of the class is complete.
10171 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10172   // Don't add implicit special members to templated classes.
10173   // FIXME: This means unqualified lookups for 'operator=' within a class
10174   // template don't work properly.
10175   if (!ClassDecl->isDependentType()) {
10176     if (ClassDecl->needsImplicitDefaultConstructor()) {
10177       ++getASTContext().NumImplicitDefaultConstructors;
10178 
10179       if (ClassDecl->hasInheritedConstructor())
10180         DeclareImplicitDefaultConstructor(ClassDecl);
10181     }
10182 
10183     if (ClassDecl->needsImplicitCopyConstructor()) {
10184       ++getASTContext().NumImplicitCopyConstructors;
10185 
10186       // If the properties or semantics of the copy constructor couldn't be
10187       // determined while the class was being declared, force a declaration
10188       // of it now.
10189       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10190           ClassDecl->hasInheritedConstructor())
10191         DeclareImplicitCopyConstructor(ClassDecl);
10192       // For the MS ABI we need to know whether the copy ctor is deleted. A
10193       // prerequisite for deleting the implicit copy ctor is that the class has
10194       // a move ctor or move assignment that is either user-declared or whose
10195       // semantics are inherited from a subobject. FIXME: We should provide a
10196       // more direct way for CodeGen to ask whether the constructor was deleted.
10197       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10198                (ClassDecl->hasUserDeclaredMoveConstructor() ||
10199                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10200                 ClassDecl->hasUserDeclaredMoveAssignment() ||
10201                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10202         DeclareImplicitCopyConstructor(ClassDecl);
10203     }
10204 
10205     if (getLangOpts().CPlusPlus11 &&
10206         ClassDecl->needsImplicitMoveConstructor()) {
10207       ++getASTContext().NumImplicitMoveConstructors;
10208 
10209       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10210           ClassDecl->hasInheritedConstructor())
10211         DeclareImplicitMoveConstructor(ClassDecl);
10212     }
10213 
10214     if (ClassDecl->needsImplicitCopyAssignment()) {
10215       ++getASTContext().NumImplicitCopyAssignmentOperators;
10216 
10217       // If we have a dynamic class, then the copy assignment operator may be
10218       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10219       // it shows up in the right place in the vtable and that we diagnose
10220       // problems with the implicit exception specification.
10221       if (ClassDecl->isDynamicClass() ||
10222           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10223           ClassDecl->hasInheritedAssignment())
10224         DeclareImplicitCopyAssignment(ClassDecl);
10225     }
10226 
10227     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10228       ++getASTContext().NumImplicitMoveAssignmentOperators;
10229 
10230       // Likewise for the move assignment operator.
10231       if (ClassDecl->isDynamicClass() ||
10232           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10233           ClassDecl->hasInheritedAssignment())
10234         DeclareImplicitMoveAssignment(ClassDecl);
10235     }
10236 
10237     if (ClassDecl->needsImplicitDestructor()) {
10238       ++getASTContext().NumImplicitDestructors;
10239 
10240       // If we have a dynamic class, then the destructor may be virtual, so we
10241       // have to declare the destructor immediately. This ensures that, e.g., it
10242       // shows up in the right place in the vtable and that we diagnose problems
10243       // with the implicit exception specification.
10244       if (ClassDecl->isDynamicClass() ||
10245           ClassDecl->needsOverloadResolutionForDestructor())
10246         DeclareImplicitDestructor(ClassDecl);
10247     }
10248   }
10249 
10250   // C++2a [class.compare.default]p3:
10251   //   If the member-specification does not explicitly declare any member or
10252   //   friend named operator==, an == operator function is declared implicitly
10253   //   for each defaulted three-way comparison operator function defined in
10254   //   the member-specification
10255   // FIXME: Consider doing this lazily.
10256   // We do this during the initial parse for a class template, not during
10257   // instantiation, so that we can handle unqualified lookups for 'operator=='
10258   // when parsing the template.
10259   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10260     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10261     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10262                                               DefaultedSpaceships);
10263     for (auto *FD : DefaultedSpaceships)
10264       DeclareImplicitEqualityComparison(ClassDecl, FD);
10265   }
10266 }
10267 
10268 unsigned
10269 Sema::ActOnReenterTemplateScope(Decl *D,
10270                                 llvm::function_ref<Scope *()> EnterScope) {
10271   if (!D)
10272     return 0;
10273   AdjustDeclIfTemplate(D);
10274 
10275   // In order to get name lookup right, reenter template scopes in order from
10276   // outermost to innermost.
10277   SmallVector<TemplateParameterList *, 4> ParameterLists;
10278   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10279 
10280   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10281     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10282       ParameterLists.push_back(DD->getTemplateParameterList(i));
10283 
10284     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10285       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10286         ParameterLists.push_back(FTD->getTemplateParameters());
10287     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10288       LookupDC = VD->getDeclContext();
10289 
10290       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10291         ParameterLists.push_back(VTD->getTemplateParameters());
10292       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10293         ParameterLists.push_back(PSD->getTemplateParameters());
10294     }
10295   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10296     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10297       ParameterLists.push_back(TD->getTemplateParameterList(i));
10298 
10299     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10300       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10301         ParameterLists.push_back(CTD->getTemplateParameters());
10302       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10303         ParameterLists.push_back(PSD->getTemplateParameters());
10304     }
10305   }
10306   // FIXME: Alias declarations and concepts.
10307 
10308   unsigned Count = 0;
10309   Scope *InnermostTemplateScope = nullptr;
10310   for (TemplateParameterList *Params : ParameterLists) {
10311     // Ignore explicit specializations; they don't contribute to the template
10312     // depth.
10313     if (Params->size() == 0)
10314       continue;
10315 
10316     InnermostTemplateScope = EnterScope();
10317     for (NamedDecl *Param : *Params) {
10318       if (Param->getDeclName()) {
10319         InnermostTemplateScope->AddDecl(Param);
10320         IdResolver.AddDecl(Param);
10321       }
10322     }
10323     ++Count;
10324   }
10325 
10326   // Associate the new template scopes with the corresponding entities.
10327   if (InnermostTemplateScope) {
10328     assert(LookupDC && "no enclosing DeclContext for template lookup");
10329     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10330   }
10331 
10332   return Count;
10333 }
10334 
10335 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10336   if (!RecordD) return;
10337   AdjustDeclIfTemplate(RecordD);
10338   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10339   PushDeclContext(S, Record);
10340 }
10341 
10342 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10343   if (!RecordD) return;
10344   PopDeclContext();
10345 }
10346 
10347 /// This is used to implement the constant expression evaluation part of the
10348 /// attribute enable_if extension. There is nothing in standard C++ which would
10349 /// require reentering parameters.
10350 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10351   if (!Param)
10352     return;
10353 
10354   S->AddDecl(Param);
10355   if (Param->getDeclName())
10356     IdResolver.AddDecl(Param);
10357 }
10358 
10359 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10360 /// parsing a top-level (non-nested) C++ class, and we are now
10361 /// parsing those parts of the given Method declaration that could
10362 /// not be parsed earlier (C++ [class.mem]p2), such as default
10363 /// arguments. This action should enter the scope of the given
10364 /// Method declaration as if we had just parsed the qualified method
10365 /// name. However, it should not bring the parameters into scope;
10366 /// that will be performed by ActOnDelayedCXXMethodParameter.
10367 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10368 }
10369 
10370 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10371 /// C++ method declaration. We're (re-)introducing the given
10372 /// function parameter into scope for use in parsing later parts of
10373 /// the method declaration. For example, we could see an
10374 /// ActOnParamDefaultArgument event for this parameter.
10375 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10376   if (!ParamD)
10377     return;
10378 
10379   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10380 
10381   S->AddDecl(Param);
10382   if (Param->getDeclName())
10383     IdResolver.AddDecl(Param);
10384 }
10385 
10386 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10387 /// processing the delayed method declaration for Method. The method
10388 /// declaration is now considered finished. There may be a separate
10389 /// ActOnStartOfFunctionDef action later (not necessarily
10390 /// immediately!) for this method, if it was also defined inside the
10391 /// class body.
10392 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10393   if (!MethodD)
10394     return;
10395 
10396   AdjustDeclIfTemplate(MethodD);
10397 
10398   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10399 
10400   // Now that we have our default arguments, check the constructor
10401   // again. It could produce additional diagnostics or affect whether
10402   // the class has implicitly-declared destructors, among other
10403   // things.
10404   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10405     CheckConstructor(Constructor);
10406 
10407   // Check the default arguments, which we may have added.
10408   if (!Method->isInvalidDecl())
10409     CheckCXXDefaultArguments(Method);
10410 }
10411 
10412 // Emit the given diagnostic for each non-address-space qualifier.
10413 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10414 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10415   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10416   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10417     bool DiagOccured = false;
10418     FTI.MethodQualifiers->forEachQualifier(
10419         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10420                                    SourceLocation SL) {
10421           // This diagnostic should be emitted on any qualifier except an addr
10422           // space qualifier. However, forEachQualifier currently doesn't visit
10423           // addr space qualifiers, so there's no way to write this condition
10424           // right now; we just diagnose on everything.
10425           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10426           DiagOccured = true;
10427         });
10428     if (DiagOccured)
10429       D.setInvalidType();
10430   }
10431 }
10432 
10433 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10434 /// the well-formedness of the constructor declarator @p D with type @p
10435 /// R. If there are any errors in the declarator, this routine will
10436 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10437 /// will be updated to reflect a well-formed type for the constructor and
10438 /// returned.
10439 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10440                                           StorageClass &SC) {
10441   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10442 
10443   // C++ [class.ctor]p3:
10444   //   A constructor shall not be virtual (10.3) or static (9.4). A
10445   //   constructor can be invoked for a const, volatile or const
10446   //   volatile object. A constructor shall not be declared const,
10447   //   volatile, or const volatile (9.3.2).
10448   if (isVirtual) {
10449     if (!D.isInvalidType())
10450       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10451         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10452         << SourceRange(D.getIdentifierLoc());
10453     D.setInvalidType();
10454   }
10455   if (SC == SC_Static) {
10456     if (!D.isInvalidType())
10457       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10458         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10459         << SourceRange(D.getIdentifierLoc());
10460     D.setInvalidType();
10461     SC = SC_None;
10462   }
10463 
10464   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10465     diagnoseIgnoredQualifiers(
10466         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10467         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10468         D.getDeclSpec().getRestrictSpecLoc(),
10469         D.getDeclSpec().getAtomicSpecLoc());
10470     D.setInvalidType();
10471   }
10472 
10473   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10474 
10475   // C++0x [class.ctor]p4:
10476   //   A constructor shall not be declared with a ref-qualifier.
10477   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10478   if (FTI.hasRefQualifier()) {
10479     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10480       << FTI.RefQualifierIsLValueRef
10481       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10482     D.setInvalidType();
10483   }
10484 
10485   // Rebuild the function type "R" without any type qualifiers (in
10486   // case any of the errors above fired) and with "void" as the
10487   // return type, since constructors don't have return types.
10488   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10489   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10490     return R;
10491 
10492   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10493   EPI.TypeQuals = Qualifiers();
10494   EPI.RefQualifier = RQ_None;
10495 
10496   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10497 }
10498 
10499 /// CheckConstructor - Checks a fully-formed constructor for
10500 /// well-formedness, issuing any diagnostics required. Returns true if
10501 /// the constructor declarator is invalid.
10502 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10503   CXXRecordDecl *ClassDecl
10504     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10505   if (!ClassDecl)
10506     return Constructor->setInvalidDecl();
10507 
10508   // C++ [class.copy]p3:
10509   //   A declaration of a constructor for a class X is ill-formed if
10510   //   its first parameter is of type (optionally cv-qualified) X and
10511   //   either there are no other parameters or else all other
10512   //   parameters have default arguments.
10513   if (!Constructor->isInvalidDecl() &&
10514       Constructor->hasOneParamOrDefaultArgs() &&
10515       Constructor->getTemplateSpecializationKind() !=
10516           TSK_ImplicitInstantiation) {
10517     QualType ParamType = Constructor->getParamDecl(0)->getType();
10518     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10519     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10520       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10521       const char *ConstRef
10522         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10523                                                         : " const &";
10524       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10525         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10526 
10527       // FIXME: Rather that making the constructor invalid, we should endeavor
10528       // to fix the type.
10529       Constructor->setInvalidDecl();
10530     }
10531   }
10532 }
10533 
10534 /// CheckDestructor - Checks a fully-formed destructor definition for
10535 /// well-formedness, issuing any diagnostics required.  Returns true
10536 /// on error.
10537 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10538   CXXRecordDecl *RD = Destructor->getParent();
10539 
10540   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10541     SourceLocation Loc;
10542 
10543     if (!Destructor->isImplicit())
10544       Loc = Destructor->getLocation();
10545     else
10546       Loc = RD->getLocation();
10547 
10548     // If we have a virtual destructor, look up the deallocation function
10549     if (FunctionDecl *OperatorDelete =
10550             FindDeallocationFunctionForDestructor(Loc, RD)) {
10551       Expr *ThisArg = nullptr;
10552 
10553       // If the notional 'delete this' expression requires a non-trivial
10554       // conversion from 'this' to the type of a destroying operator delete's
10555       // first parameter, perform that conversion now.
10556       if (OperatorDelete->isDestroyingOperatorDelete()) {
10557         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10558         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10559           // C++ [class.dtor]p13:
10560           //   ... as if for the expression 'delete this' appearing in a
10561           //   non-virtual destructor of the destructor's class.
10562           ContextRAII SwitchContext(*this, Destructor);
10563           ExprResult This =
10564               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10565           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10566           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10567           if (This.isInvalid()) {
10568             // FIXME: Register this as a context note so that it comes out
10569             // in the right order.
10570             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10571             return true;
10572           }
10573           ThisArg = This.get();
10574         }
10575       }
10576 
10577       DiagnoseUseOfDecl(OperatorDelete, Loc);
10578       MarkFunctionReferenced(Loc, OperatorDelete);
10579       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10580     }
10581   }
10582 
10583   return false;
10584 }
10585 
10586 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10587 /// the well-formednes of the destructor declarator @p D with type @p
10588 /// R. If there are any errors in the declarator, this routine will
10589 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10590 /// will be updated to reflect a well-formed type for the destructor and
10591 /// returned.
10592 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10593                                          StorageClass& SC) {
10594   // C++ [class.dtor]p1:
10595   //   [...] A typedef-name that names a class is a class-name
10596   //   (7.1.3); however, a typedef-name that names a class shall not
10597   //   be used as the identifier in the declarator for a destructor
10598   //   declaration.
10599   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10600   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10601     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10602       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10603   else if (const TemplateSpecializationType *TST =
10604              DeclaratorType->getAs<TemplateSpecializationType>())
10605     if (TST->isTypeAlias())
10606       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10607         << DeclaratorType << 1;
10608 
10609   // C++ [class.dtor]p2:
10610   //   A destructor is used to destroy objects of its class type. A
10611   //   destructor takes no parameters, and no return type can be
10612   //   specified for it (not even void). The address of a destructor
10613   //   shall not be taken. A destructor shall not be static. A
10614   //   destructor can be invoked for a const, volatile or const
10615   //   volatile object. A destructor shall not be declared const,
10616   //   volatile or const volatile (9.3.2).
10617   if (SC == SC_Static) {
10618     if (!D.isInvalidType())
10619       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10620         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10621         << SourceRange(D.getIdentifierLoc())
10622         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10623 
10624     SC = SC_None;
10625   }
10626   if (!D.isInvalidType()) {
10627     // Destructors don't have return types, but the parser will
10628     // happily parse something like:
10629     //
10630     //   class X {
10631     //     float ~X();
10632     //   };
10633     //
10634     // The return type will be eliminated later.
10635     if (D.getDeclSpec().hasTypeSpecifier())
10636       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10637         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10638         << SourceRange(D.getIdentifierLoc());
10639     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10640       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10641                                 SourceLocation(),
10642                                 D.getDeclSpec().getConstSpecLoc(),
10643                                 D.getDeclSpec().getVolatileSpecLoc(),
10644                                 D.getDeclSpec().getRestrictSpecLoc(),
10645                                 D.getDeclSpec().getAtomicSpecLoc());
10646       D.setInvalidType();
10647     }
10648   }
10649 
10650   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10651 
10652   // C++0x [class.dtor]p2:
10653   //   A destructor shall not be declared with a ref-qualifier.
10654   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10655   if (FTI.hasRefQualifier()) {
10656     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10657       << FTI.RefQualifierIsLValueRef
10658       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10659     D.setInvalidType();
10660   }
10661 
10662   // Make sure we don't have any parameters.
10663   if (FTIHasNonVoidParameters(FTI)) {
10664     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10665 
10666     // Delete the parameters.
10667     FTI.freeParams();
10668     D.setInvalidType();
10669   }
10670 
10671   // Make sure the destructor isn't variadic.
10672   if (FTI.isVariadic) {
10673     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10674     D.setInvalidType();
10675   }
10676 
10677   // Rebuild the function type "R" without any type qualifiers or
10678   // parameters (in case any of the errors above fired) and with
10679   // "void" as the return type, since destructors don't have return
10680   // types.
10681   if (!D.isInvalidType())
10682     return R;
10683 
10684   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10685   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10686   EPI.Variadic = false;
10687   EPI.TypeQuals = Qualifiers();
10688   EPI.RefQualifier = RQ_None;
10689   return Context.getFunctionType(Context.VoidTy, None, EPI);
10690 }
10691 
10692 static void extendLeft(SourceRange &R, SourceRange Before) {
10693   if (Before.isInvalid())
10694     return;
10695   R.setBegin(Before.getBegin());
10696   if (R.getEnd().isInvalid())
10697     R.setEnd(Before.getEnd());
10698 }
10699 
10700 static void extendRight(SourceRange &R, SourceRange After) {
10701   if (After.isInvalid())
10702     return;
10703   if (R.getBegin().isInvalid())
10704     R.setBegin(After.getBegin());
10705   R.setEnd(After.getEnd());
10706 }
10707 
10708 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10709 /// well-formednes of the conversion function declarator @p D with
10710 /// type @p R. If there are any errors in the declarator, this routine
10711 /// will emit diagnostics and return true. Otherwise, it will return
10712 /// false. Either way, the type @p R will be updated to reflect a
10713 /// well-formed type for the conversion operator.
10714 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10715                                      StorageClass& SC) {
10716   // C++ [class.conv.fct]p1:
10717   //   Neither parameter types nor return type can be specified. The
10718   //   type of a conversion function (8.3.5) is "function taking no
10719   //   parameter returning conversion-type-id."
10720   if (SC == SC_Static) {
10721     if (!D.isInvalidType())
10722       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10723         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10724         << D.getName().getSourceRange();
10725     D.setInvalidType();
10726     SC = SC_None;
10727   }
10728 
10729   TypeSourceInfo *ConvTSI = nullptr;
10730   QualType ConvType =
10731       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10732 
10733   const DeclSpec &DS = D.getDeclSpec();
10734   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10735     // Conversion functions don't have return types, but the parser will
10736     // happily parse something like:
10737     //
10738     //   class X {
10739     //     float operator bool();
10740     //   };
10741     //
10742     // The return type will be changed later anyway.
10743     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10744       << SourceRange(DS.getTypeSpecTypeLoc())
10745       << SourceRange(D.getIdentifierLoc());
10746     D.setInvalidType();
10747   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10748     // It's also plausible that the user writes type qualifiers in the wrong
10749     // place, such as:
10750     //   struct S { const operator int(); };
10751     // FIXME: we could provide a fixit to move the qualifiers onto the
10752     // conversion type.
10753     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10754         << SourceRange(D.getIdentifierLoc()) << 0;
10755     D.setInvalidType();
10756   }
10757 
10758   const auto *Proto = R->castAs<FunctionProtoType>();
10759 
10760   // Make sure we don't have any parameters.
10761   if (Proto->getNumParams() > 0) {
10762     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10763 
10764     // Delete the parameters.
10765     D.getFunctionTypeInfo().freeParams();
10766     D.setInvalidType();
10767   } else if (Proto->isVariadic()) {
10768     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10769     D.setInvalidType();
10770   }
10771 
10772   // Diagnose "&operator bool()" and other such nonsense.  This
10773   // is actually a gcc extension which we don't support.
10774   if (Proto->getReturnType() != ConvType) {
10775     bool NeedsTypedef = false;
10776     SourceRange Before, After;
10777 
10778     // Walk the chunks and extract information on them for our diagnostic.
10779     bool PastFunctionChunk = false;
10780     for (auto &Chunk : D.type_objects()) {
10781       switch (Chunk.Kind) {
10782       case DeclaratorChunk::Function:
10783         if (!PastFunctionChunk) {
10784           if (Chunk.Fun.HasTrailingReturnType) {
10785             TypeSourceInfo *TRT = nullptr;
10786             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10787             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10788           }
10789           PastFunctionChunk = true;
10790           break;
10791         }
10792         LLVM_FALLTHROUGH;
10793       case DeclaratorChunk::Array:
10794         NeedsTypedef = true;
10795         extendRight(After, Chunk.getSourceRange());
10796         break;
10797 
10798       case DeclaratorChunk::Pointer:
10799       case DeclaratorChunk::BlockPointer:
10800       case DeclaratorChunk::Reference:
10801       case DeclaratorChunk::MemberPointer:
10802       case DeclaratorChunk::Pipe:
10803         extendLeft(Before, Chunk.getSourceRange());
10804         break;
10805 
10806       case DeclaratorChunk::Paren:
10807         extendLeft(Before, Chunk.Loc);
10808         extendRight(After, Chunk.EndLoc);
10809         break;
10810       }
10811     }
10812 
10813     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10814                          After.isValid()  ? After.getBegin() :
10815                                             D.getIdentifierLoc();
10816     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10817     DB << Before << After;
10818 
10819     if (!NeedsTypedef) {
10820       DB << /*don't need a typedef*/0;
10821 
10822       // If we can provide a correct fix-it hint, do so.
10823       if (After.isInvalid() && ConvTSI) {
10824         SourceLocation InsertLoc =
10825             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10826         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10827            << FixItHint::CreateInsertionFromRange(
10828                   InsertLoc, CharSourceRange::getTokenRange(Before))
10829            << FixItHint::CreateRemoval(Before);
10830       }
10831     } else if (!Proto->getReturnType()->isDependentType()) {
10832       DB << /*typedef*/1 << Proto->getReturnType();
10833     } else if (getLangOpts().CPlusPlus11) {
10834       DB << /*alias template*/2 << Proto->getReturnType();
10835     } else {
10836       DB << /*might not be fixable*/3;
10837     }
10838 
10839     // Recover by incorporating the other type chunks into the result type.
10840     // Note, this does *not* change the name of the function. This is compatible
10841     // with the GCC extension:
10842     //   struct S { &operator int(); } s;
10843     //   int &r = s.operator int(); // ok in GCC
10844     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10845     ConvType = Proto->getReturnType();
10846   }
10847 
10848   // C++ [class.conv.fct]p4:
10849   //   The conversion-type-id shall not represent a function type nor
10850   //   an array type.
10851   if (ConvType->isArrayType()) {
10852     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10853     ConvType = Context.getPointerType(ConvType);
10854     D.setInvalidType();
10855   } else if (ConvType->isFunctionType()) {
10856     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10857     ConvType = Context.getPointerType(ConvType);
10858     D.setInvalidType();
10859   }
10860 
10861   // Rebuild the function type "R" without any parameters (in case any
10862   // of the errors above fired) and with the conversion type as the
10863   // return type.
10864   if (D.isInvalidType())
10865     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10866 
10867   // C++0x explicit conversion operators.
10868   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10869     Diag(DS.getExplicitSpecLoc(),
10870          getLangOpts().CPlusPlus11
10871              ? diag::warn_cxx98_compat_explicit_conversion_functions
10872              : diag::ext_explicit_conversion_functions)
10873         << SourceRange(DS.getExplicitSpecRange());
10874 }
10875 
10876 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10877 /// the declaration of the given C++ conversion function. This routine
10878 /// is responsible for recording the conversion function in the C++
10879 /// class, if possible.
10880 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10881   assert(Conversion && "Expected to receive a conversion function declaration");
10882 
10883   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10884 
10885   // Make sure we aren't redeclaring the conversion function.
10886   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10887   // C++ [class.conv.fct]p1:
10888   //   [...] A conversion function is never used to convert a
10889   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10890   //   same object type (or a reference to it), to a (possibly
10891   //   cv-qualified) base class of that type (or a reference to it),
10892   //   or to (possibly cv-qualified) void.
10893   QualType ClassType
10894     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10895   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10896     ConvType = ConvTypeRef->getPointeeType();
10897   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10898       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10899     /* Suppress diagnostics for instantiations. */;
10900   else if (Conversion->size_overridden_methods() != 0)
10901     /* Suppress diagnostics for overriding virtual function in a base class. */;
10902   else if (ConvType->isRecordType()) {
10903     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10904     if (ConvType == ClassType)
10905       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10906         << ClassType;
10907     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10908       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10909         <<  ClassType << ConvType;
10910   } else if (ConvType->isVoidType()) {
10911     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10912       << ClassType << ConvType;
10913   }
10914 
10915   if (FunctionTemplateDecl *ConversionTemplate
10916                                 = Conversion->getDescribedFunctionTemplate())
10917     return ConversionTemplate;
10918 
10919   return Conversion;
10920 }
10921 
10922 namespace {
10923 /// Utility class to accumulate and print a diagnostic listing the invalid
10924 /// specifier(s) on a declaration.
10925 struct BadSpecifierDiagnoser {
10926   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10927       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10928   ~BadSpecifierDiagnoser() {
10929     Diagnostic << Specifiers;
10930   }
10931 
10932   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10933     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10934   }
10935   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10936     return check(SpecLoc,
10937                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10938   }
10939   void check(SourceLocation SpecLoc, const char *Spec) {
10940     if (SpecLoc.isInvalid()) return;
10941     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10942     if (!Specifiers.empty()) Specifiers += " ";
10943     Specifiers += Spec;
10944   }
10945 
10946   Sema &S;
10947   Sema::SemaDiagnosticBuilder Diagnostic;
10948   std::string Specifiers;
10949 };
10950 }
10951 
10952 /// Check the validity of a declarator that we parsed for a deduction-guide.
10953 /// These aren't actually declarators in the grammar, so we need to check that
10954 /// the user didn't specify any pieces that are not part of the deduction-guide
10955 /// grammar.
10956 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10957                                          StorageClass &SC) {
10958   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10959   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10960   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10961 
10962   // C++ [temp.deduct.guide]p3:
10963   //   A deduction-gide shall be declared in the same scope as the
10964   //   corresponding class template.
10965   if (!CurContext->getRedeclContext()->Equals(
10966           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10967     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10968       << GuidedTemplateDecl;
10969     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10970   }
10971 
10972   auto &DS = D.getMutableDeclSpec();
10973   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10974   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10975       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10976       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10977     BadSpecifierDiagnoser Diagnoser(
10978         *this, D.getIdentifierLoc(),
10979         diag::err_deduction_guide_invalid_specifier);
10980 
10981     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10982     DS.ClearStorageClassSpecs();
10983     SC = SC_None;
10984 
10985     // 'explicit' is permitted.
10986     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10987     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10988     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10989     DS.ClearConstexprSpec();
10990 
10991     Diagnoser.check(DS.getConstSpecLoc(), "const");
10992     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10993     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10994     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10995     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10996     DS.ClearTypeQualifiers();
10997 
10998     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10999     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11000     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11001     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11002     DS.ClearTypeSpecType();
11003   }
11004 
11005   if (D.isInvalidType())
11006     return;
11007 
11008   // Check the declarator is simple enough.
11009   bool FoundFunction = false;
11010   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11011     if (Chunk.Kind == DeclaratorChunk::Paren)
11012       continue;
11013     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11014       Diag(D.getDeclSpec().getBeginLoc(),
11015            diag::err_deduction_guide_with_complex_decl)
11016           << D.getSourceRange();
11017       break;
11018     }
11019     if (!Chunk.Fun.hasTrailingReturnType()) {
11020       Diag(D.getName().getBeginLoc(),
11021            diag::err_deduction_guide_no_trailing_return_type);
11022       break;
11023     }
11024 
11025     // Check that the return type is written as a specialization of
11026     // the template specified as the deduction-guide's name.
11027     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11028     TypeSourceInfo *TSI = nullptr;
11029     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11030     assert(TSI && "deduction guide has valid type but invalid return type?");
11031     bool AcceptableReturnType = false;
11032     bool MightInstantiateToSpecialization = false;
11033     if (auto RetTST =
11034             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
11035       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11036       bool TemplateMatches =
11037           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11038       // FIXME: We should consider other template kinds (using, qualified),
11039       // otherwise we will emit bogus diagnostics.
11040       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
11041         AcceptableReturnType = true;
11042       else {
11043         // This could still instantiate to the right type, unless we know it
11044         // names the wrong class template.
11045         auto *TD = SpecifiedName.getAsTemplateDecl();
11046         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11047                                              !TemplateMatches);
11048       }
11049     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11050       MightInstantiateToSpecialization = true;
11051     }
11052 
11053     if (!AcceptableReturnType) {
11054       Diag(TSI->getTypeLoc().getBeginLoc(),
11055            diag::err_deduction_guide_bad_trailing_return_type)
11056           << GuidedTemplate << TSI->getType()
11057           << MightInstantiateToSpecialization
11058           << TSI->getTypeLoc().getSourceRange();
11059     }
11060 
11061     // Keep going to check that we don't have any inner declarator pieces (we
11062     // could still have a function returning a pointer to a function).
11063     FoundFunction = true;
11064   }
11065 
11066   if (D.isFunctionDefinition())
11067     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11068 }
11069 
11070 //===----------------------------------------------------------------------===//
11071 // Namespace Handling
11072 //===----------------------------------------------------------------------===//
11073 
11074 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11075 /// reopened.
11076 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11077                                             SourceLocation Loc,
11078                                             IdentifierInfo *II, bool *IsInline,
11079                                             NamespaceDecl *PrevNS) {
11080   assert(*IsInline != PrevNS->isInline());
11081 
11082   // 'inline' must appear on the original definition, but not necessarily
11083   // on all extension definitions, so the note should point to the first
11084   // definition to avoid confusion.
11085   PrevNS = PrevNS->getFirstDecl();
11086 
11087   if (PrevNS->isInline())
11088     // The user probably just forgot the 'inline', so suggest that it
11089     // be added back.
11090     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11091       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11092   else
11093     S.Diag(Loc, diag::err_inline_namespace_mismatch);
11094 
11095   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11096   *IsInline = PrevNS->isInline();
11097 }
11098 
11099 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11100 /// definition.
11101 Decl *Sema::ActOnStartNamespaceDef(
11102     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
11103     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
11104     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
11105   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11106   // For anonymous namespace, take the location of the left brace.
11107   SourceLocation Loc = II ? IdentLoc : LBrace;
11108   bool IsInline = InlineLoc.isValid();
11109   bool IsInvalid = false;
11110   bool IsStd = false;
11111   bool AddToKnown = false;
11112   Scope *DeclRegionScope = NamespcScope->getParent();
11113 
11114   NamespaceDecl *PrevNS = nullptr;
11115   if (II) {
11116     // C++ [namespace.def]p2:
11117     //   The identifier in an original-namespace-definition shall not
11118     //   have been previously defined in the declarative region in
11119     //   which the original-namespace-definition appears. The
11120     //   identifier in an original-namespace-definition is the name of
11121     //   the namespace. Subsequently in that declarative region, it is
11122     //   treated as an original-namespace-name.
11123     //
11124     // Since namespace names are unique in their scope, and we don't
11125     // look through using directives, just look for any ordinary names
11126     // as if by qualified name lookup.
11127     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11128                    ForExternalRedeclaration);
11129     LookupQualifiedName(R, CurContext->getRedeclContext());
11130     NamedDecl *PrevDecl =
11131         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11132     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11133 
11134     if (PrevNS) {
11135       // This is an extended namespace definition.
11136       if (IsInline != PrevNS->isInline())
11137         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11138                                         &IsInline, PrevNS);
11139     } else if (PrevDecl) {
11140       // This is an invalid name redefinition.
11141       Diag(Loc, diag::err_redefinition_different_kind)
11142         << II;
11143       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11144       IsInvalid = true;
11145       // Continue on to push Namespc as current DeclContext and return it.
11146     } else if (II->isStr("std") &&
11147                CurContext->getRedeclContext()->isTranslationUnit()) {
11148       // This is the first "real" definition of the namespace "std", so update
11149       // our cache of the "std" namespace to point at this definition.
11150       PrevNS = getStdNamespace();
11151       IsStd = true;
11152       AddToKnown = !IsInline;
11153     } else {
11154       // We've seen this namespace for the first time.
11155       AddToKnown = !IsInline;
11156     }
11157   } else {
11158     // Anonymous namespaces.
11159 
11160     // Determine whether the parent already has an anonymous namespace.
11161     DeclContext *Parent = CurContext->getRedeclContext();
11162     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11163       PrevNS = TU->getAnonymousNamespace();
11164     } else {
11165       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11166       PrevNS = ND->getAnonymousNamespace();
11167     }
11168 
11169     if (PrevNS && IsInline != PrevNS->isInline())
11170       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11171                                       &IsInline, PrevNS);
11172   }
11173 
11174   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
11175                                                  StartLoc, Loc, II, PrevNS);
11176   if (IsInvalid)
11177     Namespc->setInvalidDecl();
11178 
11179   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11180   AddPragmaAttributes(DeclRegionScope, Namespc);
11181 
11182   // FIXME: Should we be merging attributes?
11183   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11184     PushNamespaceVisibilityAttr(Attr, Loc);
11185 
11186   if (IsStd)
11187     StdNamespace = Namespc;
11188   if (AddToKnown)
11189     KnownNamespaces[Namespc] = false;
11190 
11191   if (II) {
11192     PushOnScopeChains(Namespc, DeclRegionScope);
11193   } else {
11194     // Link the anonymous namespace into its parent.
11195     DeclContext *Parent = CurContext->getRedeclContext();
11196     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11197       TU->setAnonymousNamespace(Namespc);
11198     } else {
11199       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11200     }
11201 
11202     CurContext->addDecl(Namespc);
11203 
11204     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11205     //   behaves as if it were replaced by
11206     //     namespace unique { /* empty body */ }
11207     //     using namespace unique;
11208     //     namespace unique { namespace-body }
11209     //   where all occurrences of 'unique' in a translation unit are
11210     //   replaced by the same identifier and this identifier differs
11211     //   from all other identifiers in the entire program.
11212 
11213     // We just create the namespace with an empty name and then add an
11214     // implicit using declaration, just like the standard suggests.
11215     //
11216     // CodeGen enforces the "universally unique" aspect by giving all
11217     // declarations semantically contained within an anonymous
11218     // namespace internal linkage.
11219 
11220     if (!PrevNS) {
11221       UD = UsingDirectiveDecl::Create(Context, Parent,
11222                                       /* 'using' */ LBrace,
11223                                       /* 'namespace' */ SourceLocation(),
11224                                       /* qualifier */ NestedNameSpecifierLoc(),
11225                                       /* identifier */ SourceLocation(),
11226                                       Namespc,
11227                                       /* Ancestor */ Parent);
11228       UD->setImplicit();
11229       Parent->addDecl(UD);
11230     }
11231   }
11232 
11233   ActOnDocumentableDecl(Namespc);
11234 
11235   // Although we could have an invalid decl (i.e. the namespace name is a
11236   // redefinition), push it as current DeclContext and try to continue parsing.
11237   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11238   // for the namespace has the declarations that showed up in that particular
11239   // namespace definition.
11240   PushDeclContext(NamespcScope, Namespc);
11241   return Namespc;
11242 }
11243 
11244 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11245 /// is a namespace alias, returns the namespace it points to.
11246 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11247   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11248     return AD->getNamespace();
11249   return dyn_cast_or_null<NamespaceDecl>(D);
11250 }
11251 
11252 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11253 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11254 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11255   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11256   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11257   Namespc->setRBraceLoc(RBrace);
11258   PopDeclContext();
11259   if (Namespc->hasAttr<VisibilityAttr>())
11260     PopPragmaVisibility(true, RBrace);
11261   // If this namespace contains an export-declaration, export it now.
11262   if (DeferredExportedNamespaces.erase(Namespc))
11263     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11264 }
11265 
11266 CXXRecordDecl *Sema::getStdBadAlloc() const {
11267   return cast_or_null<CXXRecordDecl>(
11268                                   StdBadAlloc.get(Context.getExternalSource()));
11269 }
11270 
11271 EnumDecl *Sema::getStdAlignValT() const {
11272   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11273 }
11274 
11275 NamespaceDecl *Sema::getStdNamespace() const {
11276   return cast_or_null<NamespaceDecl>(
11277                                  StdNamespace.get(Context.getExternalSource()));
11278 }
11279 
11280 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11281   if (!StdExperimentalNamespaceCache) {
11282     if (auto Std = getStdNamespace()) {
11283       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11284                           SourceLocation(), LookupNamespaceName);
11285       if (!LookupQualifiedName(Result, Std) ||
11286           !(StdExperimentalNamespaceCache =
11287                 Result.getAsSingle<NamespaceDecl>()))
11288         Result.suppressDiagnostics();
11289     }
11290   }
11291   return StdExperimentalNamespaceCache;
11292 }
11293 
11294 namespace {
11295 
11296 enum UnsupportedSTLSelect {
11297   USS_InvalidMember,
11298   USS_MissingMember,
11299   USS_NonTrivial,
11300   USS_Other
11301 };
11302 
11303 struct InvalidSTLDiagnoser {
11304   Sema &S;
11305   SourceLocation Loc;
11306   QualType TyForDiags;
11307 
11308   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11309                       const VarDecl *VD = nullptr) {
11310     {
11311       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11312                << TyForDiags << ((int)Sel);
11313       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11314         assert(!Name.empty());
11315         D << Name;
11316       }
11317     }
11318     if (Sel == USS_InvalidMember) {
11319       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11320           << VD << VD->getSourceRange();
11321     }
11322     return QualType();
11323   }
11324 };
11325 } // namespace
11326 
11327 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11328                                            SourceLocation Loc,
11329                                            ComparisonCategoryUsage Usage) {
11330   assert(getLangOpts().CPlusPlus &&
11331          "Looking for comparison category type outside of C++.");
11332 
11333   // Use an elaborated type for diagnostics which has a name containing the
11334   // prepended 'std' namespace but not any inline namespace names.
11335   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11336     auto *NNS =
11337         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11338     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11339   };
11340 
11341   // Check if we've already successfully checked the comparison category type
11342   // before. If so, skip checking it again.
11343   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11344   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11345     // The only thing we need to check is that the type has a reachable
11346     // definition in the current context.
11347     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11348       return QualType();
11349 
11350     return Info->getType();
11351   }
11352 
11353   // If lookup failed
11354   if (!Info) {
11355     std::string NameForDiags = "std::";
11356     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11357     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11358         << NameForDiags << (int)Usage;
11359     return QualType();
11360   }
11361 
11362   assert(Info->Kind == Kind);
11363   assert(Info->Record);
11364 
11365   // Update the Record decl in case we encountered a forward declaration on our
11366   // first pass. FIXME: This is a bit of a hack.
11367   if (Info->Record->hasDefinition())
11368     Info->Record = Info->Record->getDefinition();
11369 
11370   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11371     return QualType();
11372 
11373   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11374 
11375   if (!Info->Record->isTriviallyCopyable())
11376     return UnsupportedSTLError(USS_NonTrivial);
11377 
11378   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11379     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11380     // Tolerate empty base classes.
11381     if (Base->isEmpty())
11382       continue;
11383     // Reject STL implementations which have at least one non-empty base.
11384     return UnsupportedSTLError();
11385   }
11386 
11387   // Check that the STL has implemented the types using a single integer field.
11388   // This expectation allows better codegen for builtin operators. We require:
11389   //   (1) The class has exactly one field.
11390   //   (2) The field is an integral or enumeration type.
11391   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11392   if (std::distance(FIt, FEnd) != 1 ||
11393       !FIt->getType()->isIntegralOrEnumerationType()) {
11394     return UnsupportedSTLError();
11395   }
11396 
11397   // Build each of the require values and store them in Info.
11398   for (ComparisonCategoryResult CCR :
11399        ComparisonCategories::getPossibleResultsForType(Kind)) {
11400     StringRef MemName = ComparisonCategories::getResultString(CCR);
11401     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11402 
11403     if (!ValInfo)
11404       return UnsupportedSTLError(USS_MissingMember, MemName);
11405 
11406     VarDecl *VD = ValInfo->VD;
11407     assert(VD && "should not be null!");
11408 
11409     // Attempt to diagnose reasons why the STL definition of this type
11410     // might be foobar, including it failing to be a constant expression.
11411     // TODO Handle more ways the lookup or result can be invalid.
11412     if (!VD->isStaticDataMember() ||
11413         !VD->isUsableInConstantExpressions(Context))
11414       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11415 
11416     // Attempt to evaluate the var decl as a constant expression and extract
11417     // the value of its first field as a ICE. If this fails, the STL
11418     // implementation is not supported.
11419     if (!ValInfo->hasValidIntValue())
11420       return UnsupportedSTLError();
11421 
11422     MarkVariableReferenced(Loc, VD);
11423   }
11424 
11425   // We've successfully built the required types and expressions. Update
11426   // the cache and return the newly cached value.
11427   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11428   return Info->getType();
11429 }
11430 
11431 /// Retrieve the special "std" namespace, which may require us to
11432 /// implicitly define the namespace.
11433 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11434   if (!StdNamespace) {
11435     // The "std" namespace has not yet been defined, so build one implicitly.
11436     StdNamespace = NamespaceDecl::Create(Context,
11437                                          Context.getTranslationUnitDecl(),
11438                                          /*Inline=*/false,
11439                                          SourceLocation(), SourceLocation(),
11440                                          &PP.getIdentifierTable().get("std"),
11441                                          /*PrevDecl=*/nullptr);
11442     getStdNamespace()->setImplicit(true);
11443   }
11444 
11445   return getStdNamespace();
11446 }
11447 
11448 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11449   assert(getLangOpts().CPlusPlus &&
11450          "Looking for std::initializer_list outside of C++.");
11451 
11452   // We're looking for implicit instantiations of
11453   // template <typename E> class std::initializer_list.
11454 
11455   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11456     return false;
11457 
11458   ClassTemplateDecl *Template = nullptr;
11459   const TemplateArgument *Arguments = nullptr;
11460 
11461   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11462 
11463     ClassTemplateSpecializationDecl *Specialization =
11464         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11465     if (!Specialization)
11466       return false;
11467 
11468     Template = Specialization->getSpecializedTemplate();
11469     Arguments = Specialization->getTemplateArgs().data();
11470   } else if (const TemplateSpecializationType *TST =
11471                  Ty->getAs<TemplateSpecializationType>()) {
11472     Template = dyn_cast_or_null<ClassTemplateDecl>(
11473         TST->getTemplateName().getAsTemplateDecl());
11474     Arguments = TST->getArgs();
11475   }
11476   if (!Template)
11477     return false;
11478 
11479   if (!StdInitializerList) {
11480     // Haven't recognized std::initializer_list yet, maybe this is it.
11481     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11482     if (TemplateClass->getIdentifier() !=
11483             &PP.getIdentifierTable().get("initializer_list") ||
11484         !getStdNamespace()->InEnclosingNamespaceSetOf(
11485             TemplateClass->getDeclContext()))
11486       return false;
11487     // This is a template called std::initializer_list, but is it the right
11488     // template?
11489     TemplateParameterList *Params = Template->getTemplateParameters();
11490     if (Params->getMinRequiredArguments() != 1)
11491       return false;
11492     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11493       return false;
11494 
11495     // It's the right template.
11496     StdInitializerList = Template;
11497   }
11498 
11499   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11500     return false;
11501 
11502   // This is an instance of std::initializer_list. Find the argument type.
11503   if (Element)
11504     *Element = Arguments[0].getAsType();
11505   return true;
11506 }
11507 
11508 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11509   NamespaceDecl *Std = S.getStdNamespace();
11510   if (!Std) {
11511     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11512     return nullptr;
11513   }
11514 
11515   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11516                       Loc, Sema::LookupOrdinaryName);
11517   if (!S.LookupQualifiedName(Result, Std)) {
11518     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11519     return nullptr;
11520   }
11521   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11522   if (!Template) {
11523     Result.suppressDiagnostics();
11524     // We found something weird. Complain about the first thing we found.
11525     NamedDecl *Found = *Result.begin();
11526     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11527     return nullptr;
11528   }
11529 
11530   // We found some template called std::initializer_list. Now verify that it's
11531   // correct.
11532   TemplateParameterList *Params = Template->getTemplateParameters();
11533   if (Params->getMinRequiredArguments() != 1 ||
11534       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11535     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11536     return nullptr;
11537   }
11538 
11539   return Template;
11540 }
11541 
11542 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11543   if (!StdInitializerList) {
11544     StdInitializerList = LookupStdInitializerList(*this, Loc);
11545     if (!StdInitializerList)
11546       return QualType();
11547   }
11548 
11549   TemplateArgumentListInfo Args(Loc, Loc);
11550   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11551                                        Context.getTrivialTypeSourceInfo(Element,
11552                                                                         Loc)));
11553   return Context.getCanonicalType(
11554       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11555 }
11556 
11557 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11558   // C++ [dcl.init.list]p2:
11559   //   A constructor is an initializer-list constructor if its first parameter
11560   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11561   //   std::initializer_list<E> for some type E, and either there are no other
11562   //   parameters or else all other parameters have default arguments.
11563   if (!Ctor->hasOneParamOrDefaultArgs())
11564     return false;
11565 
11566   QualType ArgType = Ctor->getParamDecl(0)->getType();
11567   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11568     ArgType = RT->getPointeeType().getUnqualifiedType();
11569 
11570   return isStdInitializerList(ArgType, nullptr);
11571 }
11572 
11573 /// Determine whether a using statement is in a context where it will be
11574 /// apply in all contexts.
11575 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11576   switch (CurContext->getDeclKind()) {
11577     case Decl::TranslationUnit:
11578       return true;
11579     case Decl::LinkageSpec:
11580       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11581     default:
11582       return false;
11583   }
11584 }
11585 
11586 namespace {
11587 
11588 // Callback to only accept typo corrections that are namespaces.
11589 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11590 public:
11591   bool ValidateCandidate(const TypoCorrection &candidate) override {
11592     if (NamedDecl *ND = candidate.getCorrectionDecl())
11593       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11594     return false;
11595   }
11596 
11597   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11598     return std::make_unique<NamespaceValidatorCCC>(*this);
11599   }
11600 };
11601 
11602 }
11603 
11604 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11605                                        CXXScopeSpec &SS,
11606                                        SourceLocation IdentLoc,
11607                                        IdentifierInfo *Ident) {
11608   R.clear();
11609   NamespaceValidatorCCC CCC{};
11610   if (TypoCorrection Corrected =
11611           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11612                         Sema::CTK_ErrorRecovery)) {
11613     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11614       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11615       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11616                               Ident->getName().equals(CorrectedStr);
11617       S.diagnoseTypo(Corrected,
11618                      S.PDiag(diag::err_using_directive_member_suggest)
11619                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11620                      S.PDiag(diag::note_namespace_defined_here));
11621     } else {
11622       S.diagnoseTypo(Corrected,
11623                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11624                      S.PDiag(diag::note_namespace_defined_here));
11625     }
11626     R.addDecl(Corrected.getFoundDecl());
11627     return true;
11628   }
11629   return false;
11630 }
11631 
11632 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11633                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11634                                 SourceLocation IdentLoc,
11635                                 IdentifierInfo *NamespcName,
11636                                 const ParsedAttributesView &AttrList) {
11637   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11638   assert(NamespcName && "Invalid NamespcName.");
11639   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11640 
11641   // This can only happen along a recovery path.
11642   while (S->isTemplateParamScope())
11643     S = S->getParent();
11644   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11645 
11646   UsingDirectiveDecl *UDir = nullptr;
11647   NestedNameSpecifier *Qualifier = nullptr;
11648   if (SS.isSet())
11649     Qualifier = SS.getScopeRep();
11650 
11651   // Lookup namespace name.
11652   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11653   LookupParsedName(R, S, &SS);
11654   if (R.isAmbiguous())
11655     return nullptr;
11656 
11657   if (R.empty()) {
11658     R.clear();
11659     // Allow "using namespace std;" or "using namespace ::std;" even if
11660     // "std" hasn't been defined yet, for GCC compatibility.
11661     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11662         NamespcName->isStr("std")) {
11663       Diag(IdentLoc, diag::ext_using_undefined_std);
11664       R.addDecl(getOrCreateStdNamespace());
11665       R.resolveKind();
11666     }
11667     // Otherwise, attempt typo correction.
11668     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11669   }
11670 
11671   if (!R.empty()) {
11672     NamedDecl *Named = R.getRepresentativeDecl();
11673     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11674     assert(NS && "expected namespace decl");
11675 
11676     // The use of a nested name specifier may trigger deprecation warnings.
11677     DiagnoseUseOfDecl(Named, IdentLoc);
11678 
11679     // C++ [namespace.udir]p1:
11680     //   A using-directive specifies that the names in the nominated
11681     //   namespace can be used in the scope in which the
11682     //   using-directive appears after the using-directive. During
11683     //   unqualified name lookup (3.4.1), the names appear as if they
11684     //   were declared in the nearest enclosing namespace which
11685     //   contains both the using-directive and the nominated
11686     //   namespace. [Note: in this context, "contains" means "contains
11687     //   directly or indirectly". ]
11688 
11689     // Find enclosing context containing both using-directive and
11690     // nominated namespace.
11691     DeclContext *CommonAncestor = NS;
11692     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11693       CommonAncestor = CommonAncestor->getParent();
11694 
11695     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11696                                       SS.getWithLocInContext(Context),
11697                                       IdentLoc, Named, CommonAncestor);
11698 
11699     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11700         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11701       Diag(IdentLoc, diag::warn_using_directive_in_header);
11702     }
11703 
11704     PushUsingDirective(S, UDir);
11705   } else {
11706     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11707   }
11708 
11709   if (UDir)
11710     ProcessDeclAttributeList(S, UDir, AttrList);
11711 
11712   return UDir;
11713 }
11714 
11715 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11716   // If the scope has an associated entity and the using directive is at
11717   // namespace or translation unit scope, add the UsingDirectiveDecl into
11718   // its lookup structure so qualified name lookup can find it.
11719   DeclContext *Ctx = S->getEntity();
11720   if (Ctx && !Ctx->isFunctionOrMethod())
11721     Ctx->addDecl(UDir);
11722   else
11723     // Otherwise, it is at block scope. The using-directives will affect lookup
11724     // only to the end of the scope.
11725     S->PushUsingDirective(UDir);
11726 }
11727 
11728 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11729                                   SourceLocation UsingLoc,
11730                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11731                                   UnqualifiedId &Name,
11732                                   SourceLocation EllipsisLoc,
11733                                   const ParsedAttributesView &AttrList) {
11734   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11735 
11736   if (SS.isEmpty()) {
11737     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11738     return nullptr;
11739   }
11740 
11741   switch (Name.getKind()) {
11742   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11743   case UnqualifiedIdKind::IK_Identifier:
11744   case UnqualifiedIdKind::IK_OperatorFunctionId:
11745   case UnqualifiedIdKind::IK_LiteralOperatorId:
11746   case UnqualifiedIdKind::IK_ConversionFunctionId:
11747     break;
11748 
11749   case UnqualifiedIdKind::IK_ConstructorName:
11750   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11751     // C++11 inheriting constructors.
11752     Diag(Name.getBeginLoc(),
11753          getLangOpts().CPlusPlus11
11754              ? diag::warn_cxx98_compat_using_decl_constructor
11755              : diag::err_using_decl_constructor)
11756         << SS.getRange();
11757 
11758     if (getLangOpts().CPlusPlus11) break;
11759 
11760     return nullptr;
11761 
11762   case UnqualifiedIdKind::IK_DestructorName:
11763     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11764     return nullptr;
11765 
11766   case UnqualifiedIdKind::IK_TemplateId:
11767     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11768         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11769     return nullptr;
11770 
11771   case UnqualifiedIdKind::IK_DeductionGuideName:
11772     llvm_unreachable("cannot parse qualified deduction guide name");
11773   }
11774 
11775   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11776   DeclarationName TargetName = TargetNameInfo.getName();
11777   if (!TargetName)
11778     return nullptr;
11779 
11780   // Warn about access declarations.
11781   if (UsingLoc.isInvalid()) {
11782     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11783                                  ? diag::err_access_decl
11784                                  : diag::warn_access_decl_deprecated)
11785         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11786   }
11787 
11788   if (EllipsisLoc.isInvalid()) {
11789     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11790         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11791       return nullptr;
11792   } else {
11793     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11794         !TargetNameInfo.containsUnexpandedParameterPack()) {
11795       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11796         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11797       EllipsisLoc = SourceLocation();
11798     }
11799   }
11800 
11801   NamedDecl *UD =
11802       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11803                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11804                             /*IsInstantiation*/ false,
11805                             AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11806   if (UD)
11807     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11808 
11809   return UD;
11810 }
11811 
11812 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
11813                                       SourceLocation UsingLoc,
11814                                       SourceLocation EnumLoc,
11815                                       const DeclSpec &DS) {
11816   switch (DS.getTypeSpecType()) {
11817   case DeclSpec::TST_error:
11818     // This will already have been diagnosed
11819     return nullptr;
11820 
11821   case DeclSpec::TST_enum:
11822     break;
11823 
11824   case DeclSpec::TST_typename:
11825     Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
11826     return nullptr;
11827 
11828   default:
11829     llvm_unreachable("unexpected DeclSpec type");
11830   }
11831 
11832   // As with enum-decls, we ignore attributes for now.
11833   auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
11834   if (auto *Def = Enum->getDefinition())
11835     Enum = Def;
11836 
11837   auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
11838                                        DS.getTypeSpecTypeNameLoc(), Enum);
11839   if (UD)
11840     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11841 
11842   return UD;
11843 }
11844 
11845 /// Determine whether a using declaration considers the given
11846 /// declarations as "equivalent", e.g., if they are redeclarations of
11847 /// the same entity or are both typedefs of the same type.
11848 static bool
11849 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11850   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11851     return true;
11852 
11853   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11854     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11855       return Context.hasSameType(TD1->getUnderlyingType(),
11856                                  TD2->getUnderlyingType());
11857 
11858   // Two using_if_exists using-declarations are equivalent if both are
11859   // unresolved.
11860   if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11861       isa<UnresolvedUsingIfExistsDecl>(D2))
11862     return true;
11863 
11864   return false;
11865 }
11866 
11867 
11868 /// Determines whether to create a using shadow decl for a particular
11869 /// decl, given the set of decls existing prior to this using lookup.
11870 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
11871                                 const LookupResult &Previous,
11872                                 UsingShadowDecl *&PrevShadow) {
11873   // Diagnose finding a decl which is not from a base class of the
11874   // current class.  We do this now because there are cases where this
11875   // function will silently decide not to build a shadow decl, which
11876   // will pre-empt further diagnostics.
11877   //
11878   // We don't need to do this in C++11 because we do the check once on
11879   // the qualifier.
11880   //
11881   // FIXME: diagnose the following if we care enough:
11882   //   struct A { int foo; };
11883   //   struct B : A { using A::foo; };
11884   //   template <class T> struct C : A {};
11885   //   template <class T> struct D : C<T> { using B::foo; } // <---
11886   // This is invalid (during instantiation) in C++03 because B::foo
11887   // resolves to the using decl in B, which is not a base class of D<T>.
11888   // We can't diagnose it immediately because C<T> is an unknown
11889   // specialization. The UsingShadowDecl in D<T> then points directly
11890   // to A::foo, which will look well-formed when we instantiate.
11891   // The right solution is to not collapse the shadow-decl chain.
11892   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
11893     if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
11894       DeclContext *OrigDC = Orig->getDeclContext();
11895 
11896       // Handle enums and anonymous structs.
11897       if (isa<EnumDecl>(OrigDC))
11898         OrigDC = OrigDC->getParent();
11899       CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11900       while (OrigRec->isAnonymousStructOrUnion())
11901         OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11902 
11903       if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11904         if (OrigDC == CurContext) {
11905           Diag(Using->getLocation(),
11906                diag::err_using_decl_nested_name_specifier_is_current_class)
11907               << Using->getQualifierLoc().getSourceRange();
11908           Diag(Orig->getLocation(), diag::note_using_decl_target);
11909           Using->setInvalidDecl();
11910           return true;
11911         }
11912 
11913         Diag(Using->getQualifierLoc().getBeginLoc(),
11914              diag::err_using_decl_nested_name_specifier_is_not_base_class)
11915             << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
11916             << Using->getQualifierLoc().getSourceRange();
11917         Diag(Orig->getLocation(), diag::note_using_decl_target);
11918         Using->setInvalidDecl();
11919         return true;
11920       }
11921     }
11922 
11923   if (Previous.empty()) return false;
11924 
11925   NamedDecl *Target = Orig;
11926   if (isa<UsingShadowDecl>(Target))
11927     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11928 
11929   // If the target happens to be one of the previous declarations, we
11930   // don't have a conflict.
11931   //
11932   // FIXME: but we might be increasing its access, in which case we
11933   // should redeclare it.
11934   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11935   bool FoundEquivalentDecl = false;
11936   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11937          I != E; ++I) {
11938     NamedDecl *D = (*I)->getUnderlyingDecl();
11939     // We can have UsingDecls in our Previous results because we use the same
11940     // LookupResult for checking whether the UsingDecl itself is a valid
11941     // redeclaration.
11942     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
11943       continue;
11944 
11945     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11946       // C++ [class.mem]p19:
11947       //   If T is the name of a class, then [every named member other than
11948       //   a non-static data member] shall have a name different from T
11949       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11950           !isa<IndirectFieldDecl>(Target) &&
11951           !isa<UnresolvedUsingValueDecl>(Target) &&
11952           DiagnoseClassNameShadow(
11953               CurContext,
11954               DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
11955         return true;
11956     }
11957 
11958     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11959       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11960         PrevShadow = Shadow;
11961       FoundEquivalentDecl = true;
11962     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11963       // We don't conflict with an existing using shadow decl of an equivalent
11964       // declaration, but we're not a redeclaration of it.
11965       FoundEquivalentDecl = true;
11966     }
11967 
11968     if (isVisible(D))
11969       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11970   }
11971 
11972   if (FoundEquivalentDecl)
11973     return false;
11974 
11975   // Always emit a diagnostic for a mismatch between an unresolved
11976   // using_if_exists and a resolved using declaration in either direction.
11977   if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
11978       (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
11979     if (!NonTag && !Tag)
11980       return false;
11981     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11982     Diag(Target->getLocation(), diag::note_using_decl_target);
11983     Diag((NonTag ? NonTag : Tag)->getLocation(),
11984          diag::note_using_decl_conflict);
11985     BUD->setInvalidDecl();
11986     return true;
11987   }
11988 
11989   if (FunctionDecl *FD = Target->getAsFunction()) {
11990     NamedDecl *OldDecl = nullptr;
11991     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11992                           /*IsForUsingDecl*/ true)) {
11993     case Ovl_Overload:
11994       return false;
11995 
11996     case Ovl_NonFunction:
11997       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11998       break;
11999 
12000     // We found a decl with the exact signature.
12001     case Ovl_Match:
12002       // If we're in a record, we want to hide the target, so we
12003       // return true (without a diagnostic) to tell the caller not to
12004       // build a shadow decl.
12005       if (CurContext->isRecord())
12006         return true;
12007 
12008       // If we're not in a record, this is an error.
12009       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12010       break;
12011     }
12012 
12013     Diag(Target->getLocation(), diag::note_using_decl_target);
12014     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12015     BUD->setInvalidDecl();
12016     return true;
12017   }
12018 
12019   // Target is not a function.
12020 
12021   if (isa<TagDecl>(Target)) {
12022     // No conflict between a tag and a non-tag.
12023     if (!Tag) return false;
12024 
12025     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12026     Diag(Target->getLocation(), diag::note_using_decl_target);
12027     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12028     BUD->setInvalidDecl();
12029     return true;
12030   }
12031 
12032   // No conflict between a tag and a non-tag.
12033   if (!NonTag) return false;
12034 
12035   Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12036   Diag(Target->getLocation(), diag::note_using_decl_target);
12037   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12038   BUD->setInvalidDecl();
12039   return true;
12040 }
12041 
12042 /// Determine whether a direct base class is a virtual base class.
12043 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12044   if (!Derived->getNumVBases())
12045     return false;
12046   for (auto &B : Derived->bases())
12047     if (B.getType()->getAsCXXRecordDecl() == Base)
12048       return B.isVirtual();
12049   llvm_unreachable("not a direct base class");
12050 }
12051 
12052 /// Builds a shadow declaration corresponding to a 'using' declaration.
12053 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12054                                             NamedDecl *Orig,
12055                                             UsingShadowDecl *PrevDecl) {
12056   // If we resolved to another shadow declaration, just coalesce them.
12057   NamedDecl *Target = Orig;
12058   if (isa<UsingShadowDecl>(Target)) {
12059     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12060     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12061   }
12062 
12063   NamedDecl *NonTemplateTarget = Target;
12064   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12065     NonTemplateTarget = TargetTD->getTemplatedDecl();
12066 
12067   UsingShadowDecl *Shadow;
12068   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12069     UsingDecl *Using = cast<UsingDecl>(BUD);
12070     bool IsVirtualBase =
12071         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12072                             Using->getQualifier()->getAsRecordDecl());
12073     Shadow = ConstructorUsingShadowDecl::Create(
12074         Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12075   } else {
12076     Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12077                                      Target->getDeclName(), BUD, Target);
12078   }
12079   BUD->addShadowDecl(Shadow);
12080 
12081   Shadow->setAccess(BUD->getAccess());
12082   if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12083     Shadow->setInvalidDecl();
12084 
12085   Shadow->setPreviousDecl(PrevDecl);
12086 
12087   if (S)
12088     PushOnScopeChains(Shadow, S);
12089   else
12090     CurContext->addDecl(Shadow);
12091 
12092 
12093   return Shadow;
12094 }
12095 
12096 /// Hides a using shadow declaration.  This is required by the current
12097 /// using-decl implementation when a resolvable using declaration in a
12098 /// class is followed by a declaration which would hide or override
12099 /// one or more of the using decl's targets; for example:
12100 ///
12101 ///   struct Base { void foo(int); };
12102 ///   struct Derived : Base {
12103 ///     using Base::foo;
12104 ///     void foo(int);
12105 ///   };
12106 ///
12107 /// The governing language is C++03 [namespace.udecl]p12:
12108 ///
12109 ///   When a using-declaration brings names from a base class into a
12110 ///   derived class scope, member functions in the derived class
12111 ///   override and/or hide member functions with the same name and
12112 ///   parameter types in a base class (rather than conflicting).
12113 ///
12114 /// There are two ways to implement this:
12115 ///   (1) optimistically create shadow decls when they're not hidden
12116 ///       by existing declarations, or
12117 ///   (2) don't create any shadow decls (or at least don't make them
12118 ///       visible) until we've fully parsed/instantiated the class.
12119 /// The problem with (1) is that we might have to retroactively remove
12120 /// a shadow decl, which requires several O(n) operations because the
12121 /// decl structures are (very reasonably) not designed for removal.
12122 /// (2) avoids this but is very fiddly and phase-dependent.
12123 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12124   if (Shadow->getDeclName().getNameKind() ==
12125         DeclarationName::CXXConversionFunctionName)
12126     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12127 
12128   // Remove it from the DeclContext...
12129   Shadow->getDeclContext()->removeDecl(Shadow);
12130 
12131   // ...and the scope, if applicable...
12132   if (S) {
12133     S->RemoveDecl(Shadow);
12134     IdResolver.RemoveDecl(Shadow);
12135   }
12136 
12137   // ...and the using decl.
12138   Shadow->getIntroducer()->removeShadowDecl(Shadow);
12139 
12140   // TODO: complain somehow if Shadow was used.  It shouldn't
12141   // be possible for this to happen, because...?
12142 }
12143 
12144 /// Find the base specifier for a base class with the given type.
12145 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12146                                                 QualType DesiredBase,
12147                                                 bool &AnyDependentBases) {
12148   // Check whether the named type is a direct base class.
12149   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12150     .getUnqualifiedType();
12151   for (auto &Base : Derived->bases()) {
12152     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12153     if (CanonicalDesiredBase == BaseType)
12154       return &Base;
12155     if (BaseType->isDependentType())
12156       AnyDependentBases = true;
12157   }
12158   return nullptr;
12159 }
12160 
12161 namespace {
12162 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12163 public:
12164   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12165                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12166       : HasTypenameKeyword(HasTypenameKeyword),
12167         IsInstantiation(IsInstantiation), OldNNS(NNS),
12168         RequireMemberOf(RequireMemberOf) {}
12169 
12170   bool ValidateCandidate(const TypoCorrection &Candidate) override {
12171     NamedDecl *ND = Candidate.getCorrectionDecl();
12172 
12173     // Keywords are not valid here.
12174     if (!ND || isa<NamespaceDecl>(ND))
12175       return false;
12176 
12177     // Completely unqualified names are invalid for a 'using' declaration.
12178     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12179       return false;
12180 
12181     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12182     // reject.
12183 
12184     if (RequireMemberOf) {
12185       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12186       if (FoundRecord && FoundRecord->isInjectedClassName()) {
12187         // No-one ever wants a using-declaration to name an injected-class-name
12188         // of a base class, unless they're declaring an inheriting constructor.
12189         ASTContext &Ctx = ND->getASTContext();
12190         if (!Ctx.getLangOpts().CPlusPlus11)
12191           return false;
12192         QualType FoundType = Ctx.getRecordType(FoundRecord);
12193 
12194         // Check that the injected-class-name is named as a member of its own
12195         // type; we don't want to suggest 'using Derived::Base;', since that
12196         // means something else.
12197         NestedNameSpecifier *Specifier =
12198             Candidate.WillReplaceSpecifier()
12199                 ? Candidate.getCorrectionSpecifier()
12200                 : OldNNS;
12201         if (!Specifier->getAsType() ||
12202             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12203           return false;
12204 
12205         // Check that this inheriting constructor declaration actually names a
12206         // direct base class of the current class.
12207         bool AnyDependentBases = false;
12208         if (!findDirectBaseWithType(RequireMemberOf,
12209                                     Ctx.getRecordType(FoundRecord),
12210                                     AnyDependentBases) &&
12211             !AnyDependentBases)
12212           return false;
12213       } else {
12214         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12215         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12216           return false;
12217 
12218         // FIXME: Check that the base class member is accessible?
12219       }
12220     } else {
12221       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12222       if (FoundRecord && FoundRecord->isInjectedClassName())
12223         return false;
12224     }
12225 
12226     if (isa<TypeDecl>(ND))
12227       return HasTypenameKeyword || !IsInstantiation;
12228 
12229     return !HasTypenameKeyword;
12230   }
12231 
12232   std::unique_ptr<CorrectionCandidateCallback> clone() override {
12233     return std::make_unique<UsingValidatorCCC>(*this);
12234   }
12235 
12236 private:
12237   bool HasTypenameKeyword;
12238   bool IsInstantiation;
12239   NestedNameSpecifier *OldNNS;
12240   CXXRecordDecl *RequireMemberOf;
12241 };
12242 } // end anonymous namespace
12243 
12244 /// Remove decls we can't actually see from a lookup being used to declare
12245 /// shadow using decls.
12246 ///
12247 /// \param S - The scope of the potential shadow decl
12248 /// \param Previous - The lookup of a potential shadow decl's name.
12249 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12250   // It is really dumb that we have to do this.
12251   LookupResult::Filter F = Previous.makeFilter();
12252   while (F.hasNext()) {
12253     NamedDecl *D = F.next();
12254     if (!isDeclInScope(D, CurContext, S))
12255       F.erase();
12256     // If we found a local extern declaration that's not ordinarily visible,
12257     // and this declaration is being added to a non-block scope, ignore it.
12258     // We're only checking for scope conflicts here, not also for violations
12259     // of the linkage rules.
12260     else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12261              !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12262       F.erase();
12263   }
12264   F.done();
12265 }
12266 
12267 /// Builds a using declaration.
12268 ///
12269 /// \param IsInstantiation - Whether this call arises from an
12270 ///   instantiation of an unresolved using declaration.  We treat
12271 ///   the lookup differently for these declarations.
12272 NamedDecl *Sema::BuildUsingDeclaration(
12273     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12274     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12275     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12276     const ParsedAttributesView &AttrList, bool IsInstantiation,
12277     bool IsUsingIfExists) {
12278   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12279   SourceLocation IdentLoc = NameInfo.getLoc();
12280   assert(IdentLoc.isValid() && "Invalid TargetName location.");
12281 
12282   // FIXME: We ignore attributes for now.
12283 
12284   // For an inheriting constructor declaration, the name of the using
12285   // declaration is the name of a constructor in this class, not in the
12286   // base class.
12287   DeclarationNameInfo UsingName = NameInfo;
12288   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12289     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12290       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12291           Context.getCanonicalType(Context.getRecordType(RD))));
12292 
12293   // Do the redeclaration lookup in the current scope.
12294   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12295                         ForVisibleRedeclaration);
12296   Previous.setHideTags(false);
12297   if (S) {
12298     LookupName(Previous, S);
12299 
12300     FilterUsingLookup(S, Previous);
12301   } else {
12302     assert(IsInstantiation && "no scope in non-instantiation");
12303     if (CurContext->isRecord())
12304       LookupQualifiedName(Previous, CurContext);
12305     else {
12306       // No redeclaration check is needed here; in non-member contexts we
12307       // diagnosed all possible conflicts with other using-declarations when
12308       // building the template:
12309       //
12310       // For a dependent non-type using declaration, the only valid case is
12311       // if we instantiate to a single enumerator. We check for conflicts
12312       // between shadow declarations we introduce, and we check in the template
12313       // definition for conflicts between a non-type using declaration and any
12314       // other declaration, which together covers all cases.
12315       //
12316       // A dependent typename using declaration will never successfully
12317       // instantiate, since it will always name a class member, so we reject
12318       // that in the template definition.
12319     }
12320   }
12321 
12322   // Check for invalid redeclarations.
12323   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12324                                   SS, IdentLoc, Previous))
12325     return nullptr;
12326 
12327   // 'using_if_exists' doesn't make sense on an inherited constructor.
12328   if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12329                              DeclarationName::CXXConstructorName) {
12330     Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12331     return nullptr;
12332   }
12333 
12334   DeclContext *LookupContext = computeDeclContext(SS);
12335   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12336   if (!LookupContext || EllipsisLoc.isValid()) {
12337     NamedDecl *D;
12338     // Dependent scope, or an unexpanded pack
12339     if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12340                                                   SS, NameInfo, IdentLoc))
12341       return nullptr;
12342 
12343     if (HasTypenameKeyword) {
12344       // FIXME: not all declaration name kinds are legal here
12345       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12346                                               UsingLoc, TypenameLoc,
12347                                               QualifierLoc,
12348                                               IdentLoc, NameInfo.getName(),
12349                                               EllipsisLoc);
12350     } else {
12351       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12352                                            QualifierLoc, NameInfo, EllipsisLoc);
12353     }
12354     D->setAccess(AS);
12355     CurContext->addDecl(D);
12356     ProcessDeclAttributeList(S, D, AttrList);
12357     return D;
12358   }
12359 
12360   auto Build = [&](bool Invalid) {
12361     UsingDecl *UD =
12362         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12363                           UsingName, HasTypenameKeyword);
12364     UD->setAccess(AS);
12365     CurContext->addDecl(UD);
12366     ProcessDeclAttributeList(S, UD, AttrList);
12367     UD->setInvalidDecl(Invalid);
12368     return UD;
12369   };
12370   auto BuildInvalid = [&]{ return Build(true); };
12371   auto BuildValid = [&]{ return Build(false); };
12372 
12373   if (RequireCompleteDeclContext(SS, LookupContext))
12374     return BuildInvalid();
12375 
12376   // Look up the target name.
12377   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12378 
12379   // Unlike most lookups, we don't always want to hide tag
12380   // declarations: tag names are visible through the using declaration
12381   // even if hidden by ordinary names, *except* in a dependent context
12382   // where they may be used by two-phase lookup.
12383   if (!IsInstantiation)
12384     R.setHideTags(false);
12385 
12386   // For the purposes of this lookup, we have a base object type
12387   // equal to that of the current context.
12388   if (CurContext->isRecord()) {
12389     R.setBaseObjectType(
12390                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12391   }
12392 
12393   LookupQualifiedName(R, LookupContext);
12394 
12395   // Validate the context, now we have a lookup
12396   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12397                               IdentLoc, &R))
12398     return nullptr;
12399 
12400   if (R.empty() && IsUsingIfExists)
12401     R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12402                                                   UsingName.getName()),
12403               AS_public);
12404 
12405   // Try to correct typos if possible. If constructor name lookup finds no
12406   // results, that means the named class has no explicit constructors, and we
12407   // suppressed declaring implicit ones (probably because it's dependent or
12408   // invalid).
12409   if (R.empty() &&
12410       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12411     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12412     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12413     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12414     auto *II = NameInfo.getName().getAsIdentifierInfo();
12415     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12416         CurContext->isStdNamespace() &&
12417         isa<TranslationUnitDecl>(LookupContext) &&
12418         getSourceManager().isInSystemHeader(UsingLoc))
12419       return nullptr;
12420     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12421                           dyn_cast<CXXRecordDecl>(CurContext));
12422     if (TypoCorrection Corrected =
12423             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12424                         CTK_ErrorRecovery)) {
12425       // We reject candidates where DroppedSpecifier == true, hence the
12426       // literal '0' below.
12427       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12428                                 << NameInfo.getName() << LookupContext << 0
12429                                 << SS.getRange());
12430 
12431       // If we picked a correction with no attached Decl we can't do anything
12432       // useful with it, bail out.
12433       NamedDecl *ND = Corrected.getCorrectionDecl();
12434       if (!ND)
12435         return BuildInvalid();
12436 
12437       // If we corrected to an inheriting constructor, handle it as one.
12438       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12439       if (RD && RD->isInjectedClassName()) {
12440         // The parent of the injected class name is the class itself.
12441         RD = cast<CXXRecordDecl>(RD->getParent());
12442 
12443         // Fix up the information we'll use to build the using declaration.
12444         if (Corrected.WillReplaceSpecifier()) {
12445           NestedNameSpecifierLocBuilder Builder;
12446           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12447                               QualifierLoc.getSourceRange());
12448           QualifierLoc = Builder.getWithLocInContext(Context);
12449         }
12450 
12451         // In this case, the name we introduce is the name of a derived class
12452         // constructor.
12453         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12454         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12455             Context.getCanonicalType(Context.getRecordType(CurClass))));
12456         UsingName.setNamedTypeInfo(nullptr);
12457         for (auto *Ctor : LookupConstructors(RD))
12458           R.addDecl(Ctor);
12459         R.resolveKind();
12460       } else {
12461         // FIXME: Pick up all the declarations if we found an overloaded
12462         // function.
12463         UsingName.setName(ND->getDeclName());
12464         R.addDecl(ND);
12465       }
12466     } else {
12467       Diag(IdentLoc, diag::err_no_member)
12468         << NameInfo.getName() << LookupContext << SS.getRange();
12469       return BuildInvalid();
12470     }
12471   }
12472 
12473   if (R.isAmbiguous())
12474     return BuildInvalid();
12475 
12476   if (HasTypenameKeyword) {
12477     // If we asked for a typename and got a non-type decl, error out.
12478     if (!R.getAsSingle<TypeDecl>() &&
12479         !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12480       Diag(IdentLoc, diag::err_using_typename_non_type);
12481       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12482         Diag((*I)->getUnderlyingDecl()->getLocation(),
12483              diag::note_using_decl_target);
12484       return BuildInvalid();
12485     }
12486   } else {
12487     // If we asked for a non-typename and we got a type, error out,
12488     // but only if this is an instantiation of an unresolved using
12489     // decl.  Otherwise just silently find the type name.
12490     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12491       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12492       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12493       return BuildInvalid();
12494     }
12495   }
12496 
12497   // C++14 [namespace.udecl]p6:
12498   // A using-declaration shall not name a namespace.
12499   if (R.getAsSingle<NamespaceDecl>()) {
12500     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12501       << SS.getRange();
12502     return BuildInvalid();
12503   }
12504 
12505   UsingDecl *UD = BuildValid();
12506 
12507   // Some additional rules apply to inheriting constructors.
12508   if (UsingName.getName().getNameKind() ==
12509         DeclarationName::CXXConstructorName) {
12510     // Suppress access diagnostics; the access check is instead performed at the
12511     // point of use for an inheriting constructor.
12512     R.suppressDiagnostics();
12513     if (CheckInheritingConstructorUsingDecl(UD))
12514       return UD;
12515   }
12516 
12517   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12518     UsingShadowDecl *PrevDecl = nullptr;
12519     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12520       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12521   }
12522 
12523   return UD;
12524 }
12525 
12526 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12527                                            SourceLocation UsingLoc,
12528                                            SourceLocation EnumLoc,
12529                                            SourceLocation NameLoc,
12530                                            EnumDecl *ED) {
12531   bool Invalid = false;
12532 
12533   if (CurContext->getRedeclContext()->isRecord()) {
12534     /// In class scope, check if this is a duplicate, for better a diagnostic.
12535     DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12536     LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12537                           ForVisibleRedeclaration);
12538 
12539     LookupName(Previous, S);
12540 
12541     for (NamedDecl *D : Previous)
12542       if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12543         if (UED->getEnumDecl() == ED) {
12544           Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12545               << SourceRange(EnumLoc, NameLoc);
12546           Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12547           Invalid = true;
12548           break;
12549         }
12550   }
12551 
12552   if (RequireCompleteEnumDecl(ED, NameLoc))
12553     Invalid = true;
12554 
12555   UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12556                                             EnumLoc, NameLoc, ED);
12557   UD->setAccess(AS);
12558   CurContext->addDecl(UD);
12559 
12560   if (Invalid) {
12561     UD->setInvalidDecl();
12562     return UD;
12563   }
12564 
12565   // Create the shadow decls for each enumerator
12566   for (EnumConstantDecl *EC : ED->enumerators()) {
12567     UsingShadowDecl *PrevDecl = nullptr;
12568     DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12569     LookupResult Previous(*this, DNI, LookupOrdinaryName,
12570                           ForVisibleRedeclaration);
12571     LookupName(Previous, S);
12572     FilterUsingLookup(S, Previous);
12573 
12574     if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12575       BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12576   }
12577 
12578   return UD;
12579 }
12580 
12581 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12582                                     ArrayRef<NamedDecl *> Expansions) {
12583   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12584          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12585          isa<UsingPackDecl>(InstantiatedFrom));
12586 
12587   auto *UPD =
12588       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12589   UPD->setAccess(InstantiatedFrom->getAccess());
12590   CurContext->addDecl(UPD);
12591   return UPD;
12592 }
12593 
12594 /// Additional checks for a using declaration referring to a constructor name.
12595 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12596   assert(!UD->hasTypename() && "expecting a constructor name");
12597 
12598   const Type *SourceType = UD->getQualifier()->getAsType();
12599   assert(SourceType &&
12600          "Using decl naming constructor doesn't have type in scope spec.");
12601   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12602 
12603   // Check whether the named type is a direct base class.
12604   bool AnyDependentBases = false;
12605   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12606                                       AnyDependentBases);
12607   if (!Base && !AnyDependentBases) {
12608     Diag(UD->getUsingLoc(),
12609          diag::err_using_decl_constructor_not_in_direct_base)
12610       << UD->getNameInfo().getSourceRange()
12611       << QualType(SourceType, 0) << TargetClass;
12612     UD->setInvalidDecl();
12613     return true;
12614   }
12615 
12616   if (Base)
12617     Base->setInheritConstructors();
12618 
12619   return false;
12620 }
12621 
12622 /// Checks that the given using declaration is not an invalid
12623 /// redeclaration.  Note that this is checking only for the using decl
12624 /// itself, not for any ill-formedness among the UsingShadowDecls.
12625 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12626                                        bool HasTypenameKeyword,
12627                                        const CXXScopeSpec &SS,
12628                                        SourceLocation NameLoc,
12629                                        const LookupResult &Prev) {
12630   NestedNameSpecifier *Qual = SS.getScopeRep();
12631 
12632   // C++03 [namespace.udecl]p8:
12633   // C++0x [namespace.udecl]p10:
12634   //   A using-declaration is a declaration and can therefore be used
12635   //   repeatedly where (and only where) multiple declarations are
12636   //   allowed.
12637   //
12638   // That's in non-member contexts.
12639   if (!CurContext->getRedeclContext()->isRecord()) {
12640     // A dependent qualifier outside a class can only ever resolve to an
12641     // enumeration type. Therefore it conflicts with any other non-type
12642     // declaration in the same scope.
12643     // FIXME: How should we check for dependent type-type conflicts at block
12644     // scope?
12645     if (Qual->isDependent() && !HasTypenameKeyword) {
12646       for (auto *D : Prev) {
12647         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12648           bool OldCouldBeEnumerator =
12649               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12650           Diag(NameLoc,
12651                OldCouldBeEnumerator ? diag::err_redefinition
12652                                     : diag::err_redefinition_different_kind)
12653               << Prev.getLookupName();
12654           Diag(D->getLocation(), diag::note_previous_definition);
12655           return true;
12656         }
12657       }
12658     }
12659     return false;
12660   }
12661 
12662   const NestedNameSpecifier *CNNS =
12663       Context.getCanonicalNestedNameSpecifier(Qual);
12664   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12665     NamedDecl *D = *I;
12666 
12667     bool DTypename;
12668     NestedNameSpecifier *DQual;
12669     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12670       DTypename = UD->hasTypename();
12671       DQual = UD->getQualifier();
12672     } else if (UnresolvedUsingValueDecl *UD
12673                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12674       DTypename = false;
12675       DQual = UD->getQualifier();
12676     } else if (UnresolvedUsingTypenameDecl *UD
12677                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12678       DTypename = true;
12679       DQual = UD->getQualifier();
12680     } else continue;
12681 
12682     // using decls differ if one says 'typename' and the other doesn't.
12683     // FIXME: non-dependent using decls?
12684     if (HasTypenameKeyword != DTypename) continue;
12685 
12686     // using decls differ if they name different scopes (but note that
12687     // template instantiation can cause this check to trigger when it
12688     // didn't before instantiation).
12689     if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12690       continue;
12691 
12692     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12693     Diag(D->getLocation(), diag::note_using_decl) << 1;
12694     return true;
12695   }
12696 
12697   return false;
12698 }
12699 
12700 /// Checks that the given nested-name qualifier used in a using decl
12701 /// in the current context is appropriately related to the current
12702 /// scope.  If an error is found, diagnoses it and returns true.
12703 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12704 /// result of that lookup. UD is likewise nullptr, except when we have an
12705 /// already-populated UsingDecl whose shadow decls contain the same information
12706 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12707 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12708                                    const CXXScopeSpec &SS,
12709                                    const DeclarationNameInfo &NameInfo,
12710                                    SourceLocation NameLoc,
12711                                    const LookupResult *R, const UsingDecl *UD) {
12712   DeclContext *NamedContext = computeDeclContext(SS);
12713   assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
12714          "resolvable context must have exactly one set of decls");
12715 
12716   // C++ 20 permits using an enumerator that does not have a class-hierarchy
12717   // relationship.
12718   bool Cxx20Enumerator = false;
12719   if (NamedContext) {
12720     EnumConstantDecl *EC = nullptr;
12721     if (R)
12722       EC = R->getAsSingle<EnumConstantDecl>();
12723     else if (UD && UD->shadow_size() == 1)
12724       EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12725     if (EC)
12726       Cxx20Enumerator = getLangOpts().CPlusPlus20;
12727 
12728     if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12729       // C++14 [namespace.udecl]p7:
12730       // A using-declaration shall not name a scoped enumerator.
12731       // C++20 p1099 permits enumerators.
12732       if (EC && R && ED->isScoped())
12733         Diag(SS.getBeginLoc(),
12734              getLangOpts().CPlusPlus20
12735                  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12736                  : diag::ext_using_decl_scoped_enumerator)
12737             << SS.getRange();
12738 
12739       // We want to consider the scope of the enumerator
12740       NamedContext = ED->getDeclContext();
12741     }
12742   }
12743 
12744   if (!CurContext->isRecord()) {
12745     // C++03 [namespace.udecl]p3:
12746     // C++0x [namespace.udecl]p8:
12747     //   A using-declaration for a class member shall be a member-declaration.
12748     // C++20 [namespace.udecl]p7
12749     //   ... other than an enumerator ...
12750 
12751     // If we weren't able to compute a valid scope, it might validly be a
12752     // dependent class or enumeration scope. If we have a 'typename' keyword,
12753     // the scope must resolve to a class type.
12754     if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12755                      : !HasTypename)
12756       return false; // OK
12757 
12758     Diag(NameLoc,
12759          Cxx20Enumerator
12760              ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12761              : diag::err_using_decl_can_not_refer_to_class_member)
12762         << SS.getRange();
12763 
12764     if (Cxx20Enumerator)
12765       return false; // OK
12766 
12767     auto *RD = NamedContext
12768                    ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12769                    : nullptr;
12770     if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12771       // See if there's a helpful fixit
12772 
12773       if (!R) {
12774         // We will have already diagnosed the problem on the template
12775         // definition,  Maybe we should do so again?
12776       } else if (R->getAsSingle<TypeDecl>()) {
12777         if (getLangOpts().CPlusPlus11) {
12778           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12779           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12780             << 0 // alias declaration
12781             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12782                                           NameInfo.getName().getAsString() +
12783                                               " = ");
12784         } else {
12785           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12786           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12787           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12788             << 1 // typedef declaration
12789             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12790             << FixItHint::CreateInsertion(
12791                    InsertLoc, " " + NameInfo.getName().getAsString());
12792         }
12793       } else if (R->getAsSingle<VarDecl>()) {
12794         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12795         // repeating the type of the static data member here.
12796         FixItHint FixIt;
12797         if (getLangOpts().CPlusPlus11) {
12798           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12799           FixIt = FixItHint::CreateReplacement(
12800               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12801         }
12802 
12803         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12804           << 2 // reference declaration
12805           << FixIt;
12806       } else if (R->getAsSingle<EnumConstantDecl>()) {
12807         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12808         // repeating the type of the enumeration here, and we can't do so if
12809         // the type is anonymous.
12810         FixItHint FixIt;
12811         if (getLangOpts().CPlusPlus11) {
12812           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12813           FixIt = FixItHint::CreateReplacement(
12814               UsingLoc,
12815               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12816         }
12817 
12818         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12819           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12820           << FixIt;
12821       }
12822     }
12823 
12824     return true; // Fail
12825   }
12826 
12827   // If the named context is dependent, we can't decide much.
12828   if (!NamedContext) {
12829     // FIXME: in C++0x, we can diagnose if we can prove that the
12830     // nested-name-specifier does not refer to a base class, which is
12831     // still possible in some cases.
12832 
12833     // Otherwise we have to conservatively report that things might be
12834     // okay.
12835     return false;
12836   }
12837 
12838   // The current scope is a record.
12839   if (!NamedContext->isRecord()) {
12840     // Ideally this would point at the last name in the specifier,
12841     // but we don't have that level of source info.
12842     Diag(SS.getBeginLoc(),
12843          Cxx20Enumerator
12844              ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12845              : diag::err_using_decl_nested_name_specifier_is_not_class)
12846         << SS.getScopeRep() << SS.getRange();
12847 
12848     if (Cxx20Enumerator)
12849       return false; // OK
12850 
12851     return true;
12852   }
12853 
12854   if (!NamedContext->isDependentContext() &&
12855       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12856     return true;
12857 
12858   if (getLangOpts().CPlusPlus11) {
12859     // C++11 [namespace.udecl]p3:
12860     //   In a using-declaration used as a member-declaration, the
12861     //   nested-name-specifier shall name a base class of the class
12862     //   being defined.
12863 
12864     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12865                                  cast<CXXRecordDecl>(NamedContext))) {
12866 
12867       if (Cxx20Enumerator) {
12868         Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12869             << SS.getRange();
12870         return false;
12871       }
12872 
12873       if (CurContext == NamedContext) {
12874         Diag(SS.getBeginLoc(),
12875              diag::err_using_decl_nested_name_specifier_is_current_class)
12876             << SS.getRange();
12877         return !getLangOpts().CPlusPlus20;
12878       }
12879 
12880       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12881         Diag(SS.getBeginLoc(),
12882              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12883             << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12884             << SS.getRange();
12885       }
12886       return true;
12887     }
12888 
12889     return false;
12890   }
12891 
12892   // C++03 [namespace.udecl]p4:
12893   //   A using-declaration used as a member-declaration shall refer
12894   //   to a member of a base class of the class being defined [etc.].
12895 
12896   // Salient point: SS doesn't have to name a base class as long as
12897   // lookup only finds members from base classes.  Therefore we can
12898   // diagnose here only if we can prove that that can't happen,
12899   // i.e. if the class hierarchies provably don't intersect.
12900 
12901   // TODO: it would be nice if "definitely valid" results were cached
12902   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12903   // need to be repeated.
12904 
12905   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12906   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12907     Bases.insert(Base);
12908     return true;
12909   };
12910 
12911   // Collect all bases. Return false if we find a dependent base.
12912   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12913     return false;
12914 
12915   // Returns true if the base is dependent or is one of the accumulated base
12916   // classes.
12917   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12918     return !Bases.count(Base);
12919   };
12920 
12921   // Return false if the class has a dependent base or if it or one
12922   // of its bases is present in the base set of the current context.
12923   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12924       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12925     return false;
12926 
12927   Diag(SS.getRange().getBegin(),
12928        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12929     << SS.getScopeRep()
12930     << cast<CXXRecordDecl>(CurContext)
12931     << SS.getRange();
12932 
12933   return true;
12934 }
12935 
12936 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12937                                   MultiTemplateParamsArg TemplateParamLists,
12938                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12939                                   const ParsedAttributesView &AttrList,
12940                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12941   // Skip up to the relevant declaration scope.
12942   while (S->isTemplateParamScope())
12943     S = S->getParent();
12944   assert((S->getFlags() & Scope::DeclScope) &&
12945          "got alias-declaration outside of declaration scope");
12946 
12947   if (Type.isInvalid())
12948     return nullptr;
12949 
12950   bool Invalid = false;
12951   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12952   TypeSourceInfo *TInfo = nullptr;
12953   GetTypeFromParser(Type.get(), &TInfo);
12954 
12955   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12956     return nullptr;
12957 
12958   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12959                                       UPPC_DeclarationType)) {
12960     Invalid = true;
12961     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12962                                              TInfo->getTypeLoc().getBeginLoc());
12963   }
12964 
12965   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12966                         TemplateParamLists.size()
12967                             ? forRedeclarationInCurContext()
12968                             : ForVisibleRedeclaration);
12969   LookupName(Previous, S);
12970 
12971   // Warn about shadowing the name of a template parameter.
12972   if (Previous.isSingleResult() &&
12973       Previous.getFoundDecl()->isTemplateParameter()) {
12974     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12975     Previous.clear();
12976   }
12977 
12978   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12979          "name in alias declaration must be an identifier");
12980   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12981                                                Name.StartLocation,
12982                                                Name.Identifier, TInfo);
12983 
12984   NewTD->setAccess(AS);
12985 
12986   if (Invalid)
12987     NewTD->setInvalidDecl();
12988 
12989   ProcessDeclAttributeList(S, NewTD, AttrList);
12990   AddPragmaAttributes(S, NewTD);
12991 
12992   CheckTypedefForVariablyModifiedType(S, NewTD);
12993   Invalid |= NewTD->isInvalidDecl();
12994 
12995   bool Redeclaration = false;
12996 
12997   NamedDecl *NewND;
12998   if (TemplateParamLists.size()) {
12999     TypeAliasTemplateDecl *OldDecl = nullptr;
13000     TemplateParameterList *OldTemplateParams = nullptr;
13001 
13002     if (TemplateParamLists.size() != 1) {
13003       Diag(UsingLoc, diag::err_alias_template_extra_headers)
13004         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13005          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13006     }
13007     TemplateParameterList *TemplateParams = TemplateParamLists[0];
13008 
13009     // Check that we can declare a template here.
13010     if (CheckTemplateDeclScope(S, TemplateParams))
13011       return nullptr;
13012 
13013     // Only consider previous declarations in the same scope.
13014     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13015                          /*ExplicitInstantiationOrSpecialization*/false);
13016     if (!Previous.empty()) {
13017       Redeclaration = true;
13018 
13019       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13020       if (!OldDecl && !Invalid) {
13021         Diag(UsingLoc, diag::err_redefinition_different_kind)
13022           << Name.Identifier;
13023 
13024         NamedDecl *OldD = Previous.getRepresentativeDecl();
13025         if (OldD->getLocation().isValid())
13026           Diag(OldD->getLocation(), diag::note_previous_definition);
13027 
13028         Invalid = true;
13029       }
13030 
13031       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13032         if (TemplateParameterListsAreEqual(TemplateParams,
13033                                            OldDecl->getTemplateParameters(),
13034                                            /*Complain=*/true,
13035                                            TPL_TemplateMatch))
13036           OldTemplateParams =
13037               OldDecl->getMostRecentDecl()->getTemplateParameters();
13038         else
13039           Invalid = true;
13040 
13041         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13042         if (!Invalid &&
13043             !Context.hasSameType(OldTD->getUnderlyingType(),
13044                                  NewTD->getUnderlyingType())) {
13045           // FIXME: The C++0x standard does not clearly say this is ill-formed,
13046           // but we can't reasonably accept it.
13047           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13048             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13049           if (OldTD->getLocation().isValid())
13050             Diag(OldTD->getLocation(), diag::note_previous_definition);
13051           Invalid = true;
13052         }
13053       }
13054     }
13055 
13056     // Merge any previous default template arguments into our parameters,
13057     // and check the parameter list.
13058     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13059                                    TPC_TypeAliasTemplate))
13060       return nullptr;
13061 
13062     TypeAliasTemplateDecl *NewDecl =
13063       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13064                                     Name.Identifier, TemplateParams,
13065                                     NewTD);
13066     NewTD->setDescribedAliasTemplate(NewDecl);
13067 
13068     NewDecl->setAccess(AS);
13069 
13070     if (Invalid)
13071       NewDecl->setInvalidDecl();
13072     else if (OldDecl) {
13073       NewDecl->setPreviousDecl(OldDecl);
13074       CheckRedeclarationInModule(NewDecl, OldDecl);
13075     }
13076 
13077     NewND = NewDecl;
13078   } else {
13079     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13080       setTagNameForLinkagePurposes(TD, NewTD);
13081       handleTagNumbering(TD, S);
13082     }
13083     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13084     NewND = NewTD;
13085   }
13086 
13087   PushOnScopeChains(NewND, S);
13088   ActOnDocumentableDecl(NewND);
13089   return NewND;
13090 }
13091 
13092 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13093                                    SourceLocation AliasLoc,
13094                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
13095                                    SourceLocation IdentLoc,
13096                                    IdentifierInfo *Ident) {
13097 
13098   // Lookup the namespace name.
13099   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13100   LookupParsedName(R, S, &SS);
13101 
13102   if (R.isAmbiguous())
13103     return nullptr;
13104 
13105   if (R.empty()) {
13106     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13107       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13108       return nullptr;
13109     }
13110   }
13111   assert(!R.isAmbiguous() && !R.empty());
13112   NamedDecl *ND = R.getRepresentativeDecl();
13113 
13114   // Check if we have a previous declaration with the same name.
13115   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13116                      ForVisibleRedeclaration);
13117   LookupName(PrevR, S);
13118 
13119   // Check we're not shadowing a template parameter.
13120   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13121     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13122     PrevR.clear();
13123   }
13124 
13125   // Filter out any other lookup result from an enclosing scope.
13126   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13127                        /*AllowInlineNamespace*/false);
13128 
13129   // Find the previous declaration and check that we can redeclare it.
13130   NamespaceAliasDecl *Prev = nullptr;
13131   if (PrevR.isSingleResult()) {
13132     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13133     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13134       // We already have an alias with the same name that points to the same
13135       // namespace; check that it matches.
13136       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13137         Prev = AD;
13138       } else if (isVisible(PrevDecl)) {
13139         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13140           << Alias;
13141         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13142           << AD->getNamespace();
13143         return nullptr;
13144       }
13145     } else if (isVisible(PrevDecl)) {
13146       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13147                             ? diag::err_redefinition
13148                             : diag::err_redefinition_different_kind;
13149       Diag(AliasLoc, DiagID) << Alias;
13150       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13151       return nullptr;
13152     }
13153   }
13154 
13155   // The use of a nested name specifier may trigger deprecation warnings.
13156   DiagnoseUseOfDecl(ND, IdentLoc);
13157 
13158   NamespaceAliasDecl *AliasDecl =
13159     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13160                                Alias, SS.getWithLocInContext(Context),
13161                                IdentLoc, ND);
13162   if (Prev)
13163     AliasDecl->setPreviousDecl(Prev);
13164 
13165   PushOnScopeChains(AliasDecl, S);
13166   return AliasDecl;
13167 }
13168 
13169 namespace {
13170 struct SpecialMemberExceptionSpecInfo
13171     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13172   SourceLocation Loc;
13173   Sema::ImplicitExceptionSpecification ExceptSpec;
13174 
13175   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13176                                  Sema::CXXSpecialMember CSM,
13177                                  Sema::InheritedConstructorInfo *ICI,
13178                                  SourceLocation Loc)
13179       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13180 
13181   bool visitBase(CXXBaseSpecifier *Base);
13182   bool visitField(FieldDecl *FD);
13183 
13184   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13185                            unsigned Quals);
13186 
13187   void visitSubobjectCall(Subobject Subobj,
13188                           Sema::SpecialMemberOverloadResult SMOR);
13189 };
13190 }
13191 
13192 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13193   auto *RT = Base->getType()->getAs<RecordType>();
13194   if (!RT)
13195     return false;
13196 
13197   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13198   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13199   if (auto *BaseCtor = SMOR.getMethod()) {
13200     visitSubobjectCall(Base, BaseCtor);
13201     return false;
13202   }
13203 
13204   visitClassSubobject(BaseClass, Base, 0);
13205   return false;
13206 }
13207 
13208 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13209   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13210     Expr *E = FD->getInClassInitializer();
13211     if (!E)
13212       // FIXME: It's a little wasteful to build and throw away a
13213       // CXXDefaultInitExpr here.
13214       // FIXME: We should have a single context note pointing at Loc, and
13215       // this location should be MD->getLocation() instead, since that's
13216       // the location where we actually use the default init expression.
13217       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13218     if (E)
13219       ExceptSpec.CalledExpr(E);
13220   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13221                             ->getAs<RecordType>()) {
13222     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13223                         FD->getType().getCVRQualifiers());
13224   }
13225   return false;
13226 }
13227 
13228 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13229                                                          Subobject Subobj,
13230                                                          unsigned Quals) {
13231   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13232   bool IsMutable = Field && Field->isMutable();
13233   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13234 }
13235 
13236 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13237     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13238   // Note, if lookup fails, it doesn't matter what exception specification we
13239   // choose because the special member will be deleted.
13240   if (CXXMethodDecl *MD = SMOR.getMethod())
13241     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13242 }
13243 
13244 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13245   llvm::APSInt Result;
13246   ExprResult Converted = CheckConvertedConstantExpression(
13247       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13248   ExplicitSpec.setExpr(Converted.get());
13249   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13250     ExplicitSpec.setKind(Result.getBoolValue()
13251                              ? ExplicitSpecKind::ResolvedTrue
13252                              : ExplicitSpecKind::ResolvedFalse);
13253     return true;
13254   }
13255   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13256   return false;
13257 }
13258 
13259 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13260   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13261   if (!ExplicitExpr->isTypeDependent())
13262     tryResolveExplicitSpecifier(ES);
13263   return ES;
13264 }
13265 
13266 static Sema::ImplicitExceptionSpecification
13267 ComputeDefaultedSpecialMemberExceptionSpec(
13268     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13269     Sema::InheritedConstructorInfo *ICI) {
13270   ComputingExceptionSpec CES(S, MD, Loc);
13271 
13272   CXXRecordDecl *ClassDecl = MD->getParent();
13273 
13274   // C++ [except.spec]p14:
13275   //   An implicitly declared special member function (Clause 12) shall have an
13276   //   exception-specification. [...]
13277   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13278   if (ClassDecl->isInvalidDecl())
13279     return Info.ExceptSpec;
13280 
13281   // FIXME: If this diagnostic fires, we're probably missing a check for
13282   // attempting to resolve an exception specification before it's known
13283   // at a higher level.
13284   if (S.RequireCompleteType(MD->getLocation(),
13285                             S.Context.getRecordType(ClassDecl),
13286                             diag::err_exception_spec_incomplete_type))
13287     return Info.ExceptSpec;
13288 
13289   // C++1z [except.spec]p7:
13290   //   [Look for exceptions thrown by] a constructor selected [...] to
13291   //   initialize a potentially constructed subobject,
13292   // C++1z [except.spec]p8:
13293   //   The exception specification for an implicitly-declared destructor, or a
13294   //   destructor without a noexcept-specifier, is potentially-throwing if and
13295   //   only if any of the destructors for any of its potentially constructed
13296   //   subojects is potentially throwing.
13297   // FIXME: We respect the first rule but ignore the "potentially constructed"
13298   // in the second rule to resolve a core issue (no number yet) that would have
13299   // us reject:
13300   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13301   //   struct B : A {};
13302   //   struct C : B { void f(); };
13303   // ... due to giving B::~B() a non-throwing exception specification.
13304   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13305                                 : Info.VisitAllBases);
13306 
13307   return Info.ExceptSpec;
13308 }
13309 
13310 namespace {
13311 /// RAII object to register a special member as being currently declared.
13312 struct DeclaringSpecialMember {
13313   Sema &S;
13314   Sema::SpecialMemberDecl D;
13315   Sema::ContextRAII SavedContext;
13316   bool WasAlreadyBeingDeclared;
13317 
13318   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13319       : S(S), D(RD, CSM), SavedContext(S, RD) {
13320     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13321     if (WasAlreadyBeingDeclared)
13322       // This almost never happens, but if it does, ensure that our cache
13323       // doesn't contain a stale result.
13324       S.SpecialMemberCache.clear();
13325     else {
13326       // Register a note to be produced if we encounter an error while
13327       // declaring the special member.
13328       Sema::CodeSynthesisContext Ctx;
13329       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13330       // FIXME: We don't have a location to use here. Using the class's
13331       // location maintains the fiction that we declare all special members
13332       // with the class, but (1) it's not clear that lying about that helps our
13333       // users understand what's going on, and (2) there may be outer contexts
13334       // on the stack (some of which are relevant) and printing them exposes
13335       // our lies.
13336       Ctx.PointOfInstantiation = RD->getLocation();
13337       Ctx.Entity = RD;
13338       Ctx.SpecialMember = CSM;
13339       S.pushCodeSynthesisContext(Ctx);
13340     }
13341   }
13342   ~DeclaringSpecialMember() {
13343     if (!WasAlreadyBeingDeclared) {
13344       S.SpecialMembersBeingDeclared.erase(D);
13345       S.popCodeSynthesisContext();
13346     }
13347   }
13348 
13349   /// Are we already trying to declare this special member?
13350   bool isAlreadyBeingDeclared() const {
13351     return WasAlreadyBeingDeclared;
13352   }
13353 };
13354 }
13355 
13356 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13357   // Look up any existing declarations, but don't trigger declaration of all
13358   // implicit special members with this name.
13359   DeclarationName Name = FD->getDeclName();
13360   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13361                  ForExternalRedeclaration);
13362   for (auto *D : FD->getParent()->lookup(Name))
13363     if (auto *Acceptable = R.getAcceptableDecl(D))
13364       R.addDecl(Acceptable);
13365   R.resolveKind();
13366   R.suppressDiagnostics();
13367 
13368   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13369                            FD->isThisDeclarationADefinition());
13370 }
13371 
13372 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13373                                           QualType ResultTy,
13374                                           ArrayRef<QualType> Args) {
13375   // Build an exception specification pointing back at this constructor.
13376   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13377 
13378   LangAS AS = getDefaultCXXMethodAddrSpace();
13379   if (AS != LangAS::Default) {
13380     EPI.TypeQuals.addAddressSpace(AS);
13381   }
13382 
13383   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13384   SpecialMem->setType(QT);
13385 
13386   // During template instantiation of implicit special member functions we need
13387   // a reliable TypeSourceInfo for the function prototype in order to allow
13388   // functions to be substituted.
13389   if (inTemplateInstantiation() &&
13390       cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13391     TypeSourceInfo *TSI =
13392         Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13393     SpecialMem->setTypeSourceInfo(TSI);
13394   }
13395 }
13396 
13397 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13398                                                      CXXRecordDecl *ClassDecl) {
13399   // C++ [class.ctor]p5:
13400   //   A default constructor for a class X is a constructor of class X
13401   //   that can be called without an argument. If there is no
13402   //   user-declared constructor for class X, a default constructor is
13403   //   implicitly declared. An implicitly-declared default constructor
13404   //   is an inline public member of its class.
13405   assert(ClassDecl->needsImplicitDefaultConstructor() &&
13406          "Should not build implicit default constructor!");
13407 
13408   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13409   if (DSM.isAlreadyBeingDeclared())
13410     return nullptr;
13411 
13412   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13413                                                      CXXDefaultConstructor,
13414                                                      false);
13415 
13416   // Create the actual constructor declaration.
13417   CanQualType ClassType
13418     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13419   SourceLocation ClassLoc = ClassDecl->getLocation();
13420   DeclarationName Name
13421     = Context.DeclarationNames.getCXXConstructorName(ClassType);
13422   DeclarationNameInfo NameInfo(Name, ClassLoc);
13423   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13424       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13425       /*TInfo=*/nullptr, ExplicitSpecifier(),
13426       getCurFPFeatures().isFPConstrained(),
13427       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13428       Constexpr ? ConstexprSpecKind::Constexpr
13429                 : ConstexprSpecKind::Unspecified);
13430   DefaultCon->setAccess(AS_public);
13431   DefaultCon->setDefaulted();
13432 
13433   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13434 
13435   if (getLangOpts().CUDA)
13436     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13437                                             DefaultCon,
13438                                             /* ConstRHS */ false,
13439                                             /* Diagnose */ false);
13440 
13441   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13442   // constructors is easy to compute.
13443   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13444 
13445   // Note that we have declared this constructor.
13446   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13447 
13448   Scope *S = getScopeForContext(ClassDecl);
13449   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13450 
13451   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13452     SetDeclDeleted(DefaultCon, ClassLoc);
13453 
13454   if (S)
13455     PushOnScopeChains(DefaultCon, S, false);
13456   ClassDecl->addDecl(DefaultCon);
13457 
13458   return DefaultCon;
13459 }
13460 
13461 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13462                                             CXXConstructorDecl *Constructor) {
13463   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13464           !Constructor->doesThisDeclarationHaveABody() &&
13465           !Constructor->isDeleted()) &&
13466     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13467   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13468     return;
13469 
13470   CXXRecordDecl *ClassDecl = Constructor->getParent();
13471   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13472 
13473   SynthesizedFunctionScope Scope(*this, Constructor);
13474 
13475   // The exception specification is needed because we are defining the
13476   // function.
13477   ResolveExceptionSpec(CurrentLocation,
13478                        Constructor->getType()->castAs<FunctionProtoType>());
13479   MarkVTableUsed(CurrentLocation, ClassDecl);
13480 
13481   // Add a context note for diagnostics produced after this point.
13482   Scope.addContextNote(CurrentLocation);
13483 
13484   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13485     Constructor->setInvalidDecl();
13486     return;
13487   }
13488 
13489   SourceLocation Loc = Constructor->getEndLoc().isValid()
13490                            ? Constructor->getEndLoc()
13491                            : Constructor->getLocation();
13492   Constructor->setBody(new (Context) CompoundStmt(Loc));
13493   Constructor->markUsed(Context);
13494 
13495   if (ASTMutationListener *L = getASTMutationListener()) {
13496     L->CompletedImplicitDefinition(Constructor);
13497   }
13498 
13499   DiagnoseUninitializedFields(*this, Constructor);
13500 }
13501 
13502 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13503   // Perform any delayed checks on exception specifications.
13504   CheckDelayedMemberExceptionSpecs();
13505 }
13506 
13507 /// Find or create the fake constructor we synthesize to model constructing an
13508 /// object of a derived class via a constructor of a base class.
13509 CXXConstructorDecl *
13510 Sema::findInheritingConstructor(SourceLocation Loc,
13511                                 CXXConstructorDecl *BaseCtor,
13512                                 ConstructorUsingShadowDecl *Shadow) {
13513   CXXRecordDecl *Derived = Shadow->getParent();
13514   SourceLocation UsingLoc = Shadow->getLocation();
13515 
13516   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13517   // For now we use the name of the base class constructor as a member of the
13518   // derived class to indicate a (fake) inherited constructor name.
13519   DeclarationName Name = BaseCtor->getDeclName();
13520 
13521   // Check to see if we already have a fake constructor for this inherited
13522   // constructor call.
13523   for (NamedDecl *Ctor : Derived->lookup(Name))
13524     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13525                                ->getInheritedConstructor()
13526                                .getConstructor(),
13527                            BaseCtor))
13528       return cast<CXXConstructorDecl>(Ctor);
13529 
13530   DeclarationNameInfo NameInfo(Name, UsingLoc);
13531   TypeSourceInfo *TInfo =
13532       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13533   FunctionProtoTypeLoc ProtoLoc =
13534       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13535 
13536   // Check the inherited constructor is valid and find the list of base classes
13537   // from which it was inherited.
13538   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13539 
13540   bool Constexpr =
13541       BaseCtor->isConstexpr() &&
13542       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13543                                         false, BaseCtor, &ICI);
13544 
13545   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13546       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13547       BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13548       /*isInline=*/true,
13549       /*isImplicitlyDeclared=*/true,
13550       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13551       InheritedConstructor(Shadow, BaseCtor),
13552       BaseCtor->getTrailingRequiresClause());
13553   if (Shadow->isInvalidDecl())
13554     DerivedCtor->setInvalidDecl();
13555 
13556   // Build an unevaluated exception specification for this fake constructor.
13557   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13558   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13559   EPI.ExceptionSpec.Type = EST_Unevaluated;
13560   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13561   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13562                                                FPT->getParamTypes(), EPI));
13563 
13564   // Build the parameter declarations.
13565   SmallVector<ParmVarDecl *, 16> ParamDecls;
13566   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13567     TypeSourceInfo *TInfo =
13568         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13569     ParmVarDecl *PD = ParmVarDecl::Create(
13570         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13571         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13572     PD->setScopeInfo(0, I);
13573     PD->setImplicit();
13574     // Ensure attributes are propagated onto parameters (this matters for
13575     // format, pass_object_size, ...).
13576     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13577     ParamDecls.push_back(PD);
13578     ProtoLoc.setParam(I, PD);
13579   }
13580 
13581   // Set up the new constructor.
13582   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13583   DerivedCtor->setAccess(BaseCtor->getAccess());
13584   DerivedCtor->setParams(ParamDecls);
13585   Derived->addDecl(DerivedCtor);
13586 
13587   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13588     SetDeclDeleted(DerivedCtor, UsingLoc);
13589 
13590   return DerivedCtor;
13591 }
13592 
13593 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13594   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13595                                Ctor->getInheritedConstructor().getShadowDecl());
13596   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13597                             /*Diagnose*/true);
13598 }
13599 
13600 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13601                                        CXXConstructorDecl *Constructor) {
13602   CXXRecordDecl *ClassDecl = Constructor->getParent();
13603   assert(Constructor->getInheritedConstructor() &&
13604          !Constructor->doesThisDeclarationHaveABody() &&
13605          !Constructor->isDeleted());
13606   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13607     return;
13608 
13609   // Initializations are performed "as if by a defaulted default constructor",
13610   // so enter the appropriate scope.
13611   SynthesizedFunctionScope Scope(*this, Constructor);
13612 
13613   // The exception specification is needed because we are defining the
13614   // function.
13615   ResolveExceptionSpec(CurrentLocation,
13616                        Constructor->getType()->castAs<FunctionProtoType>());
13617   MarkVTableUsed(CurrentLocation, ClassDecl);
13618 
13619   // Add a context note for diagnostics produced after this point.
13620   Scope.addContextNote(CurrentLocation);
13621 
13622   ConstructorUsingShadowDecl *Shadow =
13623       Constructor->getInheritedConstructor().getShadowDecl();
13624   CXXConstructorDecl *InheritedCtor =
13625       Constructor->getInheritedConstructor().getConstructor();
13626 
13627   // [class.inhctor.init]p1:
13628   //   initialization proceeds as if a defaulted default constructor is used to
13629   //   initialize the D object and each base class subobject from which the
13630   //   constructor was inherited
13631 
13632   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13633   CXXRecordDecl *RD = Shadow->getParent();
13634   SourceLocation InitLoc = Shadow->getLocation();
13635 
13636   // Build explicit initializers for all base classes from which the
13637   // constructor was inherited.
13638   SmallVector<CXXCtorInitializer*, 8> Inits;
13639   for (bool VBase : {false, true}) {
13640     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13641       if (B.isVirtual() != VBase)
13642         continue;
13643 
13644       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13645       if (!BaseRD)
13646         continue;
13647 
13648       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13649       if (!BaseCtor.first)
13650         continue;
13651 
13652       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13653       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13654           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13655 
13656       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13657       Inits.push_back(new (Context) CXXCtorInitializer(
13658           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13659           SourceLocation()));
13660     }
13661   }
13662 
13663   // We now proceed as if for a defaulted default constructor, with the relevant
13664   // initializers replaced.
13665 
13666   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13667     Constructor->setInvalidDecl();
13668     return;
13669   }
13670 
13671   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13672   Constructor->markUsed(Context);
13673 
13674   if (ASTMutationListener *L = getASTMutationListener()) {
13675     L->CompletedImplicitDefinition(Constructor);
13676   }
13677 
13678   DiagnoseUninitializedFields(*this, Constructor);
13679 }
13680 
13681 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13682   // C++ [class.dtor]p2:
13683   //   If a class has no user-declared destructor, a destructor is
13684   //   declared implicitly. An implicitly-declared destructor is an
13685   //   inline public member of its class.
13686   assert(ClassDecl->needsImplicitDestructor());
13687 
13688   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13689   if (DSM.isAlreadyBeingDeclared())
13690     return nullptr;
13691 
13692   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13693                                                      CXXDestructor,
13694                                                      false);
13695 
13696   // Create the actual destructor declaration.
13697   CanQualType ClassType
13698     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13699   SourceLocation ClassLoc = ClassDecl->getLocation();
13700   DeclarationName Name
13701     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13702   DeclarationNameInfo NameInfo(Name, ClassLoc);
13703   CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
13704       Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13705       getCurFPFeatures().isFPConstrained(),
13706       /*isInline=*/true,
13707       /*isImplicitlyDeclared=*/true,
13708       Constexpr ? ConstexprSpecKind::Constexpr
13709                 : ConstexprSpecKind::Unspecified);
13710   Destructor->setAccess(AS_public);
13711   Destructor->setDefaulted();
13712 
13713   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13714 
13715   if (getLangOpts().CUDA)
13716     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13717                                             Destructor,
13718                                             /* ConstRHS */ false,
13719                                             /* Diagnose */ false);
13720 
13721   // We don't need to use SpecialMemberIsTrivial here; triviality for
13722   // destructors is easy to compute.
13723   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13724   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13725                                 ClassDecl->hasTrivialDestructorForCall());
13726 
13727   // Note that we have declared this destructor.
13728   ++getASTContext().NumImplicitDestructorsDeclared;
13729 
13730   Scope *S = getScopeForContext(ClassDecl);
13731   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13732 
13733   // We can't check whether an implicit destructor is deleted before we complete
13734   // the definition of the class, because its validity depends on the alignment
13735   // of the class. We'll check this from ActOnFields once the class is complete.
13736   if (ClassDecl->isCompleteDefinition() &&
13737       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13738     SetDeclDeleted(Destructor, ClassLoc);
13739 
13740   // Introduce this destructor into its scope.
13741   if (S)
13742     PushOnScopeChains(Destructor, S, false);
13743   ClassDecl->addDecl(Destructor);
13744 
13745   return Destructor;
13746 }
13747 
13748 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13749                                     CXXDestructorDecl *Destructor) {
13750   assert((Destructor->isDefaulted() &&
13751           !Destructor->doesThisDeclarationHaveABody() &&
13752           !Destructor->isDeleted()) &&
13753          "DefineImplicitDestructor - call it for implicit default dtor");
13754   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13755     return;
13756 
13757   CXXRecordDecl *ClassDecl = Destructor->getParent();
13758   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13759 
13760   SynthesizedFunctionScope Scope(*this, Destructor);
13761 
13762   // The exception specification is needed because we are defining the
13763   // function.
13764   ResolveExceptionSpec(CurrentLocation,
13765                        Destructor->getType()->castAs<FunctionProtoType>());
13766   MarkVTableUsed(CurrentLocation, ClassDecl);
13767 
13768   // Add a context note for diagnostics produced after this point.
13769   Scope.addContextNote(CurrentLocation);
13770 
13771   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13772                                          Destructor->getParent());
13773 
13774   if (CheckDestructor(Destructor)) {
13775     Destructor->setInvalidDecl();
13776     return;
13777   }
13778 
13779   SourceLocation Loc = Destructor->getEndLoc().isValid()
13780                            ? Destructor->getEndLoc()
13781                            : Destructor->getLocation();
13782   Destructor->setBody(new (Context) CompoundStmt(Loc));
13783   Destructor->markUsed(Context);
13784 
13785   if (ASTMutationListener *L = getASTMutationListener()) {
13786     L->CompletedImplicitDefinition(Destructor);
13787   }
13788 }
13789 
13790 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13791                                           CXXDestructorDecl *Destructor) {
13792   if (Destructor->isInvalidDecl())
13793     return;
13794 
13795   CXXRecordDecl *ClassDecl = Destructor->getParent();
13796   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13797          "implicit complete dtors unneeded outside MS ABI");
13798   assert(ClassDecl->getNumVBases() > 0 &&
13799          "complete dtor only exists for classes with vbases");
13800 
13801   SynthesizedFunctionScope Scope(*this, Destructor);
13802 
13803   // Add a context note for diagnostics produced after this point.
13804   Scope.addContextNote(CurrentLocation);
13805 
13806   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13807 }
13808 
13809 /// Perform any semantic analysis which needs to be delayed until all
13810 /// pending class member declarations have been parsed.
13811 void Sema::ActOnFinishCXXMemberDecls() {
13812   // If the context is an invalid C++ class, just suppress these checks.
13813   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13814     if (Record->isInvalidDecl()) {
13815       DelayedOverridingExceptionSpecChecks.clear();
13816       DelayedEquivalentExceptionSpecChecks.clear();
13817       return;
13818     }
13819     checkForMultipleExportedDefaultConstructors(*this, Record);
13820   }
13821 }
13822 
13823 void Sema::ActOnFinishCXXNonNestedClass() {
13824   referenceDLLExportedClassMethods();
13825 
13826   if (!DelayedDllExportMemberFunctions.empty()) {
13827     SmallVector<CXXMethodDecl*, 4> WorkList;
13828     std::swap(DelayedDllExportMemberFunctions, WorkList);
13829     for (CXXMethodDecl *M : WorkList) {
13830       DefineDefaultedFunction(*this, M, M->getLocation());
13831 
13832       // Pass the method to the consumer to get emitted. This is not necessary
13833       // for explicit instantiation definitions, as they will get emitted
13834       // anyway.
13835       if (M->getParent()->getTemplateSpecializationKind() !=
13836           TSK_ExplicitInstantiationDefinition)
13837         ActOnFinishInlineFunctionDef(M);
13838     }
13839   }
13840 }
13841 
13842 void Sema::referenceDLLExportedClassMethods() {
13843   if (!DelayedDllExportClasses.empty()) {
13844     // Calling ReferenceDllExportedMembers might cause the current function to
13845     // be called again, so use a local copy of DelayedDllExportClasses.
13846     SmallVector<CXXRecordDecl *, 4> WorkList;
13847     std::swap(DelayedDllExportClasses, WorkList);
13848     for (CXXRecordDecl *Class : WorkList)
13849       ReferenceDllExportedMembers(*this, Class);
13850   }
13851 }
13852 
13853 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13854   assert(getLangOpts().CPlusPlus11 &&
13855          "adjusting dtor exception specs was introduced in c++11");
13856 
13857   if (Destructor->isDependentContext())
13858     return;
13859 
13860   // C++11 [class.dtor]p3:
13861   //   A declaration of a destructor that does not have an exception-
13862   //   specification is implicitly considered to have the same exception-
13863   //   specification as an implicit declaration.
13864   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13865   if (DtorType->hasExceptionSpec())
13866     return;
13867 
13868   // Replace the destructor's type, building off the existing one. Fortunately,
13869   // the only thing of interest in the destructor type is its extended info.
13870   // The return and arguments are fixed.
13871   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13872   EPI.ExceptionSpec.Type = EST_Unevaluated;
13873   EPI.ExceptionSpec.SourceDecl = Destructor;
13874   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13875 
13876   // FIXME: If the destructor has a body that could throw, and the newly created
13877   // spec doesn't allow exceptions, we should emit a warning, because this
13878   // change in behavior can break conforming C++03 programs at runtime.
13879   // However, we don't have a body or an exception specification yet, so it
13880   // needs to be done somewhere else.
13881 }
13882 
13883 namespace {
13884 /// An abstract base class for all helper classes used in building the
13885 //  copy/move operators. These classes serve as factory functions and help us
13886 //  avoid using the same Expr* in the AST twice.
13887 class ExprBuilder {
13888   ExprBuilder(const ExprBuilder&) = delete;
13889   ExprBuilder &operator=(const ExprBuilder&) = delete;
13890 
13891 protected:
13892   static Expr *assertNotNull(Expr *E) {
13893     assert(E && "Expression construction must not fail.");
13894     return E;
13895   }
13896 
13897 public:
13898   ExprBuilder() {}
13899   virtual ~ExprBuilder() {}
13900 
13901   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13902 };
13903 
13904 class RefBuilder: public ExprBuilder {
13905   VarDecl *Var;
13906   QualType VarType;
13907 
13908 public:
13909   Expr *build(Sema &S, SourceLocation Loc) const override {
13910     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13911   }
13912 
13913   RefBuilder(VarDecl *Var, QualType VarType)
13914       : Var(Var), VarType(VarType) {}
13915 };
13916 
13917 class ThisBuilder: public ExprBuilder {
13918 public:
13919   Expr *build(Sema &S, SourceLocation Loc) const override {
13920     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13921   }
13922 };
13923 
13924 class CastBuilder: public ExprBuilder {
13925   const ExprBuilder &Builder;
13926   QualType Type;
13927   ExprValueKind Kind;
13928   const CXXCastPath &Path;
13929 
13930 public:
13931   Expr *build(Sema &S, SourceLocation Loc) const override {
13932     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13933                                              CK_UncheckedDerivedToBase, Kind,
13934                                              &Path).get());
13935   }
13936 
13937   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13938               const CXXCastPath &Path)
13939       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13940 };
13941 
13942 class DerefBuilder: public ExprBuilder {
13943   const ExprBuilder &Builder;
13944 
13945 public:
13946   Expr *build(Sema &S, SourceLocation Loc) const override {
13947     return assertNotNull(
13948         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13949   }
13950 
13951   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13952 };
13953 
13954 class MemberBuilder: public ExprBuilder {
13955   const ExprBuilder &Builder;
13956   QualType Type;
13957   CXXScopeSpec SS;
13958   bool IsArrow;
13959   LookupResult &MemberLookup;
13960 
13961 public:
13962   Expr *build(Sema &S, SourceLocation Loc) const override {
13963     return assertNotNull(S.BuildMemberReferenceExpr(
13964         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13965         nullptr, MemberLookup, nullptr, nullptr).get());
13966   }
13967 
13968   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13969                 LookupResult &MemberLookup)
13970       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13971         MemberLookup(MemberLookup) {}
13972 };
13973 
13974 class MoveCastBuilder: public ExprBuilder {
13975   const ExprBuilder &Builder;
13976 
13977 public:
13978   Expr *build(Sema &S, SourceLocation Loc) const override {
13979     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13980   }
13981 
13982   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13983 };
13984 
13985 class LvalueConvBuilder: public ExprBuilder {
13986   const ExprBuilder &Builder;
13987 
13988 public:
13989   Expr *build(Sema &S, SourceLocation Loc) const override {
13990     return assertNotNull(
13991         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13992   }
13993 
13994   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13995 };
13996 
13997 class SubscriptBuilder: public ExprBuilder {
13998   const ExprBuilder &Base;
13999   const ExprBuilder &Index;
14000 
14001 public:
14002   Expr *build(Sema &S, SourceLocation Loc) const override {
14003     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14004         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14005   }
14006 
14007   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14008       : Base(Base), Index(Index) {}
14009 };
14010 
14011 } // end anonymous namespace
14012 
14013 /// When generating a defaulted copy or move assignment operator, if a field
14014 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14015 /// do so. This optimization only applies for arrays of scalars, and for arrays
14016 /// of class type where the selected copy/move-assignment operator is trivial.
14017 static StmtResult
14018 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14019                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
14020   // Compute the size of the memory buffer to be copied.
14021   QualType SizeType = S.Context.getSizeType();
14022   llvm::APInt Size(S.Context.getTypeSize(SizeType),
14023                    S.Context.getTypeSizeInChars(T).getQuantity());
14024 
14025   // Take the address of the field references for "from" and "to". We
14026   // directly construct UnaryOperators here because semantic analysis
14027   // does not permit us to take the address of an xvalue.
14028   Expr *From = FromB.build(S, Loc);
14029   From = UnaryOperator::Create(
14030       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14031       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14032   Expr *To = ToB.build(S, Loc);
14033   To = UnaryOperator::Create(
14034       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14035       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14036 
14037   const Type *E = T->getBaseElementTypeUnsafe();
14038   bool NeedsCollectableMemCpy =
14039       E->isRecordType() &&
14040       E->castAs<RecordType>()->getDecl()->hasObjectMember();
14041 
14042   // Create a reference to the __builtin_objc_memmove_collectable function
14043   StringRef MemCpyName = NeedsCollectableMemCpy ?
14044     "__builtin_objc_memmove_collectable" :
14045     "__builtin_memcpy";
14046   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14047                  Sema::LookupOrdinaryName);
14048   S.LookupName(R, S.TUScope, true);
14049 
14050   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14051   if (!MemCpy)
14052     // Something went horribly wrong earlier, and we will have complained
14053     // about it.
14054     return StmtError();
14055 
14056   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14057                                             VK_PRValue, Loc, nullptr);
14058   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14059 
14060   Expr *CallArgs[] = {
14061     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14062   };
14063   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14064                                     Loc, CallArgs, Loc);
14065 
14066   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14067   return Call.getAs<Stmt>();
14068 }
14069 
14070 /// Builds a statement that copies/moves the given entity from \p From to
14071 /// \c To.
14072 ///
14073 /// This routine is used to copy/move the members of a class with an
14074 /// implicitly-declared copy/move assignment operator. When the entities being
14075 /// copied are arrays, this routine builds for loops to copy them.
14076 ///
14077 /// \param S The Sema object used for type-checking.
14078 ///
14079 /// \param Loc The location where the implicit copy/move is being generated.
14080 ///
14081 /// \param T The type of the expressions being copied/moved. Both expressions
14082 /// must have this type.
14083 ///
14084 /// \param To The expression we are copying/moving to.
14085 ///
14086 /// \param From The expression we are copying/moving from.
14087 ///
14088 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14089 /// Otherwise, it's a non-static member subobject.
14090 ///
14091 /// \param Copying Whether we're copying or moving.
14092 ///
14093 /// \param Depth Internal parameter recording the depth of the recursion.
14094 ///
14095 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14096 /// if a memcpy should be used instead.
14097 static StmtResult
14098 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14099                                  const ExprBuilder &To, const ExprBuilder &From,
14100                                  bool CopyingBaseSubobject, bool Copying,
14101                                  unsigned Depth = 0) {
14102   // C++11 [class.copy]p28:
14103   //   Each subobject is assigned in the manner appropriate to its type:
14104   //
14105   //     - if the subobject is of class type, as if by a call to operator= with
14106   //       the subobject as the object expression and the corresponding
14107   //       subobject of x as a single function argument (as if by explicit
14108   //       qualification; that is, ignoring any possible virtual overriding
14109   //       functions in more derived classes);
14110   //
14111   // C++03 [class.copy]p13:
14112   //     - if the subobject is of class type, the copy assignment operator for
14113   //       the class is used (as if by explicit qualification; that is,
14114   //       ignoring any possible virtual overriding functions in more derived
14115   //       classes);
14116   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14117     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14118 
14119     // Look for operator=.
14120     DeclarationName Name
14121       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14122     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14123     S.LookupQualifiedName(OpLookup, ClassDecl, false);
14124 
14125     // Prior to C++11, filter out any result that isn't a copy/move-assignment
14126     // operator.
14127     if (!S.getLangOpts().CPlusPlus11) {
14128       LookupResult::Filter F = OpLookup.makeFilter();
14129       while (F.hasNext()) {
14130         NamedDecl *D = F.next();
14131         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14132           if (Method->isCopyAssignmentOperator() ||
14133               (!Copying && Method->isMoveAssignmentOperator()))
14134             continue;
14135 
14136         F.erase();
14137       }
14138       F.done();
14139     }
14140 
14141     // Suppress the protected check (C++ [class.protected]) for each of the
14142     // assignment operators we found. This strange dance is required when
14143     // we're assigning via a base classes's copy-assignment operator. To
14144     // ensure that we're getting the right base class subobject (without
14145     // ambiguities), we need to cast "this" to that subobject type; to
14146     // ensure that we don't go through the virtual call mechanism, we need
14147     // to qualify the operator= name with the base class (see below). However,
14148     // this means that if the base class has a protected copy assignment
14149     // operator, the protected member access check will fail. So, we
14150     // rewrite "protected" access to "public" access in this case, since we
14151     // know by construction that we're calling from a derived class.
14152     if (CopyingBaseSubobject) {
14153       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14154            L != LEnd; ++L) {
14155         if (L.getAccess() == AS_protected)
14156           L.setAccess(AS_public);
14157       }
14158     }
14159 
14160     // Create the nested-name-specifier that will be used to qualify the
14161     // reference to operator=; this is required to suppress the virtual
14162     // call mechanism.
14163     CXXScopeSpec SS;
14164     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14165     SS.MakeTrivial(S.Context,
14166                    NestedNameSpecifier::Create(S.Context, nullptr, false,
14167                                                CanonicalT),
14168                    Loc);
14169 
14170     // Create the reference to operator=.
14171     ExprResult OpEqualRef
14172       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14173                                    SS, /*TemplateKWLoc=*/SourceLocation(),
14174                                    /*FirstQualifierInScope=*/nullptr,
14175                                    OpLookup,
14176                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
14177                                    /*SuppressQualifierCheck=*/true);
14178     if (OpEqualRef.isInvalid())
14179       return StmtError();
14180 
14181     // Build the call to the assignment operator.
14182 
14183     Expr *FromInst = From.build(S, Loc);
14184     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14185                                                   OpEqualRef.getAs<Expr>(),
14186                                                   Loc, FromInst, Loc);
14187     if (Call.isInvalid())
14188       return StmtError();
14189 
14190     // If we built a call to a trivial 'operator=' while copying an array,
14191     // bail out. We'll replace the whole shebang with a memcpy.
14192     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14193     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14194       return StmtResult((Stmt*)nullptr);
14195 
14196     // Convert to an expression-statement, and clean up any produced
14197     // temporaries.
14198     return S.ActOnExprStmt(Call);
14199   }
14200 
14201   //     - if the subobject is of scalar type, the built-in assignment
14202   //       operator is used.
14203   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14204   if (!ArrayTy) {
14205     ExprResult Assignment = S.CreateBuiltinBinOp(
14206         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14207     if (Assignment.isInvalid())
14208       return StmtError();
14209     return S.ActOnExprStmt(Assignment);
14210   }
14211 
14212   //     - if the subobject is an array, each element is assigned, in the
14213   //       manner appropriate to the element type;
14214 
14215   // Construct a loop over the array bounds, e.g.,
14216   //
14217   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14218   //
14219   // that will copy each of the array elements.
14220   QualType SizeType = S.Context.getSizeType();
14221 
14222   // Create the iteration variable.
14223   IdentifierInfo *IterationVarName = nullptr;
14224   {
14225     SmallString<8> Str;
14226     llvm::raw_svector_ostream OS(Str);
14227     OS << "__i" << Depth;
14228     IterationVarName = &S.Context.Idents.get(OS.str());
14229   }
14230   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14231                                           IterationVarName, SizeType,
14232                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14233                                           SC_None);
14234 
14235   // Initialize the iteration variable to zero.
14236   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14237   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14238 
14239   // Creates a reference to the iteration variable.
14240   RefBuilder IterationVarRef(IterationVar, SizeType);
14241   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14242 
14243   // Create the DeclStmt that holds the iteration variable.
14244   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14245 
14246   // Subscript the "from" and "to" expressions with the iteration variable.
14247   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14248   MoveCastBuilder FromIndexMove(FromIndexCopy);
14249   const ExprBuilder *FromIndex;
14250   if (Copying)
14251     FromIndex = &FromIndexCopy;
14252   else
14253     FromIndex = &FromIndexMove;
14254 
14255   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14256 
14257   // Build the copy/move for an individual element of the array.
14258   StmtResult Copy =
14259     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14260                                      ToIndex, *FromIndex, CopyingBaseSubobject,
14261                                      Copying, Depth + 1);
14262   // Bail out if copying fails or if we determined that we should use memcpy.
14263   if (Copy.isInvalid() || !Copy.get())
14264     return Copy;
14265 
14266   // Create the comparison against the array bound.
14267   llvm::APInt Upper
14268     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14269   Expr *Comparison = BinaryOperator::Create(
14270       S.Context, IterationVarRefRVal.build(S, Loc),
14271       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14272       S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14273       S.CurFPFeatureOverrides());
14274 
14275   // Create the pre-increment of the iteration variable. We can determine
14276   // whether the increment will overflow based on the value of the array
14277   // bound.
14278   Expr *Increment = UnaryOperator::Create(
14279       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14280       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14281 
14282   // Construct the loop that copies all elements of this array.
14283   return S.ActOnForStmt(
14284       Loc, Loc, InitStmt,
14285       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14286       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14287 }
14288 
14289 static StmtResult
14290 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14291                       const ExprBuilder &To, const ExprBuilder &From,
14292                       bool CopyingBaseSubobject, bool Copying) {
14293   // Maybe we should use a memcpy?
14294   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14295       T.isTriviallyCopyableType(S.Context))
14296     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14297 
14298   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14299                                                      CopyingBaseSubobject,
14300                                                      Copying, 0));
14301 
14302   // If we ended up picking a trivial assignment operator for an array of a
14303   // non-trivially-copyable class type, just emit a memcpy.
14304   if (!Result.isInvalid() && !Result.get())
14305     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14306 
14307   return Result;
14308 }
14309 
14310 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14311   // Note: The following rules are largely analoguous to the copy
14312   // constructor rules. Note that virtual bases are not taken into account
14313   // for determining the argument type of the operator. Note also that
14314   // operators taking an object instead of a reference are allowed.
14315   assert(ClassDecl->needsImplicitCopyAssignment());
14316 
14317   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14318   if (DSM.isAlreadyBeingDeclared())
14319     return nullptr;
14320 
14321   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14322   LangAS AS = getDefaultCXXMethodAddrSpace();
14323   if (AS != LangAS::Default)
14324     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14325   QualType RetType = Context.getLValueReferenceType(ArgType);
14326   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14327   if (Const)
14328     ArgType = ArgType.withConst();
14329 
14330   ArgType = Context.getLValueReferenceType(ArgType);
14331 
14332   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14333                                                      CXXCopyAssignment,
14334                                                      Const);
14335 
14336   //   An implicitly-declared copy assignment operator is an inline public
14337   //   member of its class.
14338   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14339   SourceLocation ClassLoc = ClassDecl->getLocation();
14340   DeclarationNameInfo NameInfo(Name, ClassLoc);
14341   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14342       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14343       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14344       getCurFPFeatures().isFPConstrained(),
14345       /*isInline=*/true,
14346       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14347       SourceLocation());
14348   CopyAssignment->setAccess(AS_public);
14349   CopyAssignment->setDefaulted();
14350   CopyAssignment->setImplicit();
14351 
14352   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14353 
14354   if (getLangOpts().CUDA)
14355     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14356                                             CopyAssignment,
14357                                             /* ConstRHS */ Const,
14358                                             /* Diagnose */ false);
14359 
14360   // Add the parameter to the operator.
14361   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14362                                                ClassLoc, ClassLoc,
14363                                                /*Id=*/nullptr, ArgType,
14364                                                /*TInfo=*/nullptr, SC_None,
14365                                                nullptr);
14366   CopyAssignment->setParams(FromParam);
14367 
14368   CopyAssignment->setTrivial(
14369     ClassDecl->needsOverloadResolutionForCopyAssignment()
14370       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14371       : ClassDecl->hasTrivialCopyAssignment());
14372 
14373   // Note that we have added this copy-assignment operator.
14374   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14375 
14376   Scope *S = getScopeForContext(ClassDecl);
14377   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14378 
14379   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14380     ClassDecl->setImplicitCopyAssignmentIsDeleted();
14381     SetDeclDeleted(CopyAssignment, ClassLoc);
14382   }
14383 
14384   if (S)
14385     PushOnScopeChains(CopyAssignment, S, false);
14386   ClassDecl->addDecl(CopyAssignment);
14387 
14388   return CopyAssignment;
14389 }
14390 
14391 /// Diagnose an implicit copy operation for a class which is odr-used, but
14392 /// which is deprecated because the class has a user-declared copy constructor,
14393 /// copy assignment operator, or destructor.
14394 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14395   assert(CopyOp->isImplicit());
14396 
14397   CXXRecordDecl *RD = CopyOp->getParent();
14398   CXXMethodDecl *UserDeclaredOperation = nullptr;
14399 
14400   // In Microsoft mode, assignment operations don't affect constructors and
14401   // vice versa.
14402   if (RD->hasUserDeclaredDestructor()) {
14403     UserDeclaredOperation = RD->getDestructor();
14404   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14405              RD->hasUserDeclaredCopyConstructor() &&
14406              !S.getLangOpts().MSVCCompat) {
14407     // Find any user-declared copy constructor.
14408     for (auto *I : RD->ctors()) {
14409       if (I->isCopyConstructor()) {
14410         UserDeclaredOperation = I;
14411         break;
14412       }
14413     }
14414     assert(UserDeclaredOperation);
14415   } else if (isa<CXXConstructorDecl>(CopyOp) &&
14416              RD->hasUserDeclaredCopyAssignment() &&
14417              !S.getLangOpts().MSVCCompat) {
14418     // Find any user-declared move assignment operator.
14419     for (auto *I : RD->methods()) {
14420       if (I->isCopyAssignmentOperator()) {
14421         UserDeclaredOperation = I;
14422         break;
14423       }
14424     }
14425     assert(UserDeclaredOperation);
14426   }
14427 
14428   if (UserDeclaredOperation) {
14429     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14430     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14431     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14432     unsigned DiagID =
14433         (UDOIsUserProvided && UDOIsDestructor)
14434             ? diag::warn_deprecated_copy_with_user_provided_dtor
14435         : (UDOIsUserProvided && !UDOIsDestructor)
14436             ? diag::warn_deprecated_copy_with_user_provided_copy
14437         : (!UDOIsUserProvided && UDOIsDestructor)
14438             ? diag::warn_deprecated_copy_with_dtor
14439             : diag::warn_deprecated_copy;
14440     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14441         << RD << IsCopyAssignment;
14442   }
14443 }
14444 
14445 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14446                                         CXXMethodDecl *CopyAssignOperator) {
14447   assert((CopyAssignOperator->isDefaulted() &&
14448           CopyAssignOperator->isOverloadedOperator() &&
14449           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14450           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14451           !CopyAssignOperator->isDeleted()) &&
14452          "DefineImplicitCopyAssignment called for wrong function");
14453   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14454     return;
14455 
14456   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14457   if (ClassDecl->isInvalidDecl()) {
14458     CopyAssignOperator->setInvalidDecl();
14459     return;
14460   }
14461 
14462   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14463 
14464   // The exception specification is needed because we are defining the
14465   // function.
14466   ResolveExceptionSpec(CurrentLocation,
14467                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14468 
14469   // Add a context note for diagnostics produced after this point.
14470   Scope.addContextNote(CurrentLocation);
14471 
14472   // C++11 [class.copy]p18:
14473   //   The [definition of an implicitly declared copy assignment operator] is
14474   //   deprecated if the class has a user-declared copy constructor or a
14475   //   user-declared destructor.
14476   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14477     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14478 
14479   // C++0x [class.copy]p30:
14480   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14481   //   for a non-union class X performs memberwise copy assignment of its
14482   //   subobjects. The direct base classes of X are assigned first, in the
14483   //   order of their declaration in the base-specifier-list, and then the
14484   //   immediate non-static data members of X are assigned, in the order in
14485   //   which they were declared in the class definition.
14486 
14487   // The statements that form the synthesized function body.
14488   SmallVector<Stmt*, 8> Statements;
14489 
14490   // The parameter for the "other" object, which we are copying from.
14491   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14492   Qualifiers OtherQuals = Other->getType().getQualifiers();
14493   QualType OtherRefType = Other->getType();
14494   if (const LValueReferenceType *OtherRef
14495                                 = OtherRefType->getAs<LValueReferenceType>()) {
14496     OtherRefType = OtherRef->getPointeeType();
14497     OtherQuals = OtherRefType.getQualifiers();
14498   }
14499 
14500   // Our location for everything implicitly-generated.
14501   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14502                            ? CopyAssignOperator->getEndLoc()
14503                            : CopyAssignOperator->getLocation();
14504 
14505   // Builds a DeclRefExpr for the "other" object.
14506   RefBuilder OtherRef(Other, OtherRefType);
14507 
14508   // Builds the "this" pointer.
14509   ThisBuilder This;
14510 
14511   // Assign base classes.
14512   bool Invalid = false;
14513   for (auto &Base : ClassDecl->bases()) {
14514     // Form the assignment:
14515     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14516     QualType BaseType = Base.getType().getUnqualifiedType();
14517     if (!BaseType->isRecordType()) {
14518       Invalid = true;
14519       continue;
14520     }
14521 
14522     CXXCastPath BasePath;
14523     BasePath.push_back(&Base);
14524 
14525     // Construct the "from" expression, which is an implicit cast to the
14526     // appropriately-qualified base type.
14527     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14528                      VK_LValue, BasePath);
14529 
14530     // Dereference "this".
14531     DerefBuilder DerefThis(This);
14532     CastBuilder To(DerefThis,
14533                    Context.getQualifiedType(
14534                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14535                    VK_LValue, BasePath);
14536 
14537     // Build the copy.
14538     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14539                                             To, From,
14540                                             /*CopyingBaseSubobject=*/true,
14541                                             /*Copying=*/true);
14542     if (Copy.isInvalid()) {
14543       CopyAssignOperator->setInvalidDecl();
14544       return;
14545     }
14546 
14547     // Success! Record the copy.
14548     Statements.push_back(Copy.getAs<Expr>());
14549   }
14550 
14551   // Assign non-static members.
14552   for (auto *Field : ClassDecl->fields()) {
14553     // FIXME: We should form some kind of AST representation for the implied
14554     // memcpy in a union copy operation.
14555     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14556       continue;
14557 
14558     if (Field->isInvalidDecl()) {
14559       Invalid = true;
14560       continue;
14561     }
14562 
14563     // Check for members of reference type; we can't copy those.
14564     if (Field->getType()->isReferenceType()) {
14565       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14566         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14567       Diag(Field->getLocation(), diag::note_declared_at);
14568       Invalid = true;
14569       continue;
14570     }
14571 
14572     // Check for members of const-qualified, non-class type.
14573     QualType BaseType = Context.getBaseElementType(Field->getType());
14574     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14575       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14576         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14577       Diag(Field->getLocation(), diag::note_declared_at);
14578       Invalid = true;
14579       continue;
14580     }
14581 
14582     // Suppress assigning zero-width bitfields.
14583     if (Field->isZeroLengthBitField(Context))
14584       continue;
14585 
14586     QualType FieldType = Field->getType().getNonReferenceType();
14587     if (FieldType->isIncompleteArrayType()) {
14588       assert(ClassDecl->hasFlexibleArrayMember() &&
14589              "Incomplete array type is not valid");
14590       continue;
14591     }
14592 
14593     // Build references to the field in the object we're copying from and to.
14594     CXXScopeSpec SS; // Intentionally empty
14595     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14596                               LookupMemberName);
14597     MemberLookup.addDecl(Field);
14598     MemberLookup.resolveKind();
14599 
14600     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14601 
14602     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14603 
14604     // Build the copy of this field.
14605     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14606                                             To, From,
14607                                             /*CopyingBaseSubobject=*/false,
14608                                             /*Copying=*/true);
14609     if (Copy.isInvalid()) {
14610       CopyAssignOperator->setInvalidDecl();
14611       return;
14612     }
14613 
14614     // Success! Record the copy.
14615     Statements.push_back(Copy.getAs<Stmt>());
14616   }
14617 
14618   if (!Invalid) {
14619     // Add a "return *this;"
14620     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14621 
14622     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14623     if (Return.isInvalid())
14624       Invalid = true;
14625     else
14626       Statements.push_back(Return.getAs<Stmt>());
14627   }
14628 
14629   if (Invalid) {
14630     CopyAssignOperator->setInvalidDecl();
14631     return;
14632   }
14633 
14634   StmtResult Body;
14635   {
14636     CompoundScopeRAII CompoundScope(*this);
14637     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14638                              /*isStmtExpr=*/false);
14639     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14640   }
14641   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14642   CopyAssignOperator->markUsed(Context);
14643 
14644   if (ASTMutationListener *L = getASTMutationListener()) {
14645     L->CompletedImplicitDefinition(CopyAssignOperator);
14646   }
14647 }
14648 
14649 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14650   assert(ClassDecl->needsImplicitMoveAssignment());
14651 
14652   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14653   if (DSM.isAlreadyBeingDeclared())
14654     return nullptr;
14655 
14656   // Note: The following rules are largely analoguous to the move
14657   // constructor rules.
14658 
14659   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14660   LangAS AS = getDefaultCXXMethodAddrSpace();
14661   if (AS != LangAS::Default)
14662     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14663   QualType RetType = Context.getLValueReferenceType(ArgType);
14664   ArgType = Context.getRValueReferenceType(ArgType);
14665 
14666   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14667                                                      CXXMoveAssignment,
14668                                                      false);
14669 
14670   //   An implicitly-declared move assignment operator is an inline public
14671   //   member of its class.
14672   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14673   SourceLocation ClassLoc = ClassDecl->getLocation();
14674   DeclarationNameInfo NameInfo(Name, ClassLoc);
14675   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14676       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14677       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14678       getCurFPFeatures().isFPConstrained(),
14679       /*isInline=*/true,
14680       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14681       SourceLocation());
14682   MoveAssignment->setAccess(AS_public);
14683   MoveAssignment->setDefaulted();
14684   MoveAssignment->setImplicit();
14685 
14686   setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14687 
14688   if (getLangOpts().CUDA)
14689     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14690                                             MoveAssignment,
14691                                             /* ConstRHS */ false,
14692                                             /* Diagnose */ false);
14693 
14694   // Add the parameter to the operator.
14695   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14696                                                ClassLoc, ClassLoc,
14697                                                /*Id=*/nullptr, ArgType,
14698                                                /*TInfo=*/nullptr, SC_None,
14699                                                nullptr);
14700   MoveAssignment->setParams(FromParam);
14701 
14702   MoveAssignment->setTrivial(
14703     ClassDecl->needsOverloadResolutionForMoveAssignment()
14704       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14705       : ClassDecl->hasTrivialMoveAssignment());
14706 
14707   // Note that we have added this copy-assignment operator.
14708   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14709 
14710   Scope *S = getScopeForContext(ClassDecl);
14711   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14712 
14713   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14714     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14715     SetDeclDeleted(MoveAssignment, ClassLoc);
14716   }
14717 
14718   if (S)
14719     PushOnScopeChains(MoveAssignment, S, false);
14720   ClassDecl->addDecl(MoveAssignment);
14721 
14722   return MoveAssignment;
14723 }
14724 
14725 /// Check if we're implicitly defining a move assignment operator for a class
14726 /// with virtual bases. Such a move assignment might move-assign the virtual
14727 /// base multiple times.
14728 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14729                                                SourceLocation CurrentLocation) {
14730   assert(!Class->isDependentContext() && "should not define dependent move");
14731 
14732   // Only a virtual base could get implicitly move-assigned multiple times.
14733   // Only a non-trivial move assignment can observe this. We only want to
14734   // diagnose if we implicitly define an assignment operator that assigns
14735   // two base classes, both of which move-assign the same virtual base.
14736   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14737       Class->getNumBases() < 2)
14738     return;
14739 
14740   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14741   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14742   VBaseMap VBases;
14743 
14744   for (auto &BI : Class->bases()) {
14745     Worklist.push_back(&BI);
14746     while (!Worklist.empty()) {
14747       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14748       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14749 
14750       // If the base has no non-trivial move assignment operators,
14751       // we don't care about moves from it.
14752       if (!Base->hasNonTrivialMoveAssignment())
14753         continue;
14754 
14755       // If there's nothing virtual here, skip it.
14756       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14757         continue;
14758 
14759       // If we're not actually going to call a move assignment for this base,
14760       // or the selected move assignment is trivial, skip it.
14761       Sema::SpecialMemberOverloadResult SMOR =
14762         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14763                               /*ConstArg*/false, /*VolatileArg*/false,
14764                               /*RValueThis*/true, /*ConstThis*/false,
14765                               /*VolatileThis*/false);
14766       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14767           !SMOR.getMethod()->isMoveAssignmentOperator())
14768         continue;
14769 
14770       if (BaseSpec->isVirtual()) {
14771         // We're going to move-assign this virtual base, and its move
14772         // assignment operator is not trivial. If this can happen for
14773         // multiple distinct direct bases of Class, diagnose it. (If it
14774         // only happens in one base, we'll diagnose it when synthesizing
14775         // that base class's move assignment operator.)
14776         CXXBaseSpecifier *&Existing =
14777             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14778                 .first->second;
14779         if (Existing && Existing != &BI) {
14780           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14781             << Class << Base;
14782           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14783               << (Base->getCanonicalDecl() ==
14784                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14785               << Base << Existing->getType() << Existing->getSourceRange();
14786           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14787               << (Base->getCanonicalDecl() ==
14788                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14789               << Base << BI.getType() << BaseSpec->getSourceRange();
14790 
14791           // Only diagnose each vbase once.
14792           Existing = nullptr;
14793         }
14794       } else {
14795         // Only walk over bases that have defaulted move assignment operators.
14796         // We assume that any user-provided move assignment operator handles
14797         // the multiple-moves-of-vbase case itself somehow.
14798         if (!SMOR.getMethod()->isDefaulted())
14799           continue;
14800 
14801         // We're going to move the base classes of Base. Add them to the list.
14802         llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
14803       }
14804     }
14805   }
14806 }
14807 
14808 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14809                                         CXXMethodDecl *MoveAssignOperator) {
14810   assert((MoveAssignOperator->isDefaulted() &&
14811           MoveAssignOperator->isOverloadedOperator() &&
14812           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14813           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14814           !MoveAssignOperator->isDeleted()) &&
14815          "DefineImplicitMoveAssignment called for wrong function");
14816   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14817     return;
14818 
14819   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14820   if (ClassDecl->isInvalidDecl()) {
14821     MoveAssignOperator->setInvalidDecl();
14822     return;
14823   }
14824 
14825   // C++0x [class.copy]p28:
14826   //   The implicitly-defined or move assignment operator for a non-union class
14827   //   X performs memberwise move assignment of its subobjects. The direct base
14828   //   classes of X are assigned first, in the order of their declaration in the
14829   //   base-specifier-list, and then the immediate non-static data members of X
14830   //   are assigned, in the order in which they were declared in the class
14831   //   definition.
14832 
14833   // Issue a warning if our implicit move assignment operator will move
14834   // from a virtual base more than once.
14835   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14836 
14837   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14838 
14839   // The exception specification is needed because we are defining the
14840   // function.
14841   ResolveExceptionSpec(CurrentLocation,
14842                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14843 
14844   // Add a context note for diagnostics produced after this point.
14845   Scope.addContextNote(CurrentLocation);
14846 
14847   // The statements that form the synthesized function body.
14848   SmallVector<Stmt*, 8> Statements;
14849 
14850   // The parameter for the "other" object, which we are move from.
14851   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14852   QualType OtherRefType =
14853       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14854 
14855   // Our location for everything implicitly-generated.
14856   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14857                            ? MoveAssignOperator->getEndLoc()
14858                            : MoveAssignOperator->getLocation();
14859 
14860   // Builds a reference to the "other" object.
14861   RefBuilder OtherRef(Other, OtherRefType);
14862   // Cast to rvalue.
14863   MoveCastBuilder MoveOther(OtherRef);
14864 
14865   // Builds the "this" pointer.
14866   ThisBuilder This;
14867 
14868   // Assign base classes.
14869   bool Invalid = false;
14870   for (auto &Base : ClassDecl->bases()) {
14871     // C++11 [class.copy]p28:
14872     //   It is unspecified whether subobjects representing virtual base classes
14873     //   are assigned more than once by the implicitly-defined copy assignment
14874     //   operator.
14875     // FIXME: Do not assign to a vbase that will be assigned by some other base
14876     // class. For a move-assignment, this can result in the vbase being moved
14877     // multiple times.
14878 
14879     // Form the assignment:
14880     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14881     QualType BaseType = Base.getType().getUnqualifiedType();
14882     if (!BaseType->isRecordType()) {
14883       Invalid = true;
14884       continue;
14885     }
14886 
14887     CXXCastPath BasePath;
14888     BasePath.push_back(&Base);
14889 
14890     // Construct the "from" expression, which is an implicit cast to the
14891     // appropriately-qualified base type.
14892     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14893 
14894     // Dereference "this".
14895     DerefBuilder DerefThis(This);
14896 
14897     // Implicitly cast "this" to the appropriately-qualified base type.
14898     CastBuilder To(DerefThis,
14899                    Context.getQualifiedType(
14900                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14901                    VK_LValue, BasePath);
14902 
14903     // Build the move.
14904     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14905                                             To, From,
14906                                             /*CopyingBaseSubobject=*/true,
14907                                             /*Copying=*/false);
14908     if (Move.isInvalid()) {
14909       MoveAssignOperator->setInvalidDecl();
14910       return;
14911     }
14912 
14913     // Success! Record the move.
14914     Statements.push_back(Move.getAs<Expr>());
14915   }
14916 
14917   // Assign non-static members.
14918   for (auto *Field : ClassDecl->fields()) {
14919     // FIXME: We should form some kind of AST representation for the implied
14920     // memcpy in a union copy operation.
14921     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14922       continue;
14923 
14924     if (Field->isInvalidDecl()) {
14925       Invalid = true;
14926       continue;
14927     }
14928 
14929     // Check for members of reference type; we can't move those.
14930     if (Field->getType()->isReferenceType()) {
14931       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14932         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14933       Diag(Field->getLocation(), diag::note_declared_at);
14934       Invalid = true;
14935       continue;
14936     }
14937 
14938     // Check for members of const-qualified, non-class type.
14939     QualType BaseType = Context.getBaseElementType(Field->getType());
14940     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14941       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14942         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14943       Diag(Field->getLocation(), diag::note_declared_at);
14944       Invalid = true;
14945       continue;
14946     }
14947 
14948     // Suppress assigning zero-width bitfields.
14949     if (Field->isZeroLengthBitField(Context))
14950       continue;
14951 
14952     QualType FieldType = Field->getType().getNonReferenceType();
14953     if (FieldType->isIncompleteArrayType()) {
14954       assert(ClassDecl->hasFlexibleArrayMember() &&
14955              "Incomplete array type is not valid");
14956       continue;
14957     }
14958 
14959     // Build references to the field in the object we're copying from and to.
14960     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14961                               LookupMemberName);
14962     MemberLookup.addDecl(Field);
14963     MemberLookup.resolveKind();
14964     MemberBuilder From(MoveOther, OtherRefType,
14965                        /*IsArrow=*/false, MemberLookup);
14966     MemberBuilder To(This, getCurrentThisType(),
14967                      /*IsArrow=*/true, MemberLookup);
14968 
14969     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14970         "Member reference with rvalue base must be rvalue except for reference "
14971         "members, which aren't allowed for move assignment.");
14972 
14973     // Build the move of this field.
14974     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14975                                             To, From,
14976                                             /*CopyingBaseSubobject=*/false,
14977                                             /*Copying=*/false);
14978     if (Move.isInvalid()) {
14979       MoveAssignOperator->setInvalidDecl();
14980       return;
14981     }
14982 
14983     // Success! Record the copy.
14984     Statements.push_back(Move.getAs<Stmt>());
14985   }
14986 
14987   if (!Invalid) {
14988     // Add a "return *this;"
14989     ExprResult ThisObj =
14990         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14991 
14992     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14993     if (Return.isInvalid())
14994       Invalid = true;
14995     else
14996       Statements.push_back(Return.getAs<Stmt>());
14997   }
14998 
14999   if (Invalid) {
15000     MoveAssignOperator->setInvalidDecl();
15001     return;
15002   }
15003 
15004   StmtResult Body;
15005   {
15006     CompoundScopeRAII CompoundScope(*this);
15007     Body = ActOnCompoundStmt(Loc, Loc, Statements,
15008                              /*isStmtExpr=*/false);
15009     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15010   }
15011   MoveAssignOperator->setBody(Body.getAs<Stmt>());
15012   MoveAssignOperator->markUsed(Context);
15013 
15014   if (ASTMutationListener *L = getASTMutationListener()) {
15015     L->CompletedImplicitDefinition(MoveAssignOperator);
15016   }
15017 }
15018 
15019 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15020                                                     CXXRecordDecl *ClassDecl) {
15021   // C++ [class.copy]p4:
15022   //   If the class definition does not explicitly declare a copy
15023   //   constructor, one is declared implicitly.
15024   assert(ClassDecl->needsImplicitCopyConstructor());
15025 
15026   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15027   if (DSM.isAlreadyBeingDeclared())
15028     return nullptr;
15029 
15030   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15031   QualType ArgType = ClassType;
15032   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15033   if (Const)
15034     ArgType = ArgType.withConst();
15035 
15036   LangAS AS = getDefaultCXXMethodAddrSpace();
15037   if (AS != LangAS::Default)
15038     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15039 
15040   ArgType = Context.getLValueReferenceType(ArgType);
15041 
15042   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15043                                                      CXXCopyConstructor,
15044                                                      Const);
15045 
15046   DeclarationName Name
15047     = Context.DeclarationNames.getCXXConstructorName(
15048                                            Context.getCanonicalType(ClassType));
15049   SourceLocation ClassLoc = ClassDecl->getLocation();
15050   DeclarationNameInfo NameInfo(Name, ClassLoc);
15051 
15052   //   An implicitly-declared copy constructor is an inline public
15053   //   member of its class.
15054   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15055       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15056       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15057       /*isInline=*/true,
15058       /*isImplicitlyDeclared=*/true,
15059       Constexpr ? ConstexprSpecKind::Constexpr
15060                 : ConstexprSpecKind::Unspecified);
15061   CopyConstructor->setAccess(AS_public);
15062   CopyConstructor->setDefaulted();
15063 
15064   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15065 
15066   if (getLangOpts().CUDA)
15067     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15068                                             CopyConstructor,
15069                                             /* ConstRHS */ Const,
15070                                             /* Diagnose */ false);
15071 
15072   // During template instantiation of special member functions we need a
15073   // reliable TypeSourceInfo for the parameter types in order to allow functions
15074   // to be substituted.
15075   TypeSourceInfo *TSI = nullptr;
15076   if (inTemplateInstantiation() && ClassDecl->isLambda())
15077     TSI = Context.getTrivialTypeSourceInfo(ArgType);
15078 
15079   // Add the parameter to the constructor.
15080   ParmVarDecl *FromParam =
15081       ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15082                           /*IdentifierInfo=*/nullptr, ArgType,
15083                           /*TInfo=*/TSI, SC_None, nullptr);
15084   CopyConstructor->setParams(FromParam);
15085 
15086   CopyConstructor->setTrivial(
15087       ClassDecl->needsOverloadResolutionForCopyConstructor()
15088           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15089           : ClassDecl->hasTrivialCopyConstructor());
15090 
15091   CopyConstructor->setTrivialForCall(
15092       ClassDecl->hasAttr<TrivialABIAttr>() ||
15093       (ClassDecl->needsOverloadResolutionForCopyConstructor()
15094            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15095              TAH_ConsiderTrivialABI)
15096            : ClassDecl->hasTrivialCopyConstructorForCall()));
15097 
15098   // Note that we have declared this constructor.
15099   ++getASTContext().NumImplicitCopyConstructorsDeclared;
15100 
15101   Scope *S = getScopeForContext(ClassDecl);
15102   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15103 
15104   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15105     ClassDecl->setImplicitCopyConstructorIsDeleted();
15106     SetDeclDeleted(CopyConstructor, ClassLoc);
15107   }
15108 
15109   if (S)
15110     PushOnScopeChains(CopyConstructor, S, false);
15111   ClassDecl->addDecl(CopyConstructor);
15112 
15113   return CopyConstructor;
15114 }
15115 
15116 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15117                                          CXXConstructorDecl *CopyConstructor) {
15118   assert((CopyConstructor->isDefaulted() &&
15119           CopyConstructor->isCopyConstructor() &&
15120           !CopyConstructor->doesThisDeclarationHaveABody() &&
15121           !CopyConstructor->isDeleted()) &&
15122          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15123   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15124     return;
15125 
15126   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15127   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15128 
15129   SynthesizedFunctionScope Scope(*this, CopyConstructor);
15130 
15131   // The exception specification is needed because we are defining the
15132   // function.
15133   ResolveExceptionSpec(CurrentLocation,
15134                        CopyConstructor->getType()->castAs<FunctionProtoType>());
15135   MarkVTableUsed(CurrentLocation, ClassDecl);
15136 
15137   // Add a context note for diagnostics produced after this point.
15138   Scope.addContextNote(CurrentLocation);
15139 
15140   // C++11 [class.copy]p7:
15141   //   The [definition of an implicitly declared copy constructor] is
15142   //   deprecated if the class has a user-declared copy assignment operator
15143   //   or a user-declared destructor.
15144   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15145     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15146 
15147   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15148     CopyConstructor->setInvalidDecl();
15149   }  else {
15150     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15151                              ? CopyConstructor->getEndLoc()
15152                              : CopyConstructor->getLocation();
15153     Sema::CompoundScopeRAII CompoundScope(*this);
15154     CopyConstructor->setBody(
15155         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
15156     CopyConstructor->markUsed(Context);
15157   }
15158 
15159   if (ASTMutationListener *L = getASTMutationListener()) {
15160     L->CompletedImplicitDefinition(CopyConstructor);
15161   }
15162 }
15163 
15164 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15165                                                     CXXRecordDecl *ClassDecl) {
15166   assert(ClassDecl->needsImplicitMoveConstructor());
15167 
15168   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15169   if (DSM.isAlreadyBeingDeclared())
15170     return nullptr;
15171 
15172   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15173 
15174   QualType ArgType = ClassType;
15175   LangAS AS = getDefaultCXXMethodAddrSpace();
15176   if (AS != LangAS::Default)
15177     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15178   ArgType = Context.getRValueReferenceType(ArgType);
15179 
15180   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15181                                                      CXXMoveConstructor,
15182                                                      false);
15183 
15184   DeclarationName Name
15185     = Context.DeclarationNames.getCXXConstructorName(
15186                                            Context.getCanonicalType(ClassType));
15187   SourceLocation ClassLoc = ClassDecl->getLocation();
15188   DeclarationNameInfo NameInfo(Name, ClassLoc);
15189 
15190   // C++11 [class.copy]p11:
15191   //   An implicitly-declared copy/move constructor is an inline public
15192   //   member of its class.
15193   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15194       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15195       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15196       /*isInline=*/true,
15197       /*isImplicitlyDeclared=*/true,
15198       Constexpr ? ConstexprSpecKind::Constexpr
15199                 : ConstexprSpecKind::Unspecified);
15200   MoveConstructor->setAccess(AS_public);
15201   MoveConstructor->setDefaulted();
15202 
15203   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15204 
15205   if (getLangOpts().CUDA)
15206     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15207                                             MoveConstructor,
15208                                             /* ConstRHS */ false,
15209                                             /* Diagnose */ false);
15210 
15211   // Add the parameter to the constructor.
15212   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15213                                                ClassLoc, ClassLoc,
15214                                                /*IdentifierInfo=*/nullptr,
15215                                                ArgType, /*TInfo=*/nullptr,
15216                                                SC_None, nullptr);
15217   MoveConstructor->setParams(FromParam);
15218 
15219   MoveConstructor->setTrivial(
15220       ClassDecl->needsOverloadResolutionForMoveConstructor()
15221           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15222           : ClassDecl->hasTrivialMoveConstructor());
15223 
15224   MoveConstructor->setTrivialForCall(
15225       ClassDecl->hasAttr<TrivialABIAttr>() ||
15226       (ClassDecl->needsOverloadResolutionForMoveConstructor()
15227            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15228                                     TAH_ConsiderTrivialABI)
15229            : ClassDecl->hasTrivialMoveConstructorForCall()));
15230 
15231   // Note that we have declared this constructor.
15232   ++getASTContext().NumImplicitMoveConstructorsDeclared;
15233 
15234   Scope *S = getScopeForContext(ClassDecl);
15235   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15236 
15237   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15238     ClassDecl->setImplicitMoveConstructorIsDeleted();
15239     SetDeclDeleted(MoveConstructor, ClassLoc);
15240   }
15241 
15242   if (S)
15243     PushOnScopeChains(MoveConstructor, S, false);
15244   ClassDecl->addDecl(MoveConstructor);
15245 
15246   return MoveConstructor;
15247 }
15248 
15249 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15250                                          CXXConstructorDecl *MoveConstructor) {
15251   assert((MoveConstructor->isDefaulted() &&
15252           MoveConstructor->isMoveConstructor() &&
15253           !MoveConstructor->doesThisDeclarationHaveABody() &&
15254           !MoveConstructor->isDeleted()) &&
15255          "DefineImplicitMoveConstructor - call it for implicit move ctor");
15256   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15257     return;
15258 
15259   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15260   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15261 
15262   SynthesizedFunctionScope Scope(*this, MoveConstructor);
15263 
15264   // The exception specification is needed because we are defining the
15265   // function.
15266   ResolveExceptionSpec(CurrentLocation,
15267                        MoveConstructor->getType()->castAs<FunctionProtoType>());
15268   MarkVTableUsed(CurrentLocation, ClassDecl);
15269 
15270   // Add a context note for diagnostics produced after this point.
15271   Scope.addContextNote(CurrentLocation);
15272 
15273   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15274     MoveConstructor->setInvalidDecl();
15275   } else {
15276     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15277                              ? MoveConstructor->getEndLoc()
15278                              : MoveConstructor->getLocation();
15279     Sema::CompoundScopeRAII CompoundScope(*this);
15280     MoveConstructor->setBody(ActOnCompoundStmt(
15281         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
15282     MoveConstructor->markUsed(Context);
15283   }
15284 
15285   if (ASTMutationListener *L = getASTMutationListener()) {
15286     L->CompletedImplicitDefinition(MoveConstructor);
15287   }
15288 }
15289 
15290 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15291   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15292 }
15293 
15294 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15295                             SourceLocation CurrentLocation,
15296                             CXXConversionDecl *Conv) {
15297   SynthesizedFunctionScope Scope(*this, Conv);
15298   assert(!Conv->getReturnType()->isUndeducedType());
15299 
15300   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15301   CallingConv CC =
15302       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15303 
15304   CXXRecordDecl *Lambda = Conv->getParent();
15305   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15306   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
15307 
15308   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15309     CallOp = InstantiateFunctionDeclaration(
15310         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15311     if (!CallOp)
15312       return;
15313 
15314     Invoker = InstantiateFunctionDeclaration(
15315         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15316     if (!Invoker)
15317       return;
15318   }
15319 
15320   if (CallOp->isInvalidDecl())
15321     return;
15322 
15323   // Mark the call operator referenced (and add to pending instantiations
15324   // if necessary).
15325   // For both the conversion and static-invoker template specializations
15326   // we construct their body's in this function, so no need to add them
15327   // to the PendingInstantiations.
15328   MarkFunctionReferenced(CurrentLocation, CallOp);
15329 
15330   // Fill in the __invoke function with a dummy implementation. IR generation
15331   // will fill in the actual details. Update its type in case it contained
15332   // an 'auto'.
15333   Invoker->markUsed(Context);
15334   Invoker->setReferenced();
15335   Invoker->setType(Conv->getReturnType()->getPointeeType());
15336   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15337 
15338   // Construct the body of the conversion function { return __invoke; }.
15339   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
15340                                        VK_LValue, Conv->getLocation());
15341   assert(FunctionRef && "Can't refer to __invoke function?");
15342   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15343   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
15344                                      Conv->getLocation()));
15345   Conv->markUsed(Context);
15346   Conv->setReferenced();
15347 
15348   if (ASTMutationListener *L = getASTMutationListener()) {
15349     L->CompletedImplicitDefinition(Conv);
15350     L->CompletedImplicitDefinition(Invoker);
15351   }
15352 }
15353 
15354 
15355 
15356 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15357        SourceLocation CurrentLocation,
15358        CXXConversionDecl *Conv)
15359 {
15360   assert(!Conv->getParent()->isGenericLambda());
15361 
15362   SynthesizedFunctionScope Scope(*this, Conv);
15363 
15364   // Copy-initialize the lambda object as needed to capture it.
15365   Expr *This = ActOnCXXThis(CurrentLocation).get();
15366   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15367 
15368   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15369                                                         Conv->getLocation(),
15370                                                         Conv, DerefThis);
15371 
15372   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15373   // behavior.  Note that only the general conversion function does this
15374   // (since it's unusable otherwise); in the case where we inline the
15375   // block literal, it has block literal lifetime semantics.
15376   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15377     BuildBlock = ImplicitCastExpr::Create(
15378         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15379         BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15380 
15381   if (BuildBlock.isInvalid()) {
15382     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15383     Conv->setInvalidDecl();
15384     return;
15385   }
15386 
15387   // Create the return statement that returns the block from the conversion
15388   // function.
15389   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15390   if (Return.isInvalid()) {
15391     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15392     Conv->setInvalidDecl();
15393     return;
15394   }
15395 
15396   // Set the body of the conversion function.
15397   Stmt *ReturnS = Return.get();
15398   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
15399                                      Conv->getLocation()));
15400   Conv->markUsed(Context);
15401 
15402   // We're done; notify the mutation listener, if any.
15403   if (ASTMutationListener *L = getASTMutationListener()) {
15404     L->CompletedImplicitDefinition(Conv);
15405   }
15406 }
15407 
15408 /// Determine whether the given list arguments contains exactly one
15409 /// "real" (non-default) argument.
15410 static bool hasOneRealArgument(MultiExprArg Args) {
15411   switch (Args.size()) {
15412   case 0:
15413     return false;
15414 
15415   default:
15416     if (!Args[1]->isDefaultArgument())
15417       return false;
15418 
15419     LLVM_FALLTHROUGH;
15420   case 1:
15421     return !Args[0]->isDefaultArgument();
15422   }
15423 
15424   return false;
15425 }
15426 
15427 ExprResult
15428 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15429                             NamedDecl *FoundDecl,
15430                             CXXConstructorDecl *Constructor,
15431                             MultiExprArg ExprArgs,
15432                             bool HadMultipleCandidates,
15433                             bool IsListInitialization,
15434                             bool IsStdInitListInitialization,
15435                             bool RequiresZeroInit,
15436                             unsigned ConstructKind,
15437                             SourceRange ParenRange) {
15438   bool Elidable = false;
15439 
15440   // C++0x [class.copy]p34:
15441   //   When certain criteria are met, an implementation is allowed to
15442   //   omit the copy/move construction of a class object, even if the
15443   //   copy/move constructor and/or destructor for the object have
15444   //   side effects. [...]
15445   //     - when a temporary class object that has not been bound to a
15446   //       reference (12.2) would be copied/moved to a class object
15447   //       with the same cv-unqualified type, the copy/move operation
15448   //       can be omitted by constructing the temporary object
15449   //       directly into the target of the omitted copy/move
15450   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15451       // FIXME: Converting constructors should also be accepted.
15452       // But to fix this, the logic that digs down into a CXXConstructExpr
15453       // to find the source object needs to handle it.
15454       // Right now it assumes the source object is passed directly as the
15455       // first argument.
15456       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15457     Expr *SubExpr = ExprArgs[0];
15458     // FIXME: Per above, this is also incorrect if we want to accept
15459     //        converting constructors, as isTemporaryObject will
15460     //        reject temporaries with different type from the
15461     //        CXXRecord itself.
15462     Elidable = SubExpr->isTemporaryObject(
15463         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15464   }
15465 
15466   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15467                                FoundDecl, Constructor,
15468                                Elidable, ExprArgs, HadMultipleCandidates,
15469                                IsListInitialization,
15470                                IsStdInitListInitialization, RequiresZeroInit,
15471                                ConstructKind, ParenRange);
15472 }
15473 
15474 ExprResult
15475 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15476                             NamedDecl *FoundDecl,
15477                             CXXConstructorDecl *Constructor,
15478                             bool Elidable,
15479                             MultiExprArg ExprArgs,
15480                             bool HadMultipleCandidates,
15481                             bool IsListInitialization,
15482                             bool IsStdInitListInitialization,
15483                             bool RequiresZeroInit,
15484                             unsigned ConstructKind,
15485                             SourceRange ParenRange) {
15486   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15487     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15488     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15489       return ExprError();
15490   }
15491 
15492   return BuildCXXConstructExpr(
15493       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15494       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15495       RequiresZeroInit, ConstructKind, ParenRange);
15496 }
15497 
15498 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15499 /// including handling of its default argument expressions.
15500 ExprResult
15501 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15502                             CXXConstructorDecl *Constructor,
15503                             bool Elidable,
15504                             MultiExprArg ExprArgs,
15505                             bool HadMultipleCandidates,
15506                             bool IsListInitialization,
15507                             bool IsStdInitListInitialization,
15508                             bool RequiresZeroInit,
15509                             unsigned ConstructKind,
15510                             SourceRange ParenRange) {
15511   assert(declaresSameEntity(
15512              Constructor->getParent(),
15513              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15514          "given constructor for wrong type");
15515   MarkFunctionReferenced(ConstructLoc, Constructor);
15516   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15517     return ExprError();
15518   if (getLangOpts().SYCLIsDevice &&
15519       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15520     return ExprError();
15521 
15522   return CheckForImmediateInvocation(
15523       CXXConstructExpr::Create(
15524           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15525           HadMultipleCandidates, IsListInitialization,
15526           IsStdInitListInitialization, RequiresZeroInit,
15527           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15528           ParenRange),
15529       Constructor);
15530 }
15531 
15532 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15533   assert(Field->hasInClassInitializer());
15534 
15535   // If we already have the in-class initializer nothing needs to be done.
15536   if (Field->getInClassInitializer())
15537     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15538 
15539   // If we might have already tried and failed to instantiate, don't try again.
15540   if (Field->isInvalidDecl())
15541     return ExprError();
15542 
15543   // Maybe we haven't instantiated the in-class initializer. Go check the
15544   // pattern FieldDecl to see if it has one.
15545   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15546 
15547   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15548     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15549     DeclContext::lookup_result Lookup =
15550         ClassPattern->lookup(Field->getDeclName());
15551 
15552     FieldDecl *Pattern = nullptr;
15553     for (auto L : Lookup) {
15554       if (isa<FieldDecl>(L)) {
15555         Pattern = cast<FieldDecl>(L);
15556         break;
15557       }
15558     }
15559     assert(Pattern && "We must have set the Pattern!");
15560 
15561     if (!Pattern->hasInClassInitializer() ||
15562         InstantiateInClassInitializer(Loc, Field, Pattern,
15563                                       getTemplateInstantiationArgs(Field))) {
15564       // Don't diagnose this again.
15565       Field->setInvalidDecl();
15566       return ExprError();
15567     }
15568     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15569   }
15570 
15571   // DR1351:
15572   //   If the brace-or-equal-initializer of a non-static data member
15573   //   invokes a defaulted default constructor of its class or of an
15574   //   enclosing class in a potentially evaluated subexpression, the
15575   //   program is ill-formed.
15576   //
15577   // This resolution is unworkable: the exception specification of the
15578   // default constructor can be needed in an unevaluated context, in
15579   // particular, in the operand of a noexcept-expression, and we can be
15580   // unable to compute an exception specification for an enclosed class.
15581   //
15582   // Any attempt to resolve the exception specification of a defaulted default
15583   // constructor before the initializer is lexically complete will ultimately
15584   // come here at which point we can diagnose it.
15585   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15586   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15587       << OutermostClass << Field;
15588   Diag(Field->getEndLoc(),
15589        diag::note_default_member_initializer_not_yet_parsed);
15590   // Recover by marking the field invalid, unless we're in a SFINAE context.
15591   if (!isSFINAEContext())
15592     Field->setInvalidDecl();
15593   return ExprError();
15594 }
15595 
15596 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15597   if (VD->isInvalidDecl()) return;
15598   // If initializing the variable failed, don't also diagnose problems with
15599   // the destructor, they're likely related.
15600   if (VD->getInit() && VD->getInit()->containsErrors())
15601     return;
15602 
15603   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15604   if (ClassDecl->isInvalidDecl()) return;
15605   if (ClassDecl->hasIrrelevantDestructor()) return;
15606   if (ClassDecl->isDependentContext()) return;
15607 
15608   if (VD->isNoDestroy(getASTContext()))
15609     return;
15610 
15611   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15612 
15613   // If this is an array, we'll require the destructor during initialization, so
15614   // we can skip over this. We still want to emit exit-time destructor warnings
15615   // though.
15616   if (!VD->getType()->isArrayType()) {
15617     MarkFunctionReferenced(VD->getLocation(), Destructor);
15618     CheckDestructorAccess(VD->getLocation(), Destructor,
15619                           PDiag(diag::err_access_dtor_var)
15620                               << VD->getDeclName() << VD->getType());
15621     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15622   }
15623 
15624   if (Destructor->isTrivial()) return;
15625 
15626   // If the destructor is constexpr, check whether the variable has constant
15627   // destruction now.
15628   if (Destructor->isConstexpr()) {
15629     bool HasConstantInit = false;
15630     if (VD->getInit() && !VD->getInit()->isValueDependent())
15631       HasConstantInit = VD->evaluateValue();
15632     SmallVector<PartialDiagnosticAt, 8> Notes;
15633     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15634         HasConstantInit) {
15635       Diag(VD->getLocation(),
15636            diag::err_constexpr_var_requires_const_destruction) << VD;
15637       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15638         Diag(Notes[I].first, Notes[I].second);
15639     }
15640   }
15641 
15642   if (!VD->hasGlobalStorage()) return;
15643 
15644   // Emit warning for non-trivial dtor in global scope (a real global,
15645   // class-static, function-static).
15646   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15647 
15648   // TODO: this should be re-enabled for static locals by !CXAAtExit
15649   if (!VD->isStaticLocal())
15650     Diag(VD->getLocation(), diag::warn_global_destructor);
15651 }
15652 
15653 /// Given a constructor and the set of arguments provided for the
15654 /// constructor, convert the arguments and add any required default arguments
15655 /// to form a proper call to this constructor.
15656 ///
15657 /// \returns true if an error occurred, false otherwise.
15658 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15659                                    QualType DeclInitType, MultiExprArg ArgsPtr,
15660                                    SourceLocation Loc,
15661                                    SmallVectorImpl<Expr *> &ConvertedArgs,
15662                                    bool AllowExplicit,
15663                                    bool IsListInitialization) {
15664   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15665   unsigned NumArgs = ArgsPtr.size();
15666   Expr **Args = ArgsPtr.data();
15667 
15668   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15669   unsigned NumParams = Proto->getNumParams();
15670 
15671   // If too few arguments are available, we'll fill in the rest with defaults.
15672   if (NumArgs < NumParams)
15673     ConvertedArgs.reserve(NumParams);
15674   else
15675     ConvertedArgs.reserve(NumArgs);
15676 
15677   VariadicCallType CallType =
15678     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15679   SmallVector<Expr *, 8> AllArgs;
15680   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15681                                         Proto, 0,
15682                                         llvm::makeArrayRef(Args, NumArgs),
15683                                         AllArgs,
15684                                         CallType, AllowExplicit,
15685                                         IsListInitialization);
15686   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15687 
15688   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15689 
15690   CheckConstructorCall(Constructor, DeclInitType,
15691                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15692                        Proto, Loc);
15693 
15694   return Invalid;
15695 }
15696 
15697 static inline bool
15698 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15699                                        const FunctionDecl *FnDecl) {
15700   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15701   if (isa<NamespaceDecl>(DC)) {
15702     return SemaRef.Diag(FnDecl->getLocation(),
15703                         diag::err_operator_new_delete_declared_in_namespace)
15704       << FnDecl->getDeclName();
15705   }
15706 
15707   if (isa<TranslationUnitDecl>(DC) &&
15708       FnDecl->getStorageClass() == SC_Static) {
15709     return SemaRef.Diag(FnDecl->getLocation(),
15710                         diag::err_operator_new_delete_declared_static)
15711       << FnDecl->getDeclName();
15712   }
15713 
15714   return false;
15715 }
15716 
15717 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15718                                              const PointerType *PtrTy) {
15719   auto &Ctx = SemaRef.Context;
15720   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15721   PtrQuals.removeAddressSpace();
15722   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15723       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15724 }
15725 
15726 static inline bool
15727 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15728                             CanQualType ExpectedResultType,
15729                             CanQualType ExpectedFirstParamType,
15730                             unsigned DependentParamTypeDiag,
15731                             unsigned InvalidParamTypeDiag) {
15732   QualType ResultType =
15733       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15734 
15735   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15736     // The operator is valid on any address space for OpenCL.
15737     // Drop address space from actual and expected result types.
15738     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15739       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15740 
15741     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15742       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15743   }
15744 
15745   // Check that the result type is what we expect.
15746   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15747     // Reject even if the type is dependent; an operator delete function is
15748     // required to have a non-dependent result type.
15749     return SemaRef.Diag(
15750                FnDecl->getLocation(),
15751                ResultType->isDependentType()
15752                    ? diag::err_operator_new_delete_dependent_result_type
15753                    : diag::err_operator_new_delete_invalid_result_type)
15754            << FnDecl->getDeclName() << ExpectedResultType;
15755   }
15756 
15757   // A function template must have at least 2 parameters.
15758   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15759     return SemaRef.Diag(FnDecl->getLocation(),
15760                       diag::err_operator_new_delete_template_too_few_parameters)
15761         << FnDecl->getDeclName();
15762 
15763   // The function decl must have at least 1 parameter.
15764   if (FnDecl->getNumParams() == 0)
15765     return SemaRef.Diag(FnDecl->getLocation(),
15766                         diag::err_operator_new_delete_too_few_parameters)
15767       << FnDecl->getDeclName();
15768 
15769   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15770   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15771     // The operator is valid on any address space for OpenCL.
15772     // Drop address space from actual and expected first parameter types.
15773     if (const auto *PtrTy =
15774             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15775       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15776 
15777     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15778       ExpectedFirstParamType =
15779           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15780   }
15781 
15782   // Check that the first parameter type is what we expect.
15783   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15784       ExpectedFirstParamType) {
15785     // The first parameter type is not allowed to be dependent. As a tentative
15786     // DR resolution, we allow a dependent parameter type if it is the right
15787     // type anyway, to allow destroying operator delete in class templates.
15788     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15789                                                    ? DependentParamTypeDiag
15790                                                    : InvalidParamTypeDiag)
15791            << FnDecl->getDeclName() << ExpectedFirstParamType;
15792   }
15793 
15794   return false;
15795 }
15796 
15797 static bool
15798 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15799   // C++ [basic.stc.dynamic.allocation]p1:
15800   //   A program is ill-formed if an allocation function is declared in a
15801   //   namespace scope other than global scope or declared static in global
15802   //   scope.
15803   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15804     return true;
15805 
15806   CanQualType SizeTy =
15807     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15808 
15809   // C++ [basic.stc.dynamic.allocation]p1:
15810   //  The return type shall be void*. The first parameter shall have type
15811   //  std::size_t.
15812   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15813                                   SizeTy,
15814                                   diag::err_operator_new_dependent_param_type,
15815                                   diag::err_operator_new_param_type))
15816     return true;
15817 
15818   // C++ [basic.stc.dynamic.allocation]p1:
15819   //  The first parameter shall not have an associated default argument.
15820   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15821     return SemaRef.Diag(FnDecl->getLocation(),
15822                         diag::err_operator_new_default_arg)
15823       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15824 
15825   return false;
15826 }
15827 
15828 static bool
15829 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15830   // C++ [basic.stc.dynamic.deallocation]p1:
15831   //   A program is ill-formed if deallocation functions are declared in a
15832   //   namespace scope other than global scope or declared static in global
15833   //   scope.
15834   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15835     return true;
15836 
15837   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15838 
15839   // C++ P0722:
15840   //   Within a class C, the first parameter of a destroying operator delete
15841   //   shall be of type C *. The first parameter of any other deallocation
15842   //   function shall be of type void *.
15843   CanQualType ExpectedFirstParamType =
15844       MD && MD->isDestroyingOperatorDelete()
15845           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15846                 SemaRef.Context.getRecordType(MD->getParent())))
15847           : SemaRef.Context.VoidPtrTy;
15848 
15849   // C++ [basic.stc.dynamic.deallocation]p2:
15850   //   Each deallocation function shall return void
15851   if (CheckOperatorNewDeleteTypes(
15852           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15853           diag::err_operator_delete_dependent_param_type,
15854           diag::err_operator_delete_param_type))
15855     return true;
15856 
15857   // C++ P0722:
15858   //   A destroying operator delete shall be a usual deallocation function.
15859   if (MD && !MD->getParent()->isDependentContext() &&
15860       MD->isDestroyingOperatorDelete() &&
15861       !SemaRef.isUsualDeallocationFunction(MD)) {
15862     SemaRef.Diag(MD->getLocation(),
15863                  diag::err_destroying_operator_delete_not_usual);
15864     return true;
15865   }
15866 
15867   return false;
15868 }
15869 
15870 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15871 /// of this overloaded operator is well-formed. If so, returns false;
15872 /// otherwise, emits appropriate diagnostics and returns true.
15873 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15874   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15875          "Expected an overloaded operator declaration");
15876 
15877   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15878 
15879   // C++ [over.oper]p5:
15880   //   The allocation and deallocation functions, operator new,
15881   //   operator new[], operator delete and operator delete[], are
15882   //   described completely in 3.7.3. The attributes and restrictions
15883   //   found in the rest of this subclause do not apply to them unless
15884   //   explicitly stated in 3.7.3.
15885   if (Op == OO_Delete || Op == OO_Array_Delete)
15886     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15887 
15888   if (Op == OO_New || Op == OO_Array_New)
15889     return CheckOperatorNewDeclaration(*this, FnDecl);
15890 
15891   // C++ [over.oper]p6:
15892   //   An operator function shall either be a non-static member
15893   //   function or be a non-member function and have at least one
15894   //   parameter whose type is a class, a reference to a class, an
15895   //   enumeration, or a reference to an enumeration.
15896   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15897     if (MethodDecl->isStatic())
15898       return Diag(FnDecl->getLocation(),
15899                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15900   } else {
15901     bool ClassOrEnumParam = false;
15902     for (auto Param : FnDecl->parameters()) {
15903       QualType ParamType = Param->getType().getNonReferenceType();
15904       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15905           ParamType->isEnumeralType()) {
15906         ClassOrEnumParam = true;
15907         break;
15908       }
15909     }
15910 
15911     if (!ClassOrEnumParam)
15912       return Diag(FnDecl->getLocation(),
15913                   diag::err_operator_overload_needs_class_or_enum)
15914         << FnDecl->getDeclName();
15915   }
15916 
15917   // C++ [over.oper]p8:
15918   //   An operator function cannot have default arguments (8.3.6),
15919   //   except where explicitly stated below.
15920   //
15921   // Only the function-call operator (C++ [over.call]p1) and the subscript
15922   // operator (CWG2507) allow default arguments.
15923   if (Op != OO_Call) {
15924     ParmVarDecl *FirstDefaultedParam = nullptr;
15925     for (auto Param : FnDecl->parameters()) {
15926       if (Param->hasDefaultArg()) {
15927         FirstDefaultedParam = Param;
15928         break;
15929       }
15930     }
15931     if (FirstDefaultedParam) {
15932       if (Op == OO_Subscript) {
15933         Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15934                                         ? diag::ext_subscript_overload
15935                                         : diag::error_subscript_overload)
15936             << FnDecl->getDeclName() << 1
15937             << FirstDefaultedParam->getDefaultArgRange();
15938       } else {
15939         return Diag(FirstDefaultedParam->getLocation(),
15940                     diag::err_operator_overload_default_arg)
15941                << FnDecl->getDeclName()
15942                << FirstDefaultedParam->getDefaultArgRange();
15943       }
15944     }
15945   }
15946 
15947   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15948     { false, false, false }
15949 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15950     , { Unary, Binary, MemberOnly }
15951 #include "clang/Basic/OperatorKinds.def"
15952   };
15953 
15954   bool CanBeUnaryOperator = OperatorUses[Op][0];
15955   bool CanBeBinaryOperator = OperatorUses[Op][1];
15956   bool MustBeMemberOperator = OperatorUses[Op][2];
15957 
15958   // C++ [over.oper]p8:
15959   //   [...] Operator functions cannot have more or fewer parameters
15960   //   than the number required for the corresponding operator, as
15961   //   described in the rest of this subclause.
15962   unsigned NumParams = FnDecl->getNumParams()
15963                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15964   if (Op != OO_Call && Op != OO_Subscript &&
15965       ((NumParams == 1 && !CanBeUnaryOperator) ||
15966        (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
15967        (NumParams > 2))) {
15968     // We have the wrong number of parameters.
15969     unsigned ErrorKind;
15970     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15971       ErrorKind = 2;  // 2 -> unary or binary.
15972     } else if (CanBeUnaryOperator) {
15973       ErrorKind = 0;  // 0 -> unary
15974     } else {
15975       assert(CanBeBinaryOperator &&
15976              "All non-call overloaded operators are unary or binary!");
15977       ErrorKind = 1;  // 1 -> binary
15978     }
15979     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15980       << FnDecl->getDeclName() << NumParams << ErrorKind;
15981   }
15982 
15983   if (Op == OO_Subscript && NumParams != 2) {
15984     Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15985                                     ? diag::ext_subscript_overload
15986                                     : diag::error_subscript_overload)
15987         << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
15988   }
15989 
15990   // Overloaded operators other than operator() and operator[] cannot be
15991   // variadic.
15992   if (Op != OO_Call &&
15993       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15994     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15995            << FnDecl->getDeclName();
15996   }
15997 
15998   // Some operators must be non-static member functions.
15999   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16000     return Diag(FnDecl->getLocation(),
16001                 diag::err_operator_overload_must_be_member)
16002       << FnDecl->getDeclName();
16003   }
16004 
16005   // C++ [over.inc]p1:
16006   //   The user-defined function called operator++ implements the
16007   //   prefix and postfix ++ operator. If this function is a member
16008   //   function with no parameters, or a non-member function with one
16009   //   parameter of class or enumeration type, it defines the prefix
16010   //   increment operator ++ for objects of that type. If the function
16011   //   is a member function with one parameter (which shall be of type
16012   //   int) or a non-member function with two parameters (the second
16013   //   of which shall be of type int), it defines the postfix
16014   //   increment operator ++ for objects of that type.
16015   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16016     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16017     QualType ParamType = LastParam->getType();
16018 
16019     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16020         !ParamType->isDependentType())
16021       return Diag(LastParam->getLocation(),
16022                   diag::err_operator_overload_post_incdec_must_be_int)
16023         << LastParam->getType() << (Op == OO_MinusMinus);
16024   }
16025 
16026   return false;
16027 }
16028 
16029 static bool
16030 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16031                                           FunctionTemplateDecl *TpDecl) {
16032   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16033 
16034   // Must have one or two template parameters.
16035   if (TemplateParams->size() == 1) {
16036     NonTypeTemplateParmDecl *PmDecl =
16037         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16038 
16039     // The template parameter must be a char parameter pack.
16040     if (PmDecl && PmDecl->isTemplateParameterPack() &&
16041         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16042       return false;
16043 
16044     // C++20 [over.literal]p5:
16045     //   A string literal operator template is a literal operator template
16046     //   whose template-parameter-list comprises a single non-type
16047     //   template-parameter of class type.
16048     //
16049     // As a DR resolution, we also allow placeholders for deduced class
16050     // template specializations.
16051     if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16052         !PmDecl->isTemplateParameterPack() &&
16053         (PmDecl->getType()->isRecordType() ||
16054          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16055       return false;
16056   } else if (TemplateParams->size() == 2) {
16057     TemplateTypeParmDecl *PmType =
16058         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16059     NonTypeTemplateParmDecl *PmArgs =
16060         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16061 
16062     // The second template parameter must be a parameter pack with the
16063     // first template parameter as its type.
16064     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16065         PmArgs->isTemplateParameterPack()) {
16066       const TemplateTypeParmType *TArgs =
16067           PmArgs->getType()->getAs<TemplateTypeParmType>();
16068       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16069           TArgs->getIndex() == PmType->getIndex()) {
16070         if (!SemaRef.inTemplateInstantiation())
16071           SemaRef.Diag(TpDecl->getLocation(),
16072                        diag::ext_string_literal_operator_template);
16073         return false;
16074       }
16075     }
16076   }
16077 
16078   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16079                diag::err_literal_operator_template)
16080       << TpDecl->getTemplateParameters()->getSourceRange();
16081   return true;
16082 }
16083 
16084 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16085 /// of this literal operator function is well-formed. If so, returns
16086 /// false; otherwise, emits appropriate diagnostics and returns true.
16087 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16088   if (isa<CXXMethodDecl>(FnDecl)) {
16089     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16090       << FnDecl->getDeclName();
16091     return true;
16092   }
16093 
16094   if (FnDecl->isExternC()) {
16095     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16096     if (const LinkageSpecDecl *LSD =
16097             FnDecl->getDeclContext()->getExternCContext())
16098       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16099     return true;
16100   }
16101 
16102   // This might be the definition of a literal operator template.
16103   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16104 
16105   // This might be a specialization of a literal operator template.
16106   if (!TpDecl)
16107     TpDecl = FnDecl->getPrimaryTemplate();
16108 
16109   // template <char...> type operator "" name() and
16110   // template <class T, T...> type operator "" name() are the only valid
16111   // template signatures, and the only valid signatures with no parameters.
16112   //
16113   // C++20 also allows template <SomeClass T> type operator "" name().
16114   if (TpDecl) {
16115     if (FnDecl->param_size() != 0) {
16116       Diag(FnDecl->getLocation(),
16117            diag::err_literal_operator_template_with_params);
16118       return true;
16119     }
16120 
16121     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16122       return true;
16123 
16124   } else if (FnDecl->param_size() == 1) {
16125     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16126 
16127     QualType ParamType = Param->getType().getUnqualifiedType();
16128 
16129     // Only unsigned long long int, long double, any character type, and const
16130     // char * are allowed as the only parameters.
16131     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16132         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16133         Context.hasSameType(ParamType, Context.CharTy) ||
16134         Context.hasSameType(ParamType, Context.WideCharTy) ||
16135         Context.hasSameType(ParamType, Context.Char8Ty) ||
16136         Context.hasSameType(ParamType, Context.Char16Ty) ||
16137         Context.hasSameType(ParamType, Context.Char32Ty)) {
16138     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16139       QualType InnerType = Ptr->getPointeeType();
16140 
16141       // Pointer parameter must be a const char *.
16142       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16143                                 Context.CharTy) &&
16144             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16145         Diag(Param->getSourceRange().getBegin(),
16146              diag::err_literal_operator_param)
16147             << ParamType << "'const char *'" << Param->getSourceRange();
16148         return true;
16149       }
16150 
16151     } else if (ParamType->isRealFloatingType()) {
16152       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16153           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16154       return true;
16155 
16156     } else if (ParamType->isIntegerType()) {
16157       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16158           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16159       return true;
16160 
16161     } else {
16162       Diag(Param->getSourceRange().getBegin(),
16163            diag::err_literal_operator_invalid_param)
16164           << ParamType << Param->getSourceRange();
16165       return true;
16166     }
16167 
16168   } else if (FnDecl->param_size() == 2) {
16169     FunctionDecl::param_iterator Param = FnDecl->param_begin();
16170 
16171     // First, verify that the first parameter is correct.
16172 
16173     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16174 
16175     // Two parameter function must have a pointer to const as a
16176     // first parameter; let's strip those qualifiers.
16177     const PointerType *PT = FirstParamType->getAs<PointerType>();
16178 
16179     if (!PT) {
16180       Diag((*Param)->getSourceRange().getBegin(),
16181            diag::err_literal_operator_param)
16182           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16183       return true;
16184     }
16185 
16186     QualType PointeeType = PT->getPointeeType();
16187     // First parameter must be const
16188     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16189       Diag((*Param)->getSourceRange().getBegin(),
16190            diag::err_literal_operator_param)
16191           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16192       return true;
16193     }
16194 
16195     QualType InnerType = PointeeType.getUnqualifiedType();
16196     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16197     // const char32_t* are allowed as the first parameter to a two-parameter
16198     // function
16199     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16200           Context.hasSameType(InnerType, Context.WideCharTy) ||
16201           Context.hasSameType(InnerType, Context.Char8Ty) ||
16202           Context.hasSameType(InnerType, Context.Char16Ty) ||
16203           Context.hasSameType(InnerType, Context.Char32Ty))) {
16204       Diag((*Param)->getSourceRange().getBegin(),
16205            diag::err_literal_operator_param)
16206           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16207       return true;
16208     }
16209 
16210     // Move on to the second and final parameter.
16211     ++Param;
16212 
16213     // The second parameter must be a std::size_t.
16214     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16215     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16216       Diag((*Param)->getSourceRange().getBegin(),
16217            diag::err_literal_operator_param)
16218           << SecondParamType << Context.getSizeType()
16219           << (*Param)->getSourceRange();
16220       return true;
16221     }
16222   } else {
16223     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16224     return true;
16225   }
16226 
16227   // Parameters are good.
16228 
16229   // A parameter-declaration-clause containing a default argument is not
16230   // equivalent to any of the permitted forms.
16231   for (auto Param : FnDecl->parameters()) {
16232     if (Param->hasDefaultArg()) {
16233       Diag(Param->getDefaultArgRange().getBegin(),
16234            diag::err_literal_operator_default_argument)
16235         << Param->getDefaultArgRange();
16236       break;
16237     }
16238   }
16239 
16240   StringRef LiteralName
16241     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16242   if (LiteralName[0] != '_' &&
16243       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16244     // C++11 [usrlit.suffix]p1:
16245     //   Literal suffix identifiers that do not start with an underscore
16246     //   are reserved for future standardization.
16247     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16248       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16249   }
16250 
16251   return false;
16252 }
16253 
16254 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16255 /// linkage specification, including the language and (if present)
16256 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16257 /// language string literal. LBraceLoc, if valid, provides the location of
16258 /// the '{' brace. Otherwise, this linkage specification does not
16259 /// have any braces.
16260 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16261                                            Expr *LangStr,
16262                                            SourceLocation LBraceLoc) {
16263   StringLiteral *Lit = cast<StringLiteral>(LangStr);
16264   if (!Lit->isAscii()) {
16265     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16266       << LangStr->getSourceRange();
16267     return nullptr;
16268   }
16269 
16270   StringRef Lang = Lit->getString();
16271   LinkageSpecDecl::LanguageIDs Language;
16272   if (Lang == "C")
16273     Language = LinkageSpecDecl::lang_c;
16274   else if (Lang == "C++")
16275     Language = LinkageSpecDecl::lang_cxx;
16276   else {
16277     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16278       << LangStr->getSourceRange();
16279     return nullptr;
16280   }
16281 
16282   // FIXME: Add all the various semantics of linkage specifications
16283 
16284   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16285                                                LangStr->getExprLoc(), Language,
16286                                                LBraceLoc.isValid());
16287 
16288   /// C++ [module.unit]p7.2.3
16289   /// - Otherwise, if the declaration
16290   ///   - ...
16291   ///   - ...
16292   ///   - appears within a linkage-specification,
16293   ///   it is attached to the global module.
16294   ///
16295   /// If the declaration is already in global module fragment, we don't
16296   /// need to attach it again.
16297   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16298     Module *GlobalModule =
16299         PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
16300     D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16301     D->setLocalOwningModule(GlobalModule);
16302   }
16303 
16304   CurContext->addDecl(D);
16305   PushDeclContext(S, D);
16306   return D;
16307 }
16308 
16309 /// ActOnFinishLinkageSpecification - Complete the definition of
16310 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16311 /// valid, it's the position of the closing '}' brace in a linkage
16312 /// specification that uses braces.
16313 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16314                                             Decl *LinkageSpec,
16315                                             SourceLocation RBraceLoc) {
16316   if (RBraceLoc.isValid()) {
16317     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16318     LSDecl->setRBraceLoc(RBraceLoc);
16319   }
16320 
16321   // If the current module doesn't has Parent, it implies that the
16322   // LinkageSpec isn't in the module created by itself. So we don't
16323   // need to pop it.
16324   if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16325       getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
16326     PopGlobalModuleFragment();
16327 
16328   PopDeclContext();
16329   return LinkageSpec;
16330 }
16331 
16332 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16333                                   const ParsedAttributesView &AttrList,
16334                                   SourceLocation SemiLoc) {
16335   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16336   // Attribute declarations appertain to empty declaration so we handle
16337   // them here.
16338   ProcessDeclAttributeList(S, ED, AttrList);
16339 
16340   CurContext->addDecl(ED);
16341   return ED;
16342 }
16343 
16344 /// Perform semantic analysis for the variable declaration that
16345 /// occurs within a C++ catch clause, returning the newly-created
16346 /// variable.
16347 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16348                                          TypeSourceInfo *TInfo,
16349                                          SourceLocation StartLoc,
16350                                          SourceLocation Loc,
16351                                          IdentifierInfo *Name) {
16352   bool Invalid = false;
16353   QualType ExDeclType = TInfo->getType();
16354 
16355   // Arrays and functions decay.
16356   if (ExDeclType->isArrayType())
16357     ExDeclType = Context.getArrayDecayedType(ExDeclType);
16358   else if (ExDeclType->isFunctionType())
16359     ExDeclType = Context.getPointerType(ExDeclType);
16360 
16361   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16362   // The exception-declaration shall not denote a pointer or reference to an
16363   // incomplete type, other than [cv] void*.
16364   // N2844 forbids rvalue references.
16365   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16366     Diag(Loc, diag::err_catch_rvalue_ref);
16367     Invalid = true;
16368   }
16369 
16370   if (ExDeclType->isVariablyModifiedType()) {
16371     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16372     Invalid = true;
16373   }
16374 
16375   QualType BaseType = ExDeclType;
16376   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16377   unsigned DK = diag::err_catch_incomplete;
16378   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16379     BaseType = Ptr->getPointeeType();
16380     Mode = 1;
16381     DK = diag::err_catch_incomplete_ptr;
16382   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16383     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16384     BaseType = Ref->getPointeeType();
16385     Mode = 2;
16386     DK = diag::err_catch_incomplete_ref;
16387   }
16388   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16389       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16390     Invalid = true;
16391 
16392   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16393     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16394     Invalid = true;
16395   }
16396 
16397   if (!Invalid && !ExDeclType->isDependentType() &&
16398       RequireNonAbstractType(Loc, ExDeclType,
16399                              diag::err_abstract_type_in_decl,
16400                              AbstractVariableType))
16401     Invalid = true;
16402 
16403   // Only the non-fragile NeXT runtime currently supports C++ catches
16404   // of ObjC types, and no runtime supports catching ObjC types by value.
16405   if (!Invalid && getLangOpts().ObjC) {
16406     QualType T = ExDeclType;
16407     if (const ReferenceType *RT = T->getAs<ReferenceType>())
16408       T = RT->getPointeeType();
16409 
16410     if (T->isObjCObjectType()) {
16411       Diag(Loc, diag::err_objc_object_catch);
16412       Invalid = true;
16413     } else if (T->isObjCObjectPointerType()) {
16414       // FIXME: should this be a test for macosx-fragile specifically?
16415       if (getLangOpts().ObjCRuntime.isFragile())
16416         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16417     }
16418   }
16419 
16420   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16421                                     ExDeclType, TInfo, SC_None);
16422   ExDecl->setExceptionVariable(true);
16423 
16424   // In ARC, infer 'retaining' for variables of retainable type.
16425   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16426     Invalid = true;
16427 
16428   if (!Invalid && !ExDeclType->isDependentType()) {
16429     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16430       // Insulate this from anything else we might currently be parsing.
16431       EnterExpressionEvaluationContext scope(
16432           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16433 
16434       // C++ [except.handle]p16:
16435       //   The object declared in an exception-declaration or, if the
16436       //   exception-declaration does not specify a name, a temporary (12.2) is
16437       //   copy-initialized (8.5) from the exception object. [...]
16438       //   The object is destroyed when the handler exits, after the destruction
16439       //   of any automatic objects initialized within the handler.
16440       //
16441       // We just pretend to initialize the object with itself, then make sure
16442       // it can be destroyed later.
16443       QualType initType = Context.getExceptionObjectType(ExDeclType);
16444 
16445       InitializedEntity entity =
16446         InitializedEntity::InitializeVariable(ExDecl);
16447       InitializationKind initKind =
16448         InitializationKind::CreateCopy(Loc, SourceLocation());
16449 
16450       Expr *opaqueValue =
16451         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16452       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16453       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16454       if (result.isInvalid())
16455         Invalid = true;
16456       else {
16457         // If the constructor used was non-trivial, set this as the
16458         // "initializer".
16459         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16460         if (!construct->getConstructor()->isTrivial()) {
16461           Expr *init = MaybeCreateExprWithCleanups(construct);
16462           ExDecl->setInit(init);
16463         }
16464 
16465         // And make sure it's destructable.
16466         FinalizeVarWithDestructor(ExDecl, recordType);
16467       }
16468     }
16469   }
16470 
16471   if (Invalid)
16472     ExDecl->setInvalidDecl();
16473 
16474   return ExDecl;
16475 }
16476 
16477 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16478 /// handler.
16479 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16480   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16481   bool Invalid = D.isInvalidType();
16482 
16483   // Check for unexpanded parameter packs.
16484   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16485                                       UPPC_ExceptionType)) {
16486     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16487                                              D.getIdentifierLoc());
16488     Invalid = true;
16489   }
16490 
16491   IdentifierInfo *II = D.getIdentifier();
16492   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16493                                              LookupOrdinaryName,
16494                                              ForVisibleRedeclaration)) {
16495     // The scope should be freshly made just for us. There is just no way
16496     // it contains any previous declaration, except for function parameters in
16497     // a function-try-block's catch statement.
16498     assert(!S->isDeclScope(PrevDecl));
16499     if (isDeclInScope(PrevDecl, CurContext, S)) {
16500       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16501         << D.getIdentifier();
16502       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16503       Invalid = true;
16504     } else if (PrevDecl->isTemplateParameter())
16505       // Maybe we will complain about the shadowed template parameter.
16506       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16507   }
16508 
16509   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16510     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16511       << D.getCXXScopeSpec().getRange();
16512     Invalid = true;
16513   }
16514 
16515   VarDecl *ExDecl = BuildExceptionDeclaration(
16516       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16517   if (Invalid)
16518     ExDecl->setInvalidDecl();
16519 
16520   // Add the exception declaration into this scope.
16521   if (II)
16522     PushOnScopeChains(ExDecl, S);
16523   else
16524     CurContext->addDecl(ExDecl);
16525 
16526   ProcessDeclAttributes(S, ExDecl, D);
16527   return ExDecl;
16528 }
16529 
16530 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16531                                          Expr *AssertExpr,
16532                                          Expr *AssertMessageExpr,
16533                                          SourceLocation RParenLoc) {
16534   StringLiteral *AssertMessage =
16535       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16536 
16537   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16538     return nullptr;
16539 
16540   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16541                                       AssertMessage, RParenLoc, false);
16542 }
16543 
16544 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16545                                          Expr *AssertExpr,
16546                                          StringLiteral *AssertMessage,
16547                                          SourceLocation RParenLoc,
16548                                          bool Failed) {
16549   assert(AssertExpr != nullptr && "Expected non-null condition");
16550   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16551       !Failed) {
16552     // In a static_assert-declaration, the constant-expression shall be a
16553     // constant expression that can be contextually converted to bool.
16554     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16555     if (Converted.isInvalid())
16556       Failed = true;
16557 
16558     ExprResult FullAssertExpr =
16559         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16560                             /*DiscardedValue*/ false,
16561                             /*IsConstexpr*/ true);
16562     if (FullAssertExpr.isInvalid())
16563       Failed = true;
16564     else
16565       AssertExpr = FullAssertExpr.get();
16566 
16567     llvm::APSInt Cond;
16568     if (!Failed && VerifyIntegerConstantExpression(
16569                        AssertExpr, &Cond,
16570                        diag::err_static_assert_expression_is_not_constant)
16571                        .isInvalid())
16572       Failed = true;
16573 
16574     if (!Failed && !Cond) {
16575       SmallString<256> MsgBuffer;
16576       llvm::raw_svector_ostream Msg(MsgBuffer);
16577       if (AssertMessage)
16578         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16579 
16580       Expr *InnerCond = nullptr;
16581       std::string InnerCondDescription;
16582       std::tie(InnerCond, InnerCondDescription) =
16583         findFailedBooleanCondition(Converted.get());
16584       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16585         // Drill down into concept specialization expressions to see why they
16586         // weren't satisfied.
16587         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16588           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16589         ConstraintSatisfaction Satisfaction;
16590         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16591           DiagnoseUnsatisfiedConstraint(Satisfaction);
16592       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16593                            && !isa<IntegerLiteral>(InnerCond)) {
16594         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16595           << InnerCondDescription << !AssertMessage
16596           << Msg.str() << InnerCond->getSourceRange();
16597       } else {
16598         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16599           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16600       }
16601       Failed = true;
16602     }
16603   } else {
16604     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16605                                                     /*DiscardedValue*/false,
16606                                                     /*IsConstexpr*/true);
16607     if (FullAssertExpr.isInvalid())
16608       Failed = true;
16609     else
16610       AssertExpr = FullAssertExpr.get();
16611   }
16612 
16613   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16614                                         AssertExpr, AssertMessage, RParenLoc,
16615                                         Failed);
16616 
16617   CurContext->addDecl(Decl);
16618   return Decl;
16619 }
16620 
16621 /// Perform semantic analysis of the given friend type declaration.
16622 ///
16623 /// \returns A friend declaration that.
16624 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16625                                       SourceLocation FriendLoc,
16626                                       TypeSourceInfo *TSInfo) {
16627   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16628 
16629   QualType T = TSInfo->getType();
16630   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16631 
16632   // C++03 [class.friend]p2:
16633   //   An elaborated-type-specifier shall be used in a friend declaration
16634   //   for a class.*
16635   //
16636   //   * The class-key of the elaborated-type-specifier is required.
16637   if (!CodeSynthesisContexts.empty()) {
16638     // Do not complain about the form of friend template types during any kind
16639     // of code synthesis. For template instantiation, we will have complained
16640     // when the template was defined.
16641   } else {
16642     if (!T->isElaboratedTypeSpecifier()) {
16643       // If we evaluated the type to a record type, suggest putting
16644       // a tag in front.
16645       if (const RecordType *RT = T->getAs<RecordType>()) {
16646         RecordDecl *RD = RT->getDecl();
16647 
16648         SmallString<16> InsertionText(" ");
16649         InsertionText += RD->getKindName();
16650 
16651         Diag(TypeRange.getBegin(),
16652              getLangOpts().CPlusPlus11 ?
16653                diag::warn_cxx98_compat_unelaborated_friend_type :
16654                diag::ext_unelaborated_friend_type)
16655           << (unsigned) RD->getTagKind()
16656           << T
16657           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16658                                         InsertionText);
16659       } else {
16660         Diag(FriendLoc,
16661              getLangOpts().CPlusPlus11 ?
16662                diag::warn_cxx98_compat_nonclass_type_friend :
16663                diag::ext_nonclass_type_friend)
16664           << T
16665           << TypeRange;
16666       }
16667     } else if (T->getAs<EnumType>()) {
16668       Diag(FriendLoc,
16669            getLangOpts().CPlusPlus11 ?
16670              diag::warn_cxx98_compat_enum_friend :
16671              diag::ext_enum_friend)
16672         << T
16673         << TypeRange;
16674     }
16675 
16676     // C++11 [class.friend]p3:
16677     //   A friend declaration that does not declare a function shall have one
16678     //   of the following forms:
16679     //     friend elaborated-type-specifier ;
16680     //     friend simple-type-specifier ;
16681     //     friend typename-specifier ;
16682     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16683       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16684   }
16685 
16686   //   If the type specifier in a friend declaration designates a (possibly
16687   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16688   //   the friend declaration is ignored.
16689   return FriendDecl::Create(Context, CurContext,
16690                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16691                             FriendLoc);
16692 }
16693 
16694 /// Handle a friend tag declaration where the scope specifier was
16695 /// templated.
16696 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16697                                     unsigned TagSpec, SourceLocation TagLoc,
16698                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16699                                     SourceLocation NameLoc,
16700                                     const ParsedAttributesView &Attr,
16701                                     MultiTemplateParamsArg TempParamLists) {
16702   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16703 
16704   bool IsMemberSpecialization = false;
16705   bool Invalid = false;
16706 
16707   if (TemplateParameterList *TemplateParams =
16708           MatchTemplateParametersToScopeSpecifier(
16709               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16710               IsMemberSpecialization, Invalid)) {
16711     if (TemplateParams->size() > 0) {
16712       // This is a declaration of a class template.
16713       if (Invalid)
16714         return nullptr;
16715 
16716       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16717                                 NameLoc, Attr, TemplateParams, AS_public,
16718                                 /*ModulePrivateLoc=*/SourceLocation(),
16719                                 FriendLoc, TempParamLists.size() - 1,
16720                                 TempParamLists.data()).get();
16721     } else {
16722       // The "template<>" header is extraneous.
16723       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16724         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16725       IsMemberSpecialization = true;
16726     }
16727   }
16728 
16729   if (Invalid) return nullptr;
16730 
16731   bool isAllExplicitSpecializations = true;
16732   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16733     if (TempParamLists[I]->size()) {
16734       isAllExplicitSpecializations = false;
16735       break;
16736     }
16737   }
16738 
16739   // FIXME: don't ignore attributes.
16740 
16741   // If it's explicit specializations all the way down, just forget
16742   // about the template header and build an appropriate non-templated
16743   // friend.  TODO: for source fidelity, remember the headers.
16744   if (isAllExplicitSpecializations) {
16745     if (SS.isEmpty()) {
16746       bool Owned = false;
16747       bool IsDependent = false;
16748       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16749                       Attr, AS_public,
16750                       /*ModulePrivateLoc=*/SourceLocation(),
16751                       MultiTemplateParamsArg(), Owned, IsDependent,
16752                       /*ScopedEnumKWLoc=*/SourceLocation(),
16753                       /*ScopedEnumUsesClassTag=*/false,
16754                       /*UnderlyingType=*/TypeResult(),
16755                       /*IsTypeSpecifier=*/false,
16756                       /*IsTemplateParamOrArg=*/false);
16757     }
16758 
16759     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16760     ElaboratedTypeKeyword Keyword
16761       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16762     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16763                                    *Name, NameLoc);
16764     if (T.isNull())
16765       return nullptr;
16766 
16767     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16768     if (isa<DependentNameType>(T)) {
16769       DependentNameTypeLoc TL =
16770           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16771       TL.setElaboratedKeywordLoc(TagLoc);
16772       TL.setQualifierLoc(QualifierLoc);
16773       TL.setNameLoc(NameLoc);
16774     } else {
16775       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16776       TL.setElaboratedKeywordLoc(TagLoc);
16777       TL.setQualifierLoc(QualifierLoc);
16778       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16779     }
16780 
16781     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16782                                             TSI, FriendLoc, TempParamLists);
16783     Friend->setAccess(AS_public);
16784     CurContext->addDecl(Friend);
16785     return Friend;
16786   }
16787 
16788   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16789 
16790 
16791 
16792   // Handle the case of a templated-scope friend class.  e.g.
16793   //   template <class T> class A<T>::B;
16794   // FIXME: we don't support these right now.
16795   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16796     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16797   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16798   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16799   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16800   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16801   TL.setElaboratedKeywordLoc(TagLoc);
16802   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16803   TL.setNameLoc(NameLoc);
16804 
16805   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16806                                           TSI, FriendLoc, TempParamLists);
16807   Friend->setAccess(AS_public);
16808   Friend->setUnsupportedFriend(true);
16809   CurContext->addDecl(Friend);
16810   return Friend;
16811 }
16812 
16813 /// Handle a friend type declaration.  This works in tandem with
16814 /// ActOnTag.
16815 ///
16816 /// Notes on friend class templates:
16817 ///
16818 /// We generally treat friend class declarations as if they were
16819 /// declaring a class.  So, for example, the elaborated type specifier
16820 /// in a friend declaration is required to obey the restrictions of a
16821 /// class-head (i.e. no typedefs in the scope chain), template
16822 /// parameters are required to match up with simple template-ids, &c.
16823 /// However, unlike when declaring a template specialization, it's
16824 /// okay to refer to a template specialization without an empty
16825 /// template parameter declaration, e.g.
16826 ///   friend class A<T>::B<unsigned>;
16827 /// We permit this as a special case; if there are any template
16828 /// parameters present at all, require proper matching, i.e.
16829 ///   template <> template \<class T> friend class A<int>::B;
16830 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16831                                 MultiTemplateParamsArg TempParams) {
16832   SourceLocation Loc = DS.getBeginLoc();
16833 
16834   assert(DS.isFriendSpecified());
16835   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16836 
16837   // C++ [class.friend]p3:
16838   // A friend declaration that does not declare a function shall have one of
16839   // the following forms:
16840   //     friend elaborated-type-specifier ;
16841   //     friend simple-type-specifier ;
16842   //     friend typename-specifier ;
16843   //
16844   // Any declaration with a type qualifier does not have that form. (It's
16845   // legal to specify a qualified type as a friend, you just can't write the
16846   // keywords.)
16847   if (DS.getTypeQualifiers()) {
16848     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16849       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16850     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16851       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16852     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16853       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16854     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16855       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16856     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16857       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16858   }
16859 
16860   // Try to convert the decl specifier to a type.  This works for
16861   // friend templates because ActOnTag never produces a ClassTemplateDecl
16862   // for a TUK_Friend.
16863   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16864   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16865   QualType T = TSI->getType();
16866   if (TheDeclarator.isInvalidType())
16867     return nullptr;
16868 
16869   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16870     return nullptr;
16871 
16872   // This is definitely an error in C++98.  It's probably meant to
16873   // be forbidden in C++0x, too, but the specification is just
16874   // poorly written.
16875   //
16876   // The problem is with declarations like the following:
16877   //   template <T> friend A<T>::foo;
16878   // where deciding whether a class C is a friend or not now hinges
16879   // on whether there exists an instantiation of A that causes
16880   // 'foo' to equal C.  There are restrictions on class-heads
16881   // (which we declare (by fiat) elaborated friend declarations to
16882   // be) that makes this tractable.
16883   //
16884   // FIXME: handle "template <> friend class A<T>;", which
16885   // is possibly well-formed?  Who even knows?
16886   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16887     Diag(Loc, diag::err_tagless_friend_type_template)
16888       << DS.getSourceRange();
16889     return nullptr;
16890   }
16891 
16892   // C++98 [class.friend]p1: A friend of a class is a function
16893   //   or class that is not a member of the class . . .
16894   // This is fixed in DR77, which just barely didn't make the C++03
16895   // deadline.  It's also a very silly restriction that seriously
16896   // affects inner classes and which nobody else seems to implement;
16897   // thus we never diagnose it, not even in -pedantic.
16898   //
16899   // But note that we could warn about it: it's always useless to
16900   // friend one of your own members (it's not, however, worthless to
16901   // friend a member of an arbitrary specialization of your template).
16902 
16903   Decl *D;
16904   if (!TempParams.empty())
16905     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16906                                    TempParams,
16907                                    TSI,
16908                                    DS.getFriendSpecLoc());
16909   else
16910     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16911 
16912   if (!D)
16913     return nullptr;
16914 
16915   D->setAccess(AS_public);
16916   CurContext->addDecl(D);
16917 
16918   return D;
16919 }
16920 
16921 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16922                                         MultiTemplateParamsArg TemplateParams) {
16923   const DeclSpec &DS = D.getDeclSpec();
16924 
16925   assert(DS.isFriendSpecified());
16926   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16927 
16928   SourceLocation Loc = D.getIdentifierLoc();
16929   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16930 
16931   // C++ [class.friend]p1
16932   //   A friend of a class is a function or class....
16933   // Note that this sees through typedefs, which is intended.
16934   // It *doesn't* see through dependent types, which is correct
16935   // according to [temp.arg.type]p3:
16936   //   If a declaration acquires a function type through a
16937   //   type dependent on a template-parameter and this causes
16938   //   a declaration that does not use the syntactic form of a
16939   //   function declarator to have a function type, the program
16940   //   is ill-formed.
16941   if (!TInfo->getType()->isFunctionType()) {
16942     Diag(Loc, diag::err_unexpected_friend);
16943 
16944     // It might be worthwhile to try to recover by creating an
16945     // appropriate declaration.
16946     return nullptr;
16947   }
16948 
16949   // C++ [namespace.memdef]p3
16950   //  - If a friend declaration in a non-local class first declares a
16951   //    class or function, the friend class or function is a member
16952   //    of the innermost enclosing namespace.
16953   //  - The name of the friend is not found by simple name lookup
16954   //    until a matching declaration is provided in that namespace
16955   //    scope (either before or after the class declaration granting
16956   //    friendship).
16957   //  - If a friend function is called, its name may be found by the
16958   //    name lookup that considers functions from namespaces and
16959   //    classes associated with the types of the function arguments.
16960   //  - When looking for a prior declaration of a class or a function
16961   //    declared as a friend, scopes outside the innermost enclosing
16962   //    namespace scope are not considered.
16963 
16964   CXXScopeSpec &SS = D.getCXXScopeSpec();
16965   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16966   assert(NameInfo.getName());
16967 
16968   // Check for unexpanded parameter packs.
16969   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16970       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16971       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16972     return nullptr;
16973 
16974   // The context we found the declaration in, or in which we should
16975   // create the declaration.
16976   DeclContext *DC;
16977   Scope *DCScope = S;
16978   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16979                         ForExternalRedeclaration);
16980 
16981   // There are five cases here.
16982   //   - There's no scope specifier and we're in a local class. Only look
16983   //     for functions declared in the immediately-enclosing block scope.
16984   // We recover from invalid scope qualifiers as if they just weren't there.
16985   FunctionDecl *FunctionContainingLocalClass = nullptr;
16986   if ((SS.isInvalid() || !SS.isSet()) &&
16987       (FunctionContainingLocalClass =
16988            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16989     // C++11 [class.friend]p11:
16990     //   If a friend declaration appears in a local class and the name
16991     //   specified is an unqualified name, a prior declaration is
16992     //   looked up without considering scopes that are outside the
16993     //   innermost enclosing non-class scope. For a friend function
16994     //   declaration, if there is no prior declaration, the program is
16995     //   ill-formed.
16996 
16997     // Find the innermost enclosing non-class scope. This is the block
16998     // scope containing the local class definition (or for a nested class,
16999     // the outer local class).
17000     DCScope = S->getFnParent();
17001 
17002     // Look up the function name in the scope.
17003     Previous.clear(LookupLocalFriendName);
17004     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17005 
17006     if (!Previous.empty()) {
17007       // All possible previous declarations must have the same context:
17008       // either they were declared at block scope or they are members of
17009       // one of the enclosing local classes.
17010       DC = Previous.getRepresentativeDecl()->getDeclContext();
17011     } else {
17012       // This is ill-formed, but provide the context that we would have
17013       // declared the function in, if we were permitted to, for error recovery.
17014       DC = FunctionContainingLocalClass;
17015     }
17016     adjustContextForLocalExternDecl(DC);
17017 
17018     // C++ [class.friend]p6:
17019     //   A function can be defined in a friend declaration of a class if and
17020     //   only if the class is a non-local class (9.8), the function name is
17021     //   unqualified, and the function has namespace scope.
17022     if (D.isFunctionDefinition()) {
17023       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17024     }
17025 
17026   //   - There's no scope specifier, in which case we just go to the
17027   //     appropriate scope and look for a function or function template
17028   //     there as appropriate.
17029   } else if (SS.isInvalid() || !SS.isSet()) {
17030     // C++11 [namespace.memdef]p3:
17031     //   If the name in a friend declaration is neither qualified nor
17032     //   a template-id and the declaration is a function or an
17033     //   elaborated-type-specifier, the lookup to determine whether
17034     //   the entity has been previously declared shall not consider
17035     //   any scopes outside the innermost enclosing namespace.
17036     bool isTemplateId =
17037         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17038 
17039     // Find the appropriate context according to the above.
17040     DC = CurContext;
17041 
17042     // Skip class contexts.  If someone can cite chapter and verse
17043     // for this behavior, that would be nice --- it's what GCC and
17044     // EDG do, and it seems like a reasonable intent, but the spec
17045     // really only says that checks for unqualified existing
17046     // declarations should stop at the nearest enclosing namespace,
17047     // not that they should only consider the nearest enclosing
17048     // namespace.
17049     while (DC->isRecord())
17050       DC = DC->getParent();
17051 
17052     DeclContext *LookupDC = DC->getNonTransparentContext();
17053     while (true) {
17054       LookupQualifiedName(Previous, LookupDC);
17055 
17056       if (!Previous.empty()) {
17057         DC = LookupDC;
17058         break;
17059       }
17060 
17061       if (isTemplateId) {
17062         if (isa<TranslationUnitDecl>(LookupDC)) break;
17063       } else {
17064         if (LookupDC->isFileContext()) break;
17065       }
17066       LookupDC = LookupDC->getParent();
17067     }
17068 
17069     DCScope = getScopeForDeclContext(S, DC);
17070 
17071   //   - There's a non-dependent scope specifier, in which case we
17072   //     compute it and do a previous lookup there for a function
17073   //     or function template.
17074   } else if (!SS.getScopeRep()->isDependent()) {
17075     DC = computeDeclContext(SS);
17076     if (!DC) return nullptr;
17077 
17078     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17079 
17080     LookupQualifiedName(Previous, DC);
17081 
17082     // C++ [class.friend]p1: A friend of a class is a function or
17083     //   class that is not a member of the class . . .
17084     if (DC->Equals(CurContext))
17085       Diag(DS.getFriendSpecLoc(),
17086            getLangOpts().CPlusPlus11 ?
17087              diag::warn_cxx98_compat_friend_is_member :
17088              diag::err_friend_is_member);
17089 
17090     if (D.isFunctionDefinition()) {
17091       // C++ [class.friend]p6:
17092       //   A function can be defined in a friend declaration of a class if and
17093       //   only if the class is a non-local class (9.8), the function name is
17094       //   unqualified, and the function has namespace scope.
17095       //
17096       // FIXME: We should only do this if the scope specifier names the
17097       // innermost enclosing namespace; otherwise the fixit changes the
17098       // meaning of the code.
17099       SemaDiagnosticBuilder DB
17100         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17101 
17102       DB << SS.getScopeRep();
17103       if (DC->isFileContext())
17104         DB << FixItHint::CreateRemoval(SS.getRange());
17105       SS.clear();
17106     }
17107 
17108   //   - There's a scope specifier that does not match any template
17109   //     parameter lists, in which case we use some arbitrary context,
17110   //     create a method or method template, and wait for instantiation.
17111   //   - There's a scope specifier that does match some template
17112   //     parameter lists, which we don't handle right now.
17113   } else {
17114     if (D.isFunctionDefinition()) {
17115       // C++ [class.friend]p6:
17116       //   A function can be defined in a friend declaration of a class if and
17117       //   only if the class is a non-local class (9.8), the function name is
17118       //   unqualified, and the function has namespace scope.
17119       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17120         << SS.getScopeRep();
17121     }
17122 
17123     DC = CurContext;
17124     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17125   }
17126 
17127   if (!DC->isRecord()) {
17128     int DiagArg = -1;
17129     switch (D.getName().getKind()) {
17130     case UnqualifiedIdKind::IK_ConstructorTemplateId:
17131     case UnqualifiedIdKind::IK_ConstructorName:
17132       DiagArg = 0;
17133       break;
17134     case UnqualifiedIdKind::IK_DestructorName:
17135       DiagArg = 1;
17136       break;
17137     case UnqualifiedIdKind::IK_ConversionFunctionId:
17138       DiagArg = 2;
17139       break;
17140     case UnqualifiedIdKind::IK_DeductionGuideName:
17141       DiagArg = 3;
17142       break;
17143     case UnqualifiedIdKind::IK_Identifier:
17144     case UnqualifiedIdKind::IK_ImplicitSelfParam:
17145     case UnqualifiedIdKind::IK_LiteralOperatorId:
17146     case UnqualifiedIdKind::IK_OperatorFunctionId:
17147     case UnqualifiedIdKind::IK_TemplateId:
17148       break;
17149     }
17150     // This implies that it has to be an operator or function.
17151     if (DiagArg >= 0) {
17152       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17153       return nullptr;
17154     }
17155   }
17156 
17157   // FIXME: This is an egregious hack to cope with cases where the scope stack
17158   // does not contain the declaration context, i.e., in an out-of-line
17159   // definition of a class.
17160   Scope FakeDCScope(S, Scope::DeclScope, Diags);
17161   if (!DCScope) {
17162     FakeDCScope.setEntity(DC);
17163     DCScope = &FakeDCScope;
17164   }
17165 
17166   bool AddToScope = true;
17167   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17168                                           TemplateParams, AddToScope);
17169   if (!ND) return nullptr;
17170 
17171   assert(ND->getLexicalDeclContext() == CurContext);
17172 
17173   // If we performed typo correction, we might have added a scope specifier
17174   // and changed the decl context.
17175   DC = ND->getDeclContext();
17176 
17177   // Add the function declaration to the appropriate lookup tables,
17178   // adjusting the redeclarations list as necessary.  We don't
17179   // want to do this yet if the friending class is dependent.
17180   //
17181   // Also update the scope-based lookup if the target context's
17182   // lookup context is in lexical scope.
17183   if (!CurContext->isDependentContext()) {
17184     DC = DC->getRedeclContext();
17185     DC->makeDeclVisibleInContext(ND);
17186     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17187       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17188   }
17189 
17190   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17191                                        D.getIdentifierLoc(), ND,
17192                                        DS.getFriendSpecLoc());
17193   FrD->setAccess(AS_public);
17194   CurContext->addDecl(FrD);
17195 
17196   if (ND->isInvalidDecl()) {
17197     FrD->setInvalidDecl();
17198   } else {
17199     if (DC->isRecord()) CheckFriendAccess(ND);
17200 
17201     FunctionDecl *FD;
17202     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17203       FD = FTD->getTemplatedDecl();
17204     else
17205       FD = cast<FunctionDecl>(ND);
17206 
17207     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17208     // default argument expression, that declaration shall be a definition
17209     // and shall be the only declaration of the function or function
17210     // template in the translation unit.
17211     if (functionDeclHasDefaultArgument(FD)) {
17212       // We can't look at FD->getPreviousDecl() because it may not have been set
17213       // if we're in a dependent context. If the function is known to be a
17214       // redeclaration, we will have narrowed Previous down to the right decl.
17215       if (D.isRedeclaration()) {
17216         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17217         Diag(Previous.getRepresentativeDecl()->getLocation(),
17218              diag::note_previous_declaration);
17219       } else if (!D.isFunctionDefinition())
17220         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17221     }
17222 
17223     // Mark templated-scope function declarations as unsupported.
17224     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17225       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17226         << SS.getScopeRep() << SS.getRange()
17227         << cast<CXXRecordDecl>(CurContext);
17228       FrD->setUnsupportedFriend(true);
17229     }
17230   }
17231 
17232   warnOnReservedIdentifier(ND);
17233 
17234   return ND;
17235 }
17236 
17237 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17238   AdjustDeclIfTemplate(Dcl);
17239 
17240   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17241   if (!Fn) {
17242     Diag(DelLoc, diag::err_deleted_non_function);
17243     return;
17244   }
17245 
17246   // Deleted function does not have a body.
17247   Fn->setWillHaveBody(false);
17248 
17249   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17250     // Don't consider the implicit declaration we generate for explicit
17251     // specializations. FIXME: Do not generate these implicit declarations.
17252     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17253          Prev->getPreviousDecl()) &&
17254         !Prev->isDefined()) {
17255       Diag(DelLoc, diag::err_deleted_decl_not_first);
17256       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17257            Prev->isImplicit() ? diag::note_previous_implicit_declaration
17258                               : diag::note_previous_declaration);
17259       // We can't recover from this; the declaration might have already
17260       // been used.
17261       Fn->setInvalidDecl();
17262       return;
17263     }
17264 
17265     // To maintain the invariant that functions are only deleted on their first
17266     // declaration, mark the implicitly-instantiated declaration of the
17267     // explicitly-specialized function as deleted instead of marking the
17268     // instantiated redeclaration.
17269     Fn = Fn->getCanonicalDecl();
17270   }
17271 
17272   // dllimport/dllexport cannot be deleted.
17273   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17274     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17275     Fn->setInvalidDecl();
17276   }
17277 
17278   // C++11 [basic.start.main]p3:
17279   //   A program that defines main as deleted [...] is ill-formed.
17280   if (Fn->isMain())
17281     Diag(DelLoc, diag::err_deleted_main);
17282 
17283   // C++11 [dcl.fct.def.delete]p4:
17284   //  A deleted function is implicitly inline.
17285   Fn->setImplicitlyInline();
17286   Fn->setDeletedAsWritten();
17287 }
17288 
17289 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17290   if (!Dcl || Dcl->isInvalidDecl())
17291     return;
17292 
17293   auto *FD = dyn_cast<FunctionDecl>(Dcl);
17294   if (!FD) {
17295     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17296       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17297         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17298         return;
17299       }
17300     }
17301 
17302     Diag(DefaultLoc, diag::err_default_special_members)
17303         << getLangOpts().CPlusPlus20;
17304     return;
17305   }
17306 
17307   // Reject if this can't possibly be a defaultable function.
17308   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17309   if (!DefKind &&
17310       // A dependent function that doesn't locally look defaultable can
17311       // still instantiate to a defaultable function if it's a constructor
17312       // or assignment operator.
17313       (!FD->isDependentContext() ||
17314        (!isa<CXXConstructorDecl>(FD) &&
17315         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17316     Diag(DefaultLoc, diag::err_default_special_members)
17317         << getLangOpts().CPlusPlus20;
17318     return;
17319   }
17320 
17321   // Issue compatibility warning. We already warned if the operator is
17322   // 'operator<=>' when parsing the '<=>' token.
17323   if (DefKind.isComparison() &&
17324       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17325     Diag(DefaultLoc, getLangOpts().CPlusPlus20
17326                          ? diag::warn_cxx17_compat_defaulted_comparison
17327                          : diag::ext_defaulted_comparison);
17328   }
17329 
17330   FD->setDefaulted();
17331   FD->setExplicitlyDefaulted();
17332 
17333   // Defer checking functions that are defaulted in a dependent context.
17334   if (FD->isDependentContext())
17335     return;
17336 
17337   // Unset that we will have a body for this function. We might not,
17338   // if it turns out to be trivial, and we don't need this marking now
17339   // that we've marked it as defaulted.
17340   FD->setWillHaveBody(false);
17341 
17342   if (DefKind.isComparison()) {
17343     // If this comparison's defaulting occurs within the definition of its
17344     // lexical class context, we have to do the checking when complete.
17345     if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17346       if (!RD->isCompleteDefinition())
17347         return;
17348   }
17349 
17350   // If this member fn was defaulted on its first declaration, we will have
17351   // already performed the checking in CheckCompletedCXXClass. Such a
17352   // declaration doesn't trigger an implicit definition.
17353   if (isa<CXXMethodDecl>(FD)) {
17354     const FunctionDecl *Primary = FD;
17355     if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17356       // Ask the template instantiation pattern that actually had the
17357       // '= default' on it.
17358       Primary = Pattern;
17359     if (Primary->getCanonicalDecl()->isDefaulted())
17360       return;
17361   }
17362 
17363   if (DefKind.isComparison()) {
17364     if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17365       FD->setInvalidDecl();
17366     else
17367       DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17368   } else {
17369     auto *MD = cast<CXXMethodDecl>(FD);
17370 
17371     if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
17372       MD->setInvalidDecl();
17373     else
17374       DefineDefaultedFunction(*this, MD, DefaultLoc);
17375   }
17376 }
17377 
17378 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17379   for (Stmt *SubStmt : S->children()) {
17380     if (!SubStmt)
17381       continue;
17382     if (isa<ReturnStmt>(SubStmt))
17383       Self.Diag(SubStmt->getBeginLoc(),
17384                 diag::err_return_in_constructor_handler);
17385     if (!isa<Expr>(SubStmt))
17386       SearchForReturnInStmt(Self, SubStmt);
17387   }
17388 }
17389 
17390 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17391   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17392     CXXCatchStmt *Handler = TryBlock->getHandler(I);
17393     SearchForReturnInStmt(*this, Handler);
17394   }
17395 }
17396 
17397 void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
17398                                FnBodyKind BodyKind) {
17399   switch (BodyKind) {
17400   case FnBodyKind::Delete:
17401     SetDeclDeleted(D, Loc);
17402     break;
17403   case FnBodyKind::Default:
17404     SetDeclDefaulted(D, Loc);
17405     break;
17406   case FnBodyKind::Other:
17407     llvm_unreachable(
17408         "Parsed function body should be '= delete;' or '= default;'");
17409   }
17410 }
17411 
17412 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17413                                              const CXXMethodDecl *Old) {
17414   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17415   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17416 
17417   if (OldFT->hasExtParameterInfos()) {
17418     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17419       // A parameter of the overriding method should be annotated with noescape
17420       // if the corresponding parameter of the overridden method is annotated.
17421       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17422           !NewFT->getExtParameterInfo(I).isNoEscape()) {
17423         Diag(New->getParamDecl(I)->getLocation(),
17424              diag::warn_overriding_method_missing_noescape);
17425         Diag(Old->getParamDecl(I)->getLocation(),
17426              diag::note_overridden_marked_noescape);
17427       }
17428   }
17429 
17430   // Virtual overrides must have the same code_seg.
17431   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17432   const auto *NewCSA = New->getAttr<CodeSegAttr>();
17433   if ((NewCSA || OldCSA) &&
17434       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17435     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17436     Diag(Old->getLocation(), diag::note_previous_declaration);
17437     return true;
17438   }
17439 
17440   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17441 
17442   // If the calling conventions match, everything is fine
17443   if (NewCC == OldCC)
17444     return false;
17445 
17446   // If the calling conventions mismatch because the new function is static,
17447   // suppress the calling convention mismatch error; the error about static
17448   // function override (err_static_overrides_virtual from
17449   // Sema::CheckFunctionDeclaration) is more clear.
17450   if (New->getStorageClass() == SC_Static)
17451     return false;
17452 
17453   Diag(New->getLocation(),
17454        diag::err_conflicting_overriding_cc_attributes)
17455     << New->getDeclName() << New->getType() << Old->getType();
17456   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17457   return true;
17458 }
17459 
17460 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17461                                              const CXXMethodDecl *Old) {
17462   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17463   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17464 
17465   if (Context.hasSameType(NewTy, OldTy) ||
17466       NewTy->isDependentType() || OldTy->isDependentType())
17467     return false;
17468 
17469   // Check if the return types are covariant
17470   QualType NewClassTy, OldClassTy;
17471 
17472   /// Both types must be pointers or references to classes.
17473   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17474     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17475       NewClassTy = NewPT->getPointeeType();
17476       OldClassTy = OldPT->getPointeeType();
17477     }
17478   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17479     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17480       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17481         NewClassTy = NewRT->getPointeeType();
17482         OldClassTy = OldRT->getPointeeType();
17483       }
17484     }
17485   }
17486 
17487   // The return types aren't either both pointers or references to a class type.
17488   if (NewClassTy.isNull()) {
17489     Diag(New->getLocation(),
17490          diag::err_different_return_type_for_overriding_virtual_function)
17491         << New->getDeclName() << NewTy << OldTy
17492         << New->getReturnTypeSourceRange();
17493     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17494         << Old->getReturnTypeSourceRange();
17495 
17496     return true;
17497   }
17498 
17499   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17500     // C++14 [class.virtual]p8:
17501     //   If the class type in the covariant return type of D::f differs from
17502     //   that of B::f, the class type in the return type of D::f shall be
17503     //   complete at the point of declaration of D::f or shall be the class
17504     //   type D.
17505     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17506       if (!RT->isBeingDefined() &&
17507           RequireCompleteType(New->getLocation(), NewClassTy,
17508                               diag::err_covariant_return_incomplete,
17509                               New->getDeclName()))
17510         return true;
17511     }
17512 
17513     // Check if the new class derives from the old class.
17514     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17515       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17516           << New->getDeclName() << NewTy << OldTy
17517           << New->getReturnTypeSourceRange();
17518       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17519           << Old->getReturnTypeSourceRange();
17520       return true;
17521     }
17522 
17523     // Check if we the conversion from derived to base is valid.
17524     if (CheckDerivedToBaseConversion(
17525             NewClassTy, OldClassTy,
17526             diag::err_covariant_return_inaccessible_base,
17527             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17528             New->getLocation(), New->getReturnTypeSourceRange(),
17529             New->getDeclName(), nullptr)) {
17530       // FIXME: this note won't trigger for delayed access control
17531       // diagnostics, and it's impossible to get an undelayed error
17532       // here from access control during the original parse because
17533       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17534       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17535           << Old->getReturnTypeSourceRange();
17536       return true;
17537     }
17538   }
17539 
17540   // The qualifiers of the return types must be the same.
17541   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17542     Diag(New->getLocation(),
17543          diag::err_covariant_return_type_different_qualifications)
17544         << New->getDeclName() << NewTy << OldTy
17545         << New->getReturnTypeSourceRange();
17546     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17547         << Old->getReturnTypeSourceRange();
17548     return true;
17549   }
17550 
17551 
17552   // The new class type must have the same or less qualifiers as the old type.
17553   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17554     Diag(New->getLocation(),
17555          diag::err_covariant_return_type_class_type_more_qualified)
17556         << New->getDeclName() << NewTy << OldTy
17557         << New->getReturnTypeSourceRange();
17558     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17559         << Old->getReturnTypeSourceRange();
17560     return true;
17561   }
17562 
17563   return false;
17564 }
17565 
17566 /// Mark the given method pure.
17567 ///
17568 /// \param Method the method to be marked pure.
17569 ///
17570 /// \param InitRange the source range that covers the "0" initializer.
17571 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17572   SourceLocation EndLoc = InitRange.getEnd();
17573   if (EndLoc.isValid())
17574     Method->setRangeEnd(EndLoc);
17575 
17576   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17577     Method->setPure();
17578     return false;
17579   }
17580 
17581   if (!Method->isInvalidDecl())
17582     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17583       << Method->getDeclName() << InitRange;
17584   return true;
17585 }
17586 
17587 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17588   if (D->getFriendObjectKind())
17589     Diag(D->getLocation(), diag::err_pure_friend);
17590   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17591     CheckPureMethod(M, ZeroLoc);
17592   else
17593     Diag(D->getLocation(), diag::err_illegal_initializer);
17594 }
17595 
17596 /// Determine whether the given declaration is a global variable or
17597 /// static data member.
17598 static bool isNonlocalVariable(const Decl *D) {
17599   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17600     return Var->hasGlobalStorage();
17601 
17602   return false;
17603 }
17604 
17605 /// Invoked when we are about to parse an initializer for the declaration
17606 /// 'Dcl'.
17607 ///
17608 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17609 /// static data member of class X, names should be looked up in the scope of
17610 /// class X. If the declaration had a scope specifier, a scope will have
17611 /// been created and passed in for this purpose. Otherwise, S will be null.
17612 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17613   // If there is no declaration, there was an error parsing it.
17614   if (!D || D->isInvalidDecl())
17615     return;
17616 
17617   // We will always have a nested name specifier here, but this declaration
17618   // might not be out of line if the specifier names the current namespace:
17619   //   extern int n;
17620   //   int ::n = 0;
17621   if (S && D->isOutOfLine())
17622     EnterDeclaratorContext(S, D->getDeclContext());
17623 
17624   // If we are parsing the initializer for a static data member, push a
17625   // new expression evaluation context that is associated with this static
17626   // data member.
17627   if (isNonlocalVariable(D))
17628     PushExpressionEvaluationContext(
17629         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17630 }
17631 
17632 /// Invoked after we are finished parsing an initializer for the declaration D.
17633 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17634   // If there is no declaration, there was an error parsing it.
17635   if (!D || D->isInvalidDecl())
17636     return;
17637 
17638   if (isNonlocalVariable(D))
17639     PopExpressionEvaluationContext();
17640 
17641   if (S && D->isOutOfLine())
17642     ExitDeclaratorContext(S);
17643 }
17644 
17645 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17646 /// C++ if/switch/while/for statement.
17647 /// e.g: "if (int x = f()) {...}"
17648 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17649   // C++ 6.4p2:
17650   // The declarator shall not specify a function or an array.
17651   // The type-specifier-seq shall not contain typedef and shall not declare a
17652   // new class or enumeration.
17653   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17654          "Parser allowed 'typedef' as storage class of condition decl.");
17655 
17656   Decl *Dcl = ActOnDeclarator(S, D);
17657   if (!Dcl)
17658     return true;
17659 
17660   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17661     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17662       << D.getSourceRange();
17663     return true;
17664   }
17665 
17666   return Dcl;
17667 }
17668 
17669 void Sema::LoadExternalVTableUses() {
17670   if (!ExternalSource)
17671     return;
17672 
17673   SmallVector<ExternalVTableUse, 4> VTables;
17674   ExternalSource->ReadUsedVTables(VTables);
17675   SmallVector<VTableUse, 4> NewUses;
17676   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17677     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17678       = VTablesUsed.find(VTables[I].Record);
17679     // Even if a definition wasn't required before, it may be required now.
17680     if (Pos != VTablesUsed.end()) {
17681       if (!Pos->second && VTables[I].DefinitionRequired)
17682         Pos->second = true;
17683       continue;
17684     }
17685 
17686     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17687     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17688   }
17689 
17690   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17691 }
17692 
17693 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17694                           bool DefinitionRequired) {
17695   // Ignore any vtable uses in unevaluated operands or for classes that do
17696   // not have a vtable.
17697   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17698       CurContext->isDependentContext() || isUnevaluatedContext())
17699     return;
17700   // Do not mark as used if compiling for the device outside of the target
17701   // region.
17702   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17703       !isInOpenMPDeclareTargetContext() &&
17704       !isInOpenMPTargetExecutionDirective()) {
17705     if (!DefinitionRequired)
17706       MarkVirtualMembersReferenced(Loc, Class);
17707     return;
17708   }
17709 
17710   // Try to insert this class into the map.
17711   LoadExternalVTableUses();
17712   Class = Class->getCanonicalDecl();
17713   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17714     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17715   if (!Pos.second) {
17716     // If we already had an entry, check to see if we are promoting this vtable
17717     // to require a definition. If so, we need to reappend to the VTableUses
17718     // list, since we may have already processed the first entry.
17719     if (DefinitionRequired && !Pos.first->second) {
17720       Pos.first->second = true;
17721     } else {
17722       // Otherwise, we can early exit.
17723       return;
17724     }
17725   } else {
17726     // The Microsoft ABI requires that we perform the destructor body
17727     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17728     // the deleting destructor is emitted with the vtable, not with the
17729     // destructor definition as in the Itanium ABI.
17730     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17731       CXXDestructorDecl *DD = Class->getDestructor();
17732       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17733         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17734           // If this is an out-of-line declaration, marking it referenced will
17735           // not do anything. Manually call CheckDestructor to look up operator
17736           // delete().
17737           ContextRAII SavedContext(*this, DD);
17738           CheckDestructor(DD);
17739         } else {
17740           MarkFunctionReferenced(Loc, Class->getDestructor());
17741         }
17742       }
17743     }
17744   }
17745 
17746   // Local classes need to have their virtual members marked
17747   // immediately. For all other classes, we mark their virtual members
17748   // at the end of the translation unit.
17749   if (Class->isLocalClass())
17750     MarkVirtualMembersReferenced(Loc, Class);
17751   else
17752     VTableUses.push_back(std::make_pair(Class, Loc));
17753 }
17754 
17755 bool Sema::DefineUsedVTables() {
17756   LoadExternalVTableUses();
17757   if (VTableUses.empty())
17758     return false;
17759 
17760   // Note: The VTableUses vector could grow as a result of marking
17761   // the members of a class as "used", so we check the size each
17762   // time through the loop and prefer indices (which are stable) to
17763   // iterators (which are not).
17764   bool DefinedAnything = false;
17765   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17766     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17767     if (!Class)
17768       continue;
17769     TemplateSpecializationKind ClassTSK =
17770         Class->getTemplateSpecializationKind();
17771 
17772     SourceLocation Loc = VTableUses[I].second;
17773 
17774     bool DefineVTable = true;
17775 
17776     // If this class has a key function, but that key function is
17777     // defined in another translation unit, we don't need to emit the
17778     // vtable even though we're using it.
17779     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17780     if (KeyFunction && !KeyFunction->hasBody()) {
17781       // The key function is in another translation unit.
17782       DefineVTable = false;
17783       TemplateSpecializationKind TSK =
17784           KeyFunction->getTemplateSpecializationKind();
17785       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17786              TSK != TSK_ImplicitInstantiation &&
17787              "Instantiations don't have key functions");
17788       (void)TSK;
17789     } else if (!KeyFunction) {
17790       // If we have a class with no key function that is the subject
17791       // of an explicit instantiation declaration, suppress the
17792       // vtable; it will live with the explicit instantiation
17793       // definition.
17794       bool IsExplicitInstantiationDeclaration =
17795           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17796       for (auto R : Class->redecls()) {
17797         TemplateSpecializationKind TSK
17798           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17799         if (TSK == TSK_ExplicitInstantiationDeclaration)
17800           IsExplicitInstantiationDeclaration = true;
17801         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17802           IsExplicitInstantiationDeclaration = false;
17803           break;
17804         }
17805       }
17806 
17807       if (IsExplicitInstantiationDeclaration)
17808         DefineVTable = false;
17809     }
17810 
17811     // The exception specifications for all virtual members may be needed even
17812     // if we are not providing an authoritative form of the vtable in this TU.
17813     // We may choose to emit it available_externally anyway.
17814     if (!DefineVTable) {
17815       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17816       continue;
17817     }
17818 
17819     // Mark all of the virtual members of this class as referenced, so
17820     // that we can build a vtable. Then, tell the AST consumer that a
17821     // vtable for this class is required.
17822     DefinedAnything = true;
17823     MarkVirtualMembersReferenced(Loc, Class);
17824     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17825     if (VTablesUsed[Canonical])
17826       Consumer.HandleVTable(Class);
17827 
17828     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17829     // no key function or the key function is inlined. Don't warn in C++ ABIs
17830     // that lack key functions, since the user won't be able to make one.
17831     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17832         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
17833         ClassTSK != TSK_ExplicitInstantiationDefinition) {
17834       const FunctionDecl *KeyFunctionDef = nullptr;
17835       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17836                            KeyFunctionDef->isInlined()))
17837         Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
17838     }
17839   }
17840   VTableUses.clear();
17841 
17842   return DefinedAnything;
17843 }
17844 
17845 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17846                                                  const CXXRecordDecl *RD) {
17847   for (const auto *I : RD->methods())
17848     if (I->isVirtual() && !I->isPure())
17849       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17850 }
17851 
17852 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17853                                         const CXXRecordDecl *RD,
17854                                         bool ConstexprOnly) {
17855   // Mark all functions which will appear in RD's vtable as used.
17856   CXXFinalOverriderMap FinalOverriders;
17857   RD->getFinalOverriders(FinalOverriders);
17858   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17859                                             E = FinalOverriders.end();
17860        I != E; ++I) {
17861     for (OverridingMethods::const_iterator OI = I->second.begin(),
17862                                            OE = I->second.end();
17863          OI != OE; ++OI) {
17864       assert(OI->second.size() > 0 && "no final overrider");
17865       CXXMethodDecl *Overrider = OI->second.front().Method;
17866 
17867       // C++ [basic.def.odr]p2:
17868       //   [...] A virtual member function is used if it is not pure. [...]
17869       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17870         MarkFunctionReferenced(Loc, Overrider);
17871     }
17872   }
17873 
17874   // Only classes that have virtual bases need a VTT.
17875   if (RD->getNumVBases() == 0)
17876     return;
17877 
17878   for (const auto &I : RD->bases()) {
17879     const auto *Base =
17880         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17881     if (Base->getNumVBases() == 0)
17882       continue;
17883     MarkVirtualMembersReferenced(Loc, Base);
17884   }
17885 }
17886 
17887 /// SetIvarInitializers - This routine builds initialization ASTs for the
17888 /// Objective-C implementation whose ivars need be initialized.
17889 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17890   if (!getLangOpts().CPlusPlus)
17891     return;
17892   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17893     SmallVector<ObjCIvarDecl*, 8> ivars;
17894     CollectIvarsToConstructOrDestruct(OID, ivars);
17895     if (ivars.empty())
17896       return;
17897     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17898     for (unsigned i = 0; i < ivars.size(); i++) {
17899       FieldDecl *Field = ivars[i];
17900       if (Field->isInvalidDecl())
17901         continue;
17902 
17903       CXXCtorInitializer *Member;
17904       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17905       InitializationKind InitKind =
17906         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17907 
17908       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17909       ExprResult MemberInit =
17910         InitSeq.Perform(*this, InitEntity, InitKind, None);
17911       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17912       // Note, MemberInit could actually come back empty if no initialization
17913       // is required (e.g., because it would call a trivial default constructor)
17914       if (!MemberInit.get() || MemberInit.isInvalid())
17915         continue;
17916 
17917       Member =
17918         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17919                                          SourceLocation(),
17920                                          MemberInit.getAs<Expr>(),
17921                                          SourceLocation());
17922       AllToInit.push_back(Member);
17923 
17924       // Be sure that the destructor is accessible and is marked as referenced.
17925       if (const RecordType *RecordTy =
17926               Context.getBaseElementType(Field->getType())
17927                   ->getAs<RecordType>()) {
17928         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17929         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17930           MarkFunctionReferenced(Field->getLocation(), Destructor);
17931           CheckDestructorAccess(Field->getLocation(), Destructor,
17932                             PDiag(diag::err_access_dtor_ivar)
17933                               << Context.getBaseElementType(Field->getType()));
17934         }
17935       }
17936     }
17937     ObjCImplementation->setIvarInitializers(Context,
17938                                             AllToInit.data(), AllToInit.size());
17939   }
17940 }
17941 
17942 static
17943 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17944                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17945                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17946                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17947                            Sema &S) {
17948   if (Ctor->isInvalidDecl())
17949     return;
17950 
17951   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17952 
17953   // Target may not be determinable yet, for instance if this is a dependent
17954   // call in an uninstantiated template.
17955   if (Target) {
17956     const FunctionDecl *FNTarget = nullptr;
17957     (void)Target->hasBody(FNTarget);
17958     Target = const_cast<CXXConstructorDecl*>(
17959       cast_or_null<CXXConstructorDecl>(FNTarget));
17960   }
17961 
17962   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17963                      // Avoid dereferencing a null pointer here.
17964                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17965 
17966   if (!Current.insert(Canonical).second)
17967     return;
17968 
17969   // We know that beyond here, we aren't chaining into a cycle.
17970   if (!Target || !Target->isDelegatingConstructor() ||
17971       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17972     Valid.insert(Current.begin(), Current.end());
17973     Current.clear();
17974   // We've hit a cycle.
17975   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17976              Current.count(TCanonical)) {
17977     // If we haven't diagnosed this cycle yet, do so now.
17978     if (!Invalid.count(TCanonical)) {
17979       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17980              diag::warn_delegating_ctor_cycle)
17981         << Ctor;
17982 
17983       // Don't add a note for a function delegating directly to itself.
17984       if (TCanonical != Canonical)
17985         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17986 
17987       CXXConstructorDecl *C = Target;
17988       while (C->getCanonicalDecl() != Canonical) {
17989         const FunctionDecl *FNTarget = nullptr;
17990         (void)C->getTargetConstructor()->hasBody(FNTarget);
17991         assert(FNTarget && "Ctor cycle through bodiless function");
17992 
17993         C = const_cast<CXXConstructorDecl*>(
17994           cast<CXXConstructorDecl>(FNTarget));
17995         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17996       }
17997     }
17998 
17999     Invalid.insert(Current.begin(), Current.end());
18000     Current.clear();
18001   } else {
18002     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18003   }
18004 }
18005 
18006 
18007 void Sema::CheckDelegatingCtorCycles() {
18008   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18009 
18010   for (DelegatingCtorDeclsType::iterator
18011          I = DelegatingCtorDecls.begin(ExternalSource),
18012          E = DelegatingCtorDecls.end();
18013        I != E; ++I)
18014     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18015 
18016   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18017     (*CI)->setInvalidDecl();
18018 }
18019 
18020 namespace {
18021   /// AST visitor that finds references to the 'this' expression.
18022   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18023     Sema &S;
18024 
18025   public:
18026     explicit FindCXXThisExpr(Sema &S) : S(S) { }
18027 
18028     bool VisitCXXThisExpr(CXXThisExpr *E) {
18029       S.Diag(E->getLocation(), diag::err_this_static_member_func)
18030         << E->isImplicit();
18031       return false;
18032     }
18033   };
18034 }
18035 
18036 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18037   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18038   if (!TSInfo)
18039     return false;
18040 
18041   TypeLoc TL = TSInfo->getTypeLoc();
18042   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18043   if (!ProtoTL)
18044     return false;
18045 
18046   // C++11 [expr.prim.general]p3:
18047   //   [The expression this] shall not appear before the optional
18048   //   cv-qualifier-seq and it shall not appear within the declaration of a
18049   //   static member function (although its type and value category are defined
18050   //   within a static member function as they are within a non-static member
18051   //   function). [ Note: this is because declaration matching does not occur
18052   //  until the complete declarator is known. - end note ]
18053   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18054   FindCXXThisExpr Finder(*this);
18055 
18056   // If the return type came after the cv-qualifier-seq, check it now.
18057   if (Proto->hasTrailingReturn() &&
18058       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18059     return true;
18060 
18061   // Check the exception specification.
18062   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18063     return true;
18064 
18065   // Check the trailing requires clause
18066   if (Expr *E = Method->getTrailingRequiresClause())
18067     if (!Finder.TraverseStmt(E))
18068       return true;
18069 
18070   return checkThisInStaticMemberFunctionAttributes(Method);
18071 }
18072 
18073 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18074   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18075   if (!TSInfo)
18076     return false;
18077 
18078   TypeLoc TL = TSInfo->getTypeLoc();
18079   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18080   if (!ProtoTL)
18081     return false;
18082 
18083   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18084   FindCXXThisExpr Finder(*this);
18085 
18086   switch (Proto->getExceptionSpecType()) {
18087   case EST_Unparsed:
18088   case EST_Uninstantiated:
18089   case EST_Unevaluated:
18090   case EST_BasicNoexcept:
18091   case EST_NoThrow:
18092   case EST_DynamicNone:
18093   case EST_MSAny:
18094   case EST_None:
18095     break;
18096 
18097   case EST_DependentNoexcept:
18098   case EST_NoexceptFalse:
18099   case EST_NoexceptTrue:
18100     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18101       return true;
18102     LLVM_FALLTHROUGH;
18103 
18104   case EST_Dynamic:
18105     for (const auto &E : Proto->exceptions()) {
18106       if (!Finder.TraverseType(E))
18107         return true;
18108     }
18109     break;
18110   }
18111 
18112   return false;
18113 }
18114 
18115 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
18116   FindCXXThisExpr Finder(*this);
18117 
18118   // Check attributes.
18119   for (const auto *A : Method->attrs()) {
18120     // FIXME: This should be emitted by tblgen.
18121     Expr *Arg = nullptr;
18122     ArrayRef<Expr *> Args;
18123     if (const auto *G = dyn_cast<GuardedByAttr>(A))
18124       Arg = G->getArg();
18125     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18126       Arg = G->getArg();
18127     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18128       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
18129     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18130       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
18131     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18132       Arg = ETLF->getSuccessValue();
18133       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
18134     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18135       Arg = STLF->getSuccessValue();
18136       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
18137     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18138       Arg = LR->getArg();
18139     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18140       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
18141     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18142       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18143     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18144       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18145     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18146       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18147     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18148       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18149 
18150     if (Arg && !Finder.TraverseStmt(Arg))
18151       return true;
18152 
18153     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18154       if (!Finder.TraverseStmt(Args[I]))
18155         return true;
18156     }
18157   }
18158 
18159   return false;
18160 }
18161 
18162 void Sema::checkExceptionSpecification(
18163     bool IsTopLevel, ExceptionSpecificationType EST,
18164     ArrayRef<ParsedType> DynamicExceptions,
18165     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18166     SmallVectorImpl<QualType> &Exceptions,
18167     FunctionProtoType::ExceptionSpecInfo &ESI) {
18168   Exceptions.clear();
18169   ESI.Type = EST;
18170   if (EST == EST_Dynamic) {
18171     Exceptions.reserve(DynamicExceptions.size());
18172     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18173       // FIXME: Preserve type source info.
18174       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18175 
18176       if (IsTopLevel) {
18177         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
18178         collectUnexpandedParameterPacks(ET, Unexpanded);
18179         if (!Unexpanded.empty()) {
18180           DiagnoseUnexpandedParameterPacks(
18181               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18182               Unexpanded);
18183           continue;
18184         }
18185       }
18186 
18187       // Check that the type is valid for an exception spec, and
18188       // drop it if not.
18189       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18190         Exceptions.push_back(ET);
18191     }
18192     ESI.Exceptions = Exceptions;
18193     return;
18194   }
18195 
18196   if (isComputedNoexcept(EST)) {
18197     assert((NoexceptExpr->isTypeDependent() ||
18198             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18199             Context.BoolTy) &&
18200            "Parser should have made sure that the expression is boolean");
18201     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18202       ESI.Type = EST_BasicNoexcept;
18203       return;
18204     }
18205 
18206     ESI.NoexceptExpr = NoexceptExpr;
18207     return;
18208   }
18209 }
18210 
18211 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
18212              ExceptionSpecificationType EST,
18213              SourceRange SpecificationRange,
18214              ArrayRef<ParsedType> DynamicExceptions,
18215              ArrayRef<SourceRange> DynamicExceptionRanges,
18216              Expr *NoexceptExpr) {
18217   if (!MethodD)
18218     return;
18219 
18220   // Dig out the method we're referring to.
18221   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18222     MethodD = FunTmpl->getTemplatedDecl();
18223 
18224   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18225   if (!Method)
18226     return;
18227 
18228   // Check the exception specification.
18229   llvm::SmallVector<QualType, 4> Exceptions;
18230   FunctionProtoType::ExceptionSpecInfo ESI;
18231   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18232                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
18233                               ESI);
18234 
18235   // Update the exception specification on the function type.
18236   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18237 
18238   if (Method->isStatic())
18239     checkThisInStaticMemberFunctionExceptionSpec(Method);
18240 
18241   if (Method->isVirtual()) {
18242     // Check overrides, which we previously had to delay.
18243     for (const CXXMethodDecl *O : Method->overridden_methods())
18244       CheckOverridingFunctionExceptionSpec(Method, O);
18245   }
18246 }
18247 
18248 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18249 ///
18250 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18251                                        SourceLocation DeclStart, Declarator &D,
18252                                        Expr *BitWidth,
18253                                        InClassInitStyle InitStyle,
18254                                        AccessSpecifier AS,
18255                                        const ParsedAttr &MSPropertyAttr) {
18256   IdentifierInfo *II = D.getIdentifier();
18257   if (!II) {
18258     Diag(DeclStart, diag::err_anonymous_property);
18259     return nullptr;
18260   }
18261   SourceLocation Loc = D.getIdentifierLoc();
18262 
18263   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18264   QualType T = TInfo->getType();
18265   if (getLangOpts().CPlusPlus) {
18266     CheckExtraCXXDefaultArguments(D);
18267 
18268     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18269                                         UPPC_DataMemberType)) {
18270       D.setInvalidType();
18271       T = Context.IntTy;
18272       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18273     }
18274   }
18275 
18276   DiagnoseFunctionSpecifiers(D.getDeclSpec());
18277 
18278   if (D.getDeclSpec().isInlineSpecified())
18279     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18280         << getLangOpts().CPlusPlus17;
18281   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18282     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18283          diag::err_invalid_thread)
18284       << DeclSpec::getSpecifierName(TSCS);
18285 
18286   // Check to see if this name was declared as a member previously
18287   NamedDecl *PrevDecl = nullptr;
18288   LookupResult Previous(*this, II, Loc, LookupMemberName,
18289                         ForVisibleRedeclaration);
18290   LookupName(Previous, S);
18291   switch (Previous.getResultKind()) {
18292   case LookupResult::Found:
18293   case LookupResult::FoundUnresolvedValue:
18294     PrevDecl = Previous.getAsSingle<NamedDecl>();
18295     break;
18296 
18297   case LookupResult::FoundOverloaded:
18298     PrevDecl = Previous.getRepresentativeDecl();
18299     break;
18300 
18301   case LookupResult::NotFound:
18302   case LookupResult::NotFoundInCurrentInstantiation:
18303   case LookupResult::Ambiguous:
18304     break;
18305   }
18306 
18307   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18308     // Maybe we will complain about the shadowed template parameter.
18309     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18310     // Just pretend that we didn't see the previous declaration.
18311     PrevDecl = nullptr;
18312   }
18313 
18314   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18315     PrevDecl = nullptr;
18316 
18317   SourceLocation TSSL = D.getBeginLoc();
18318   MSPropertyDecl *NewPD =
18319       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18320                              MSPropertyAttr.getPropertyDataGetter(),
18321                              MSPropertyAttr.getPropertyDataSetter());
18322   ProcessDeclAttributes(TUScope, NewPD, D);
18323   NewPD->setAccess(AS);
18324 
18325   if (NewPD->isInvalidDecl())
18326     Record->setInvalidDecl();
18327 
18328   if (D.getDeclSpec().isModulePrivateSpecified())
18329     NewPD->setModulePrivate();
18330 
18331   if (NewPD->isInvalidDecl() && PrevDecl) {
18332     // Don't introduce NewFD into scope; there's already something
18333     // with the same name in the same scope.
18334   } else if (II) {
18335     PushOnScopeChains(NewPD, S);
18336   } else
18337     Record->addDecl(NewPD);
18338 
18339   return NewPD;
18340 }
18341 
18342 void Sema::ActOnStartFunctionDeclarationDeclarator(
18343     Declarator &Declarator, unsigned TemplateParameterDepth) {
18344   auto &Info = InventedParameterInfos.emplace_back();
18345   TemplateParameterList *ExplicitParams = nullptr;
18346   ArrayRef<TemplateParameterList *> ExplicitLists =
18347       Declarator.getTemplateParameterLists();
18348   if (!ExplicitLists.empty()) {
18349     bool IsMemberSpecialization, IsInvalid;
18350     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18351         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18352         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18353         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18354         /*SuppressDiagnostic=*/true);
18355   }
18356   if (ExplicitParams) {
18357     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18358     llvm::append_range(Info.TemplateParams, *ExplicitParams);
18359     Info.NumExplicitTemplateParams = ExplicitParams->size();
18360   } else {
18361     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18362     Info.NumExplicitTemplateParams = 0;
18363   }
18364 }
18365 
18366 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18367   auto &FSI = InventedParameterInfos.back();
18368   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18369     if (FSI.NumExplicitTemplateParams != 0) {
18370       TemplateParameterList *ExplicitParams =
18371           Declarator.getTemplateParameterLists().back();
18372       Declarator.setInventedTemplateParameterList(
18373           TemplateParameterList::Create(
18374               Context, ExplicitParams->getTemplateLoc(),
18375               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18376               ExplicitParams->getRAngleLoc(),
18377               ExplicitParams->getRequiresClause()));
18378     } else {
18379       Declarator.setInventedTemplateParameterList(
18380           TemplateParameterList::Create(
18381               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18382               SourceLocation(), /*RequiresClause=*/nullptr));
18383     }
18384   }
18385   InventedParameterInfos.pop_back();
18386 }
18387