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,
5434              [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; });
5435 
5436   // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5437   // emit the diagnostic before we can try adding notes.
5438   {
5439     Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5440         Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5441         WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5442                                 : diag::warn_some_initializers_out_of_order);
5443 
5444     for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5445       if (CorrelatedInitOrder[I].second == I)
5446         continue;
5447       // Ideally we would be using InsertFromRange here, but clang doesn't
5448       // appear to handle InsertFromRange correctly when the source range is
5449       // modified by another fix-it.
5450       D << FixItHint::CreateReplacement(
5451           Inits[I]->getSourceRange(),
5452           Lexer::getSourceText(
5453               CharSourceRange::getTokenRange(
5454                   Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5455               SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5456     }
5457 
5458     // If there is only 1 item out of order, the warning expects the name and
5459     // type of each being added to it.
5460     if (WarnIndexes.size() == 1) {
5461       AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5462                            Inits[WarnIndexes.front()]);
5463       return;
5464     }
5465   }
5466   // More than 1 item to warn, create notes letting the user know which ones
5467   // are bad.
5468   for (unsigned WarnIndex : WarnIndexes) {
5469     const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5470     auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5471                           diag::note_initializer_out_of_order);
5472     AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5473     D << PrevInit->getSourceRange();
5474   }
5475 }
5476 
5477 namespace {
5478 bool CheckRedundantInit(Sema &S,
5479                         CXXCtorInitializer *Init,
5480                         CXXCtorInitializer *&PrevInit) {
5481   if (!PrevInit) {
5482     PrevInit = Init;
5483     return false;
5484   }
5485 
5486   if (FieldDecl *Field = Init->getAnyMember())
5487     S.Diag(Init->getSourceLocation(),
5488            diag::err_multiple_mem_initialization)
5489       << Field->getDeclName()
5490       << Init->getSourceRange();
5491   else {
5492     const Type *BaseClass = Init->getBaseClass();
5493     assert(BaseClass && "neither field nor base");
5494     S.Diag(Init->getSourceLocation(),
5495            diag::err_multiple_base_initialization)
5496       << QualType(BaseClass, 0)
5497       << Init->getSourceRange();
5498   }
5499   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5500     << 0 << PrevInit->getSourceRange();
5501 
5502   return true;
5503 }
5504 
5505 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5506 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5507 
5508 bool CheckRedundantUnionInit(Sema &S,
5509                              CXXCtorInitializer *Init,
5510                              RedundantUnionMap &Unions) {
5511   FieldDecl *Field = Init->getAnyMember();
5512   RecordDecl *Parent = Field->getParent();
5513   NamedDecl *Child = Field;
5514 
5515   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5516     if (Parent->isUnion()) {
5517       UnionEntry &En = Unions[Parent];
5518       if (En.first && En.first != Child) {
5519         S.Diag(Init->getSourceLocation(),
5520                diag::err_multiple_mem_union_initialization)
5521           << Field->getDeclName()
5522           << Init->getSourceRange();
5523         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5524           << 0 << En.second->getSourceRange();
5525         return true;
5526       }
5527       if (!En.first) {
5528         En.first = Child;
5529         En.second = Init;
5530       }
5531       if (!Parent->isAnonymousStructOrUnion())
5532         return false;
5533     }
5534 
5535     Child = Parent;
5536     Parent = cast<RecordDecl>(Parent->getDeclContext());
5537   }
5538 
5539   return false;
5540 }
5541 } // namespace
5542 
5543 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5544 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5545                                 SourceLocation ColonLoc,
5546                                 ArrayRef<CXXCtorInitializer*> MemInits,
5547                                 bool AnyErrors) {
5548   if (!ConstructorDecl)
5549     return;
5550 
5551   AdjustDeclIfTemplate(ConstructorDecl);
5552 
5553   CXXConstructorDecl *Constructor
5554     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5555 
5556   if (!Constructor) {
5557     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5558     return;
5559   }
5560 
5561   // Mapping for the duplicate initializers check.
5562   // For member initializers, this is keyed with a FieldDecl*.
5563   // For base initializers, this is keyed with a Type*.
5564   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5565 
5566   // Mapping for the inconsistent anonymous-union initializers check.
5567   RedundantUnionMap MemberUnions;
5568 
5569   bool HadError = false;
5570   for (unsigned i = 0; i < MemInits.size(); i++) {
5571     CXXCtorInitializer *Init = MemInits[i];
5572 
5573     // Set the source order index.
5574     Init->setSourceOrder(i);
5575 
5576     if (Init->isAnyMemberInitializer()) {
5577       const void *Key = GetKeyForMember(Context, Init);
5578       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5579           CheckRedundantUnionInit(*this, Init, MemberUnions))
5580         HadError = true;
5581     } else if (Init->isBaseInitializer()) {
5582       const void *Key = GetKeyForMember(Context, Init);
5583       if (CheckRedundantInit(*this, Init, Members[Key]))
5584         HadError = true;
5585     } else {
5586       assert(Init->isDelegatingInitializer());
5587       // This must be the only initializer
5588       if (MemInits.size() != 1) {
5589         Diag(Init->getSourceLocation(),
5590              diag::err_delegating_initializer_alone)
5591           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5592         // We will treat this as being the only initializer.
5593       }
5594       SetDelegatingInitializer(Constructor, MemInits[i]);
5595       // Return immediately as the initializer is set.
5596       return;
5597     }
5598   }
5599 
5600   if (HadError)
5601     return;
5602 
5603   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5604 
5605   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5606 
5607   DiagnoseUninitializedFields(*this, Constructor);
5608 }
5609 
5610 void
5611 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5612                                              CXXRecordDecl *ClassDecl) {
5613   // Ignore dependent contexts. Also ignore unions, since their members never
5614   // have destructors implicitly called.
5615   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5616     return;
5617 
5618   // FIXME: all the access-control diagnostics are positioned on the
5619   // field/base declaration.  That's probably good; that said, the
5620   // user might reasonably want to know why the destructor is being
5621   // emitted, and we currently don't say.
5622 
5623   // Non-static data members.
5624   for (auto *Field : ClassDecl->fields()) {
5625     if (Field->isInvalidDecl())
5626       continue;
5627 
5628     // Don't destroy incomplete or zero-length arrays.
5629     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5630       continue;
5631 
5632     QualType FieldType = Context.getBaseElementType(Field->getType());
5633 
5634     const RecordType* RT = FieldType->getAs<RecordType>();
5635     if (!RT)
5636       continue;
5637 
5638     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5639     if (FieldClassDecl->isInvalidDecl())
5640       continue;
5641     if (FieldClassDecl->hasIrrelevantDestructor())
5642       continue;
5643     // The destructor for an implicit anonymous union member is never invoked.
5644     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5645       continue;
5646 
5647     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5648     assert(Dtor && "No dtor found for FieldClassDecl!");
5649     CheckDestructorAccess(Field->getLocation(), Dtor,
5650                           PDiag(diag::err_access_dtor_field)
5651                             << Field->getDeclName()
5652                             << FieldType);
5653 
5654     MarkFunctionReferenced(Location, Dtor);
5655     DiagnoseUseOfDecl(Dtor, Location);
5656   }
5657 
5658   // We only potentially invoke the destructors of potentially constructed
5659   // subobjects.
5660   bool VisitVirtualBases = !ClassDecl->isAbstract();
5661 
5662   // If the destructor exists and has already been marked used in the MS ABI,
5663   // then virtual base destructors have already been checked and marked used.
5664   // Skip checking them again to avoid duplicate diagnostics.
5665   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5666     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5667     if (Dtor && Dtor->isUsed())
5668       VisitVirtualBases = false;
5669   }
5670 
5671   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5672 
5673   // Bases.
5674   for (const auto &Base : ClassDecl->bases()) {
5675     const RecordType *RT = Base.getType()->getAs<RecordType>();
5676     if (!RT)
5677       continue;
5678 
5679     // Remember direct virtual bases.
5680     if (Base.isVirtual()) {
5681       if (!VisitVirtualBases)
5682         continue;
5683       DirectVirtualBases.insert(RT);
5684     }
5685 
5686     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5687     // If our base class is invalid, we probably can't get its dtor anyway.
5688     if (BaseClassDecl->isInvalidDecl())
5689       continue;
5690     if (BaseClassDecl->hasIrrelevantDestructor())
5691       continue;
5692 
5693     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5694     assert(Dtor && "No dtor found for BaseClassDecl!");
5695 
5696     // FIXME: caret should be on the start of the class name
5697     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5698                           PDiag(diag::err_access_dtor_base)
5699                               << Base.getType() << Base.getSourceRange(),
5700                           Context.getTypeDeclType(ClassDecl));
5701 
5702     MarkFunctionReferenced(Location, Dtor);
5703     DiagnoseUseOfDecl(Dtor, Location);
5704   }
5705 
5706   if (VisitVirtualBases)
5707     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5708                                          &DirectVirtualBases);
5709 }
5710 
5711 void Sema::MarkVirtualBaseDestructorsReferenced(
5712     SourceLocation Location, CXXRecordDecl *ClassDecl,
5713     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5714   // Virtual bases.
5715   for (const auto &VBase : ClassDecl->vbases()) {
5716     // Bases are always records in a well-formed non-dependent class.
5717     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5718 
5719     // Ignore already visited direct virtual bases.
5720     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5721       continue;
5722 
5723     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5724     // If our base class is invalid, we probably can't get its dtor anyway.
5725     if (BaseClassDecl->isInvalidDecl())
5726       continue;
5727     if (BaseClassDecl->hasIrrelevantDestructor())
5728       continue;
5729 
5730     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5731     assert(Dtor && "No dtor found for BaseClassDecl!");
5732     if (CheckDestructorAccess(
5733             ClassDecl->getLocation(), Dtor,
5734             PDiag(diag::err_access_dtor_vbase)
5735                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5736             Context.getTypeDeclType(ClassDecl)) ==
5737         AR_accessible) {
5738       CheckDerivedToBaseConversion(
5739           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5740           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5741           SourceRange(), DeclarationName(), nullptr);
5742     }
5743 
5744     MarkFunctionReferenced(Location, Dtor);
5745     DiagnoseUseOfDecl(Dtor, Location);
5746   }
5747 }
5748 
5749 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5750   if (!CDtorDecl)
5751     return;
5752 
5753   if (CXXConstructorDecl *Constructor
5754       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5755     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5756     DiagnoseUninitializedFields(*this, Constructor);
5757   }
5758 }
5759 
5760 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5761   if (!getLangOpts().CPlusPlus)
5762     return false;
5763 
5764   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5765   if (!RD)
5766     return false;
5767 
5768   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5769   // class template specialization here, but doing so breaks a lot of code.
5770 
5771   // We can't answer whether something is abstract until it has a
5772   // definition. If it's currently being defined, we'll walk back
5773   // over all the declarations when we have a full definition.
5774   const CXXRecordDecl *Def = RD->getDefinition();
5775   if (!Def || Def->isBeingDefined())
5776     return false;
5777 
5778   return RD->isAbstract();
5779 }
5780 
5781 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5782                                   TypeDiagnoser &Diagnoser) {
5783   if (!isAbstractType(Loc, T))
5784     return false;
5785 
5786   T = Context.getBaseElementType(T);
5787   Diagnoser.diagnose(*this, Loc, T);
5788   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5789   return true;
5790 }
5791 
5792 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5793   // Check if we've already emitted the list of pure virtual functions
5794   // for this class.
5795   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5796     return;
5797 
5798   // If the diagnostic is suppressed, don't emit the notes. We're only
5799   // going to emit them once, so try to attach them to a diagnostic we're
5800   // actually going to show.
5801   if (Diags.isLastDiagnosticIgnored())
5802     return;
5803 
5804   CXXFinalOverriderMap FinalOverriders;
5805   RD->getFinalOverriders(FinalOverriders);
5806 
5807   // Keep a set of seen pure methods so we won't diagnose the same method
5808   // more than once.
5809   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5810 
5811   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5812                                    MEnd = FinalOverriders.end();
5813        M != MEnd;
5814        ++M) {
5815     for (OverridingMethods::iterator SO = M->second.begin(),
5816                                   SOEnd = M->second.end();
5817          SO != SOEnd; ++SO) {
5818       // C++ [class.abstract]p4:
5819       //   A class is abstract if it contains or inherits at least one
5820       //   pure virtual function for which the final overrider is pure
5821       //   virtual.
5822 
5823       //
5824       if (SO->second.size() != 1)
5825         continue;
5826 
5827       if (!SO->second.front().Method->isPure())
5828         continue;
5829 
5830       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5831         continue;
5832 
5833       Diag(SO->second.front().Method->getLocation(),
5834            diag::note_pure_virtual_function)
5835         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5836     }
5837   }
5838 
5839   if (!PureVirtualClassDiagSet)
5840     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5841   PureVirtualClassDiagSet->insert(RD);
5842 }
5843 
5844 namespace {
5845 struct AbstractUsageInfo {
5846   Sema &S;
5847   CXXRecordDecl *Record;
5848   CanQualType AbstractType;
5849   bool Invalid;
5850 
5851   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5852     : S(S), Record(Record),
5853       AbstractType(S.Context.getCanonicalType(
5854                    S.Context.getTypeDeclType(Record))),
5855       Invalid(false) {}
5856 
5857   void DiagnoseAbstractType() {
5858     if (Invalid) return;
5859     S.DiagnoseAbstractType(Record);
5860     Invalid = true;
5861   }
5862 
5863   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5864 };
5865 
5866 struct CheckAbstractUsage {
5867   AbstractUsageInfo &Info;
5868   const NamedDecl *Ctx;
5869 
5870   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5871     : Info(Info), Ctx(Ctx) {}
5872 
5873   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5874     switch (TL.getTypeLocClass()) {
5875 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5876 #define TYPELOC(CLASS, PARENT) \
5877     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5878 #include "clang/AST/TypeLocNodes.def"
5879     }
5880   }
5881 
5882   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5883     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5884     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5885       if (!TL.getParam(I))
5886         continue;
5887 
5888       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5889       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5890     }
5891   }
5892 
5893   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5894     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5895   }
5896 
5897   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5898     // Visit the type parameters from a permissive context.
5899     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5900       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5901       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5902         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5903           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5904       // TODO: other template argument types?
5905     }
5906   }
5907 
5908   // Visit pointee types from a permissive context.
5909 #define CheckPolymorphic(Type) \
5910   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5911     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5912   }
5913   CheckPolymorphic(PointerTypeLoc)
5914   CheckPolymorphic(ReferenceTypeLoc)
5915   CheckPolymorphic(MemberPointerTypeLoc)
5916   CheckPolymorphic(BlockPointerTypeLoc)
5917   CheckPolymorphic(AtomicTypeLoc)
5918 
5919   /// Handle all the types we haven't given a more specific
5920   /// implementation for above.
5921   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5922     // Every other kind of type that we haven't called out already
5923     // that has an inner type is either (1) sugar or (2) contains that
5924     // inner type in some way as a subobject.
5925     if (TypeLoc Next = TL.getNextTypeLoc())
5926       return Visit(Next, Sel);
5927 
5928     // If there's no inner type and we're in a permissive context,
5929     // don't diagnose.
5930     if (Sel == Sema::AbstractNone) return;
5931 
5932     // Check whether the type matches the abstract type.
5933     QualType T = TL.getType();
5934     if (T->isArrayType()) {
5935       Sel = Sema::AbstractArrayType;
5936       T = Info.S.Context.getBaseElementType(T);
5937     }
5938     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5939     if (CT != Info.AbstractType) return;
5940 
5941     // It matched; do some magic.
5942     // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
5943     if (Sel == Sema::AbstractArrayType) {
5944       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5945         << T << TL.getSourceRange();
5946     } else {
5947       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5948         << Sel << T << TL.getSourceRange();
5949     }
5950     Info.DiagnoseAbstractType();
5951   }
5952 };
5953 
5954 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5955                                   Sema::AbstractDiagSelID Sel) {
5956   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5957 }
5958 
5959 }
5960 
5961 /// Check for invalid uses of an abstract type in a function declaration.
5962 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5963                                     FunctionDecl *FD) {
5964   // No need to do the check on definitions, which require that
5965   // the return/param types be complete.
5966   if (FD->doesThisDeclarationHaveABody())
5967     return;
5968 
5969   // For safety's sake, just ignore it if we don't have type source
5970   // information.  This should never happen for non-implicit methods,
5971   // but...
5972   if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5973     Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
5974 }
5975 
5976 /// Check for invalid uses of an abstract type in a variable0 declaration.
5977 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5978                                     VarDecl *VD) {
5979   // No need to do the check on definitions, which require that
5980   // the type is complete.
5981   if (VD->isThisDeclarationADefinition())
5982     return;
5983 
5984   Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
5985                  Sema::AbstractVariableType);
5986 }
5987 
5988 /// Check for invalid uses of an abstract type within a class definition.
5989 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5990                                     CXXRecordDecl *RD) {
5991   for (auto *D : RD->decls()) {
5992     if (D->isImplicit()) continue;
5993 
5994     // Step through friends to the befriended declaration.
5995     if (auto *FD = dyn_cast<FriendDecl>(D)) {
5996       D = FD->getFriendDecl();
5997       if (!D) continue;
5998     }
5999 
6000     // Functions and function templates.
6001     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6002       CheckAbstractClassUsage(Info, FD);
6003     } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
6004       CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
6005 
6006     // Fields and static variables.
6007     } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6008       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6009         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6010     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6011       CheckAbstractClassUsage(Info, VD);
6012     } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6013       CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6014 
6015     // Nested classes and class templates.
6016     } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6017       CheckAbstractClassUsage(Info, RD);
6018     } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6019       CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6020     }
6021   }
6022 }
6023 
6024 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6025   Attr *ClassAttr = getDLLAttr(Class);
6026   if (!ClassAttr)
6027     return;
6028 
6029   assert(ClassAttr->getKind() == attr::DLLExport);
6030 
6031   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6032 
6033   if (TSK == TSK_ExplicitInstantiationDeclaration)
6034     // Don't go any further if this is just an explicit instantiation
6035     // declaration.
6036     return;
6037 
6038   // Add a context note to explain how we got to any diagnostics produced below.
6039   struct MarkingClassDllexported {
6040     Sema &S;
6041     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6042                             SourceLocation AttrLoc)
6043         : S(S) {
6044       Sema::CodeSynthesisContext Ctx;
6045       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6046       Ctx.PointOfInstantiation = AttrLoc;
6047       Ctx.Entity = Class;
6048       S.pushCodeSynthesisContext(Ctx);
6049     }
6050     ~MarkingClassDllexported() {
6051       S.popCodeSynthesisContext();
6052     }
6053   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6054 
6055   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6056     S.MarkVTableUsed(Class->getLocation(), Class, true);
6057 
6058   for (Decl *Member : Class->decls()) {
6059     // Skip members that were not marked exported.
6060     if (!Member->hasAttr<DLLExportAttr>())
6061       continue;
6062 
6063     // Defined static variables that are members of an exported base
6064     // class must be marked export too.
6065     auto *VD = dyn_cast<VarDecl>(Member);
6066     if (VD && VD->getStorageClass() == SC_Static &&
6067         TSK == TSK_ImplicitInstantiation)
6068       S.MarkVariableReferenced(VD->getLocation(), VD);
6069 
6070     auto *MD = dyn_cast<CXXMethodDecl>(Member);
6071     if (!MD)
6072       continue;
6073 
6074     if (MD->isUserProvided()) {
6075       // Instantiate non-default class member functions ...
6076 
6077       // .. except for certain kinds of template specializations.
6078       if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6079         continue;
6080 
6081       // If this is an MS ABI dllexport default constructor, instantiate any
6082       // default arguments.
6083       if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6084         auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6085         if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6086           S.InstantiateDefaultCtorDefaultArgs(CD);
6087         }
6088       }
6089 
6090       S.MarkFunctionReferenced(Class->getLocation(), MD);
6091 
6092       // The function will be passed to the consumer when its definition is
6093       // encountered.
6094     } else if (MD->isExplicitlyDefaulted()) {
6095       // Synthesize and instantiate explicitly defaulted methods.
6096       S.MarkFunctionReferenced(Class->getLocation(), MD);
6097 
6098       if (TSK != TSK_ExplicitInstantiationDefinition) {
6099         // Except for explicit instantiation defs, we will not see the
6100         // definition again later, so pass it to the consumer now.
6101         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6102       }
6103     } else if (!MD->isTrivial() ||
6104                MD->isCopyAssignmentOperator() ||
6105                MD->isMoveAssignmentOperator()) {
6106       // Synthesize and instantiate non-trivial implicit methods, and the copy
6107       // and move assignment operators. The latter are exported even if they
6108       // are trivial, because the address of an operator can be taken and
6109       // should compare equal across libraries.
6110       S.MarkFunctionReferenced(Class->getLocation(), MD);
6111 
6112       // There is no later point when we will see the definition of this
6113       // function, so pass it to the consumer now.
6114       S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6115     }
6116   }
6117 }
6118 
6119 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6120                                                         CXXRecordDecl *Class) {
6121   // Only the MS ABI has default constructor closures, so we don't need to do
6122   // this semantic checking anywhere else.
6123   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6124     return;
6125 
6126   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6127   for (Decl *Member : Class->decls()) {
6128     // Look for exported default constructors.
6129     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6130     if (!CD || !CD->isDefaultConstructor())
6131       continue;
6132     auto *Attr = CD->getAttr<DLLExportAttr>();
6133     if (!Attr)
6134       continue;
6135 
6136     // If the class is non-dependent, mark the default arguments as ODR-used so
6137     // that we can properly codegen the constructor closure.
6138     if (!Class->isDependentContext()) {
6139       for (ParmVarDecl *PD : CD->parameters()) {
6140         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6141         S.DiscardCleanupsInEvaluationContext();
6142       }
6143     }
6144 
6145     if (LastExportedDefaultCtor) {
6146       S.Diag(LastExportedDefaultCtor->getLocation(),
6147              diag::err_attribute_dll_ambiguous_default_ctor)
6148           << Class;
6149       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6150           << CD->getDeclName();
6151       return;
6152     }
6153     LastExportedDefaultCtor = CD;
6154   }
6155 }
6156 
6157 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6158                                                        CXXRecordDecl *Class) {
6159   bool ErrorReported = false;
6160   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6161                                                      ClassTemplateDecl *TD) {
6162     if (ErrorReported)
6163       return;
6164     S.Diag(TD->getLocation(),
6165            diag::err_cuda_device_builtin_surftex_cls_template)
6166         << /*surface*/ 0 << TD;
6167     ErrorReported = true;
6168   };
6169 
6170   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6171   if (!TD) {
6172     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6173     if (!SD) {
6174       S.Diag(Class->getLocation(),
6175              diag::err_cuda_device_builtin_surftex_ref_decl)
6176           << /*surface*/ 0 << Class;
6177       S.Diag(Class->getLocation(),
6178              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6179           << Class;
6180       return;
6181     }
6182     TD = SD->getSpecializedTemplate();
6183   }
6184 
6185   TemplateParameterList *Params = TD->getTemplateParameters();
6186   unsigned N = Params->size();
6187 
6188   if (N != 2) {
6189     reportIllegalClassTemplate(S, TD);
6190     S.Diag(TD->getLocation(),
6191            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6192         << TD << 2;
6193   }
6194   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6195     reportIllegalClassTemplate(S, TD);
6196     S.Diag(TD->getLocation(),
6197            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6198         << TD << /*1st*/ 0 << /*type*/ 0;
6199   }
6200   if (N > 1) {
6201     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6202     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6203       reportIllegalClassTemplate(S, TD);
6204       S.Diag(TD->getLocation(),
6205              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6206           << TD << /*2nd*/ 1 << /*integer*/ 1;
6207     }
6208   }
6209 }
6210 
6211 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6212                                                        CXXRecordDecl *Class) {
6213   bool ErrorReported = false;
6214   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6215                                                      ClassTemplateDecl *TD) {
6216     if (ErrorReported)
6217       return;
6218     S.Diag(TD->getLocation(),
6219            diag::err_cuda_device_builtin_surftex_cls_template)
6220         << /*texture*/ 1 << TD;
6221     ErrorReported = true;
6222   };
6223 
6224   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6225   if (!TD) {
6226     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6227     if (!SD) {
6228       S.Diag(Class->getLocation(),
6229              diag::err_cuda_device_builtin_surftex_ref_decl)
6230           << /*texture*/ 1 << Class;
6231       S.Diag(Class->getLocation(),
6232              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6233           << Class;
6234       return;
6235     }
6236     TD = SD->getSpecializedTemplate();
6237   }
6238 
6239   TemplateParameterList *Params = TD->getTemplateParameters();
6240   unsigned N = Params->size();
6241 
6242   if (N != 3) {
6243     reportIllegalClassTemplate(S, TD);
6244     S.Diag(TD->getLocation(),
6245            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6246         << TD << 3;
6247   }
6248   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6249     reportIllegalClassTemplate(S, TD);
6250     S.Diag(TD->getLocation(),
6251            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6252         << TD << /*1st*/ 0 << /*type*/ 0;
6253   }
6254   if (N > 1) {
6255     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6256     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6257       reportIllegalClassTemplate(S, TD);
6258       S.Diag(TD->getLocation(),
6259              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6260           << TD << /*2nd*/ 1 << /*integer*/ 1;
6261     }
6262   }
6263   if (N > 2) {
6264     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6265     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6266       reportIllegalClassTemplate(S, TD);
6267       S.Diag(TD->getLocation(),
6268              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6269           << TD << /*3rd*/ 2 << /*integer*/ 1;
6270     }
6271   }
6272 }
6273 
6274 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6275   // Mark any compiler-generated routines with the implicit code_seg attribute.
6276   for (auto *Method : Class->methods()) {
6277     if (Method->isUserProvided())
6278       continue;
6279     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6280       Method->addAttr(A);
6281   }
6282 }
6283 
6284 /// Check class-level dllimport/dllexport attribute.
6285 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6286   Attr *ClassAttr = getDLLAttr(Class);
6287 
6288   // MSVC inherits DLL attributes to partial class template specializations.
6289   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6290     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6291       if (Attr *TemplateAttr =
6292               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6293         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6294         A->setInherited(true);
6295         ClassAttr = A;
6296       }
6297     }
6298   }
6299 
6300   if (!ClassAttr)
6301     return;
6302 
6303   if (!Class->isExternallyVisible()) {
6304     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6305         << Class << ClassAttr;
6306     return;
6307   }
6308 
6309   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6310       !ClassAttr->isInherited()) {
6311     // Diagnose dll attributes on members of class with dll attribute.
6312     for (Decl *Member : Class->decls()) {
6313       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6314         continue;
6315       InheritableAttr *MemberAttr = getDLLAttr(Member);
6316       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6317         continue;
6318 
6319       Diag(MemberAttr->getLocation(),
6320              diag::err_attribute_dll_member_of_dll_class)
6321           << MemberAttr << ClassAttr;
6322       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6323       Member->setInvalidDecl();
6324     }
6325   }
6326 
6327   if (Class->getDescribedClassTemplate())
6328     // Don't inherit dll attribute until the template is instantiated.
6329     return;
6330 
6331   // The class is either imported or exported.
6332   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6333 
6334   // Check if this was a dllimport attribute propagated from a derived class to
6335   // a base class template specialization. We don't apply these attributes to
6336   // static data members.
6337   const bool PropagatedImport =
6338       !ClassExported &&
6339       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6340 
6341   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6342 
6343   // Ignore explicit dllexport on explicit class template instantiation
6344   // declarations, except in MinGW mode.
6345   if (ClassExported && !ClassAttr->isInherited() &&
6346       TSK == TSK_ExplicitInstantiationDeclaration &&
6347       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6348     Class->dropAttr<DLLExportAttr>();
6349     return;
6350   }
6351 
6352   // Force declaration of implicit members so they can inherit the attribute.
6353   ForceDeclarationOfImplicitMembers(Class);
6354 
6355   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6356   // seem to be true in practice?
6357 
6358   for (Decl *Member : Class->decls()) {
6359     VarDecl *VD = dyn_cast<VarDecl>(Member);
6360     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6361 
6362     // Only methods and static fields inherit the attributes.
6363     if (!VD && !MD)
6364       continue;
6365 
6366     if (MD) {
6367       // Don't process deleted methods.
6368       if (MD->isDeleted())
6369         continue;
6370 
6371       if (MD->isInlined()) {
6372         // MinGW does not import or export inline methods. But do it for
6373         // template instantiations.
6374         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6375             TSK != TSK_ExplicitInstantiationDeclaration &&
6376             TSK != TSK_ExplicitInstantiationDefinition)
6377           continue;
6378 
6379         // MSVC versions before 2015 don't export the move assignment operators
6380         // and move constructor, so don't attempt to import/export them if
6381         // we have a definition.
6382         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6383         if ((MD->isMoveAssignmentOperator() ||
6384              (Ctor && Ctor->isMoveConstructor())) &&
6385             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6386           continue;
6387 
6388         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6389         // operator is exported anyway.
6390         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6391             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6392           continue;
6393       }
6394     }
6395 
6396     // Don't apply dllimport attributes to static data members of class template
6397     // instantiations when the attribute is propagated from a derived class.
6398     if (VD && PropagatedImport)
6399       continue;
6400 
6401     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6402       continue;
6403 
6404     if (!getDLLAttr(Member)) {
6405       InheritableAttr *NewAttr = nullptr;
6406 
6407       // Do not export/import inline function when -fno-dllexport-inlines is
6408       // passed. But add attribute for later local static var check.
6409       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6410           TSK != TSK_ExplicitInstantiationDeclaration &&
6411           TSK != TSK_ExplicitInstantiationDefinition) {
6412         if (ClassExported) {
6413           NewAttr = ::new (getASTContext())
6414               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6415         } else {
6416           NewAttr = ::new (getASTContext())
6417               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6418         }
6419       } else {
6420         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6421       }
6422 
6423       NewAttr->setInherited(true);
6424       Member->addAttr(NewAttr);
6425 
6426       if (MD) {
6427         // Propagate DLLAttr to friend re-declarations of MD that have already
6428         // been constructed.
6429         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6430              FD = FD->getPreviousDecl()) {
6431           if (FD->getFriendObjectKind() == Decl::FOK_None)
6432             continue;
6433           assert(!getDLLAttr(FD) &&
6434                  "friend re-decl should not already have a DLLAttr");
6435           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6436           NewAttr->setInherited(true);
6437           FD->addAttr(NewAttr);
6438         }
6439       }
6440     }
6441   }
6442 
6443   if (ClassExported)
6444     DelayedDllExportClasses.push_back(Class);
6445 }
6446 
6447 /// Perform propagation of DLL attributes from a derived class to a
6448 /// templated base class for MS compatibility.
6449 void Sema::propagateDLLAttrToBaseClassTemplate(
6450     CXXRecordDecl *Class, Attr *ClassAttr,
6451     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6452   if (getDLLAttr(
6453           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6454     // If the base class template has a DLL attribute, don't try to change it.
6455     return;
6456   }
6457 
6458   auto TSK = BaseTemplateSpec->getSpecializationKind();
6459   if (!getDLLAttr(BaseTemplateSpec) &&
6460       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6461        TSK == TSK_ImplicitInstantiation)) {
6462     // The template hasn't been instantiated yet (or it has, but only as an
6463     // explicit instantiation declaration or implicit instantiation, which means
6464     // we haven't codegenned any members yet), so propagate the attribute.
6465     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6466     NewAttr->setInherited(true);
6467     BaseTemplateSpec->addAttr(NewAttr);
6468 
6469     // If this was an import, mark that we propagated it from a derived class to
6470     // a base class template specialization.
6471     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6472       ImportAttr->setPropagatedToBaseTemplate();
6473 
6474     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6475     // needs to be run again to work see the new attribute. Otherwise this will
6476     // get run whenever the template is instantiated.
6477     if (TSK != TSK_Undeclared)
6478       checkClassLevelDLLAttribute(BaseTemplateSpec);
6479 
6480     return;
6481   }
6482 
6483   if (getDLLAttr(BaseTemplateSpec)) {
6484     // The template has already been specialized or instantiated with an
6485     // attribute, explicitly or through propagation. We should not try to change
6486     // it.
6487     return;
6488   }
6489 
6490   // The template was previously instantiated or explicitly specialized without
6491   // a dll attribute, It's too late for us to add an attribute, so warn that
6492   // this is unsupported.
6493   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6494       << BaseTemplateSpec->isExplicitSpecialization();
6495   Diag(ClassAttr->getLocation(), diag::note_attribute);
6496   if (BaseTemplateSpec->isExplicitSpecialization()) {
6497     Diag(BaseTemplateSpec->getLocation(),
6498            diag::note_template_class_explicit_specialization_was_here)
6499         << BaseTemplateSpec;
6500   } else {
6501     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6502            diag::note_template_class_instantiation_was_here)
6503         << BaseTemplateSpec;
6504   }
6505 }
6506 
6507 /// Determine the kind of defaulting that would be done for a given function.
6508 ///
6509 /// If the function is both a default constructor and a copy / move constructor
6510 /// (due to having a default argument for the first parameter), this picks
6511 /// CXXDefaultConstructor.
6512 ///
6513 /// FIXME: Check that case is properly handled by all callers.
6514 Sema::DefaultedFunctionKind
6515 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6516   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6517     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6518       if (Ctor->isDefaultConstructor())
6519         return Sema::CXXDefaultConstructor;
6520 
6521       if (Ctor->isCopyConstructor())
6522         return Sema::CXXCopyConstructor;
6523 
6524       if (Ctor->isMoveConstructor())
6525         return Sema::CXXMoveConstructor;
6526     }
6527 
6528     if (MD->isCopyAssignmentOperator())
6529       return Sema::CXXCopyAssignment;
6530 
6531     if (MD->isMoveAssignmentOperator())
6532       return Sema::CXXMoveAssignment;
6533 
6534     if (isa<CXXDestructorDecl>(FD))
6535       return Sema::CXXDestructor;
6536   }
6537 
6538   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6539   case OO_EqualEqual:
6540     return DefaultedComparisonKind::Equal;
6541 
6542   case OO_ExclaimEqual:
6543     return DefaultedComparisonKind::NotEqual;
6544 
6545   case OO_Spaceship:
6546     // No point allowing this if <=> doesn't exist in the current language mode.
6547     if (!getLangOpts().CPlusPlus20)
6548       break;
6549     return DefaultedComparisonKind::ThreeWay;
6550 
6551   case OO_Less:
6552   case OO_LessEqual:
6553   case OO_Greater:
6554   case OO_GreaterEqual:
6555     // No point allowing this if <=> doesn't exist in the current language mode.
6556     if (!getLangOpts().CPlusPlus20)
6557       break;
6558     return DefaultedComparisonKind::Relational;
6559 
6560   default:
6561     break;
6562   }
6563 
6564   // Not defaultable.
6565   return DefaultedFunctionKind();
6566 }
6567 
6568 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6569                                     SourceLocation DefaultLoc) {
6570   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6571   if (DFK.isComparison())
6572     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6573 
6574   switch (DFK.asSpecialMember()) {
6575   case Sema::CXXDefaultConstructor:
6576     S.DefineImplicitDefaultConstructor(DefaultLoc,
6577                                        cast<CXXConstructorDecl>(FD));
6578     break;
6579   case Sema::CXXCopyConstructor:
6580     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6581     break;
6582   case Sema::CXXCopyAssignment:
6583     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6584     break;
6585   case Sema::CXXDestructor:
6586     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6587     break;
6588   case Sema::CXXMoveConstructor:
6589     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6590     break;
6591   case Sema::CXXMoveAssignment:
6592     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6593     break;
6594   case Sema::CXXInvalid:
6595     llvm_unreachable("Invalid special member.");
6596   }
6597 }
6598 
6599 /// Determine whether a type is permitted to be passed or returned in
6600 /// registers, per C++ [class.temporary]p3.
6601 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6602                                TargetInfo::CallingConvKind CCK) {
6603   if (D->isDependentType() || D->isInvalidDecl())
6604     return false;
6605 
6606   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6607   // The PS4 platform ABI follows the behavior of Clang 3.2.
6608   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6609     return !D->hasNonTrivialDestructorForCall() &&
6610            !D->hasNonTrivialCopyConstructorForCall();
6611 
6612   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6613     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6614     bool DtorIsTrivialForCall = false;
6615 
6616     // If a class has at least one non-deleted, trivial copy constructor, it
6617     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6618     //
6619     // Note: This permits classes with non-trivial copy or move ctors to be
6620     // passed in registers, so long as they *also* have a trivial copy ctor,
6621     // which is non-conforming.
6622     if (D->needsImplicitCopyConstructor()) {
6623       if (!D->defaultedCopyConstructorIsDeleted()) {
6624         if (D->hasTrivialCopyConstructor())
6625           CopyCtorIsTrivial = true;
6626         if (D->hasTrivialCopyConstructorForCall())
6627           CopyCtorIsTrivialForCall = true;
6628       }
6629     } else {
6630       for (const CXXConstructorDecl *CD : D->ctors()) {
6631         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6632           if (CD->isTrivial())
6633             CopyCtorIsTrivial = true;
6634           if (CD->isTrivialForCall())
6635             CopyCtorIsTrivialForCall = true;
6636         }
6637       }
6638     }
6639 
6640     if (D->needsImplicitDestructor()) {
6641       if (!D->defaultedDestructorIsDeleted() &&
6642           D->hasTrivialDestructorForCall())
6643         DtorIsTrivialForCall = true;
6644     } else if (const auto *DD = D->getDestructor()) {
6645       if (!DD->isDeleted() && DD->isTrivialForCall())
6646         DtorIsTrivialForCall = true;
6647     }
6648 
6649     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6650     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6651       return true;
6652 
6653     // If a class has a destructor, we'd really like to pass it indirectly
6654     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6655     // impossible for small types, which it will pass in a single register or
6656     // stack slot. Most objects with dtors are large-ish, so handle that early.
6657     // We can't call out all large objects as being indirect because there are
6658     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6659     // how we pass large POD types.
6660 
6661     // Note: This permits small classes with nontrivial destructors to be
6662     // passed in registers, which is non-conforming.
6663     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6664     uint64_t TypeSize = isAArch64 ? 128 : 64;
6665 
6666     if (CopyCtorIsTrivial &&
6667         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6668       return true;
6669     return false;
6670   }
6671 
6672   // Per C++ [class.temporary]p3, the relevant condition is:
6673   //   each copy constructor, move constructor, and destructor of X is
6674   //   either trivial or deleted, and X has at least one non-deleted copy
6675   //   or move constructor
6676   bool HasNonDeletedCopyOrMove = false;
6677 
6678   if (D->needsImplicitCopyConstructor() &&
6679       !D->defaultedCopyConstructorIsDeleted()) {
6680     if (!D->hasTrivialCopyConstructorForCall())
6681       return false;
6682     HasNonDeletedCopyOrMove = true;
6683   }
6684 
6685   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6686       !D->defaultedMoveConstructorIsDeleted()) {
6687     if (!D->hasTrivialMoveConstructorForCall())
6688       return false;
6689     HasNonDeletedCopyOrMove = true;
6690   }
6691 
6692   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6693       !D->hasTrivialDestructorForCall())
6694     return false;
6695 
6696   for (const CXXMethodDecl *MD : D->methods()) {
6697     if (MD->isDeleted())
6698       continue;
6699 
6700     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6701     if (CD && CD->isCopyOrMoveConstructor())
6702       HasNonDeletedCopyOrMove = true;
6703     else if (!isa<CXXDestructorDecl>(MD))
6704       continue;
6705 
6706     if (!MD->isTrivialForCall())
6707       return false;
6708   }
6709 
6710   return HasNonDeletedCopyOrMove;
6711 }
6712 
6713 /// Report an error regarding overriding, along with any relevant
6714 /// overridden methods.
6715 ///
6716 /// \param DiagID the primary error to report.
6717 /// \param MD the overriding method.
6718 static bool
6719 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6720                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6721   bool IssuedDiagnostic = false;
6722   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6723     if (Report(O)) {
6724       if (!IssuedDiagnostic) {
6725         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6726         IssuedDiagnostic = true;
6727       }
6728       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6729     }
6730   }
6731   return IssuedDiagnostic;
6732 }
6733 
6734 /// Perform semantic checks on a class definition that has been
6735 /// completing, introducing implicitly-declared members, checking for
6736 /// abstract types, etc.
6737 ///
6738 /// \param S The scope in which the class was parsed. Null if we didn't just
6739 ///        parse a class definition.
6740 /// \param Record The completed class.
6741 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6742   if (!Record)
6743     return;
6744 
6745   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6746     AbstractUsageInfo Info(*this, Record);
6747     CheckAbstractClassUsage(Info, Record);
6748   }
6749 
6750   // If this is not an aggregate type and has no user-declared constructor,
6751   // complain about any non-static data members of reference or const scalar
6752   // type, since they will never get initializers.
6753   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6754       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6755       !Record->isLambda()) {
6756     bool Complained = false;
6757     for (const auto *F : Record->fields()) {
6758       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6759         continue;
6760 
6761       if (F->getType()->isReferenceType() ||
6762           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6763         if (!Complained) {
6764           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6765             << Record->getTagKind() << Record;
6766           Complained = true;
6767         }
6768 
6769         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6770           << F->getType()->isReferenceType()
6771           << F->getDeclName();
6772       }
6773     }
6774   }
6775 
6776   if (Record->getIdentifier()) {
6777     // C++ [class.mem]p13:
6778     //   If T is the name of a class, then each of the following shall have a
6779     //   name different from T:
6780     //     - every member of every anonymous union that is a member of class T.
6781     //
6782     // C++ [class.mem]p14:
6783     //   In addition, if class T has a user-declared constructor (12.1), every
6784     //   non-static data member of class T shall have a name different from T.
6785     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6786     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6787          ++I) {
6788       NamedDecl *D = (*I)->getUnderlyingDecl();
6789       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6790            Record->hasUserDeclaredConstructor()) ||
6791           isa<IndirectFieldDecl>(D)) {
6792         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6793           << D->getDeclName();
6794         break;
6795       }
6796     }
6797   }
6798 
6799   // Warn if the class has virtual methods but non-virtual public destructor.
6800   if (Record->isPolymorphic() && !Record->isDependentType()) {
6801     CXXDestructorDecl *dtor = Record->getDestructor();
6802     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6803         !Record->hasAttr<FinalAttr>())
6804       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6805            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6806   }
6807 
6808   if (Record->isAbstract()) {
6809     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6810       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6811         << FA->isSpelledAsSealed();
6812       DiagnoseAbstractType(Record);
6813     }
6814   }
6815 
6816   // Warn if the class has a final destructor but is not itself marked final.
6817   if (!Record->hasAttr<FinalAttr>()) {
6818     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6819       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6820         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6821             << FA->isSpelledAsSealed()
6822             << FixItHint::CreateInsertion(
6823                    getLocForEndOfToken(Record->getLocation()),
6824                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6825         Diag(Record->getLocation(),
6826              diag::note_final_dtor_non_final_class_silence)
6827             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6828       }
6829     }
6830   }
6831 
6832   // See if trivial_abi has to be dropped.
6833   if (Record->hasAttr<TrivialABIAttr>())
6834     checkIllFormedTrivialABIStruct(*Record);
6835 
6836   // Set HasTrivialSpecialMemberForCall if the record has attribute
6837   // "trivial_abi".
6838   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6839 
6840   if (HasTrivialABI)
6841     Record->setHasTrivialSpecialMemberForCall();
6842 
6843   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6844   // We check these last because they can depend on the properties of the
6845   // primary comparison functions (==, <=>).
6846   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6847 
6848   // Perform checks that can't be done until we know all the properties of a
6849   // member function (whether it's defaulted, deleted, virtual, overriding,
6850   // ...).
6851   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6852     // A static function cannot override anything.
6853     if (MD->getStorageClass() == SC_Static) {
6854       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6855                           [](const CXXMethodDecl *) { return true; }))
6856         return;
6857     }
6858 
6859     // A deleted function cannot override a non-deleted function and vice
6860     // versa.
6861     if (ReportOverrides(*this,
6862                         MD->isDeleted() ? diag::err_deleted_override
6863                                         : diag::err_non_deleted_override,
6864                         MD, [&](const CXXMethodDecl *V) {
6865                           return MD->isDeleted() != V->isDeleted();
6866                         })) {
6867       if (MD->isDefaulted() && MD->isDeleted())
6868         // Explain why this defaulted function was deleted.
6869         DiagnoseDeletedDefaultedFunction(MD);
6870       return;
6871     }
6872 
6873     // A consteval function cannot override a non-consteval function and vice
6874     // versa.
6875     if (ReportOverrides(*this,
6876                         MD->isConsteval() ? diag::err_consteval_override
6877                                           : diag::err_non_consteval_override,
6878                         MD, [&](const CXXMethodDecl *V) {
6879                           return MD->isConsteval() != V->isConsteval();
6880                         })) {
6881       if (MD->isDefaulted() && MD->isDeleted())
6882         // Explain why this defaulted function was deleted.
6883         DiagnoseDeletedDefaultedFunction(MD);
6884       return;
6885     }
6886   };
6887 
6888   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6889     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6890       return false;
6891 
6892     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6893     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6894         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6895       DefaultedSecondaryComparisons.push_back(FD);
6896       return true;
6897     }
6898 
6899     CheckExplicitlyDefaultedFunction(S, FD);
6900     return false;
6901   };
6902 
6903   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6904     // Check whether the explicitly-defaulted members are valid.
6905     bool Incomplete = CheckForDefaultedFunction(M);
6906 
6907     // Skip the rest of the checks for a member of a dependent class.
6908     if (Record->isDependentType())
6909       return;
6910 
6911     // For an explicitly defaulted or deleted special member, we defer
6912     // determining triviality until the class is complete. That time is now!
6913     CXXSpecialMember CSM = getSpecialMember(M);
6914     if (!M->isImplicit() && !M->isUserProvided()) {
6915       if (CSM != CXXInvalid) {
6916         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6917         // Inform the class that we've finished declaring this member.
6918         Record->finishedDefaultedOrDeletedMember(M);
6919         M->setTrivialForCall(
6920             HasTrivialABI ||
6921             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6922         Record->setTrivialForCallFlags(M);
6923       }
6924     }
6925 
6926     // Set triviality for the purpose of calls if this is a user-provided
6927     // copy/move constructor or destructor.
6928     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6929          CSM == CXXDestructor) && M->isUserProvided()) {
6930       M->setTrivialForCall(HasTrivialABI);
6931       Record->setTrivialForCallFlags(M);
6932     }
6933 
6934     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6935         M->hasAttr<DLLExportAttr>()) {
6936       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6937           M->isTrivial() &&
6938           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6939            CSM == CXXDestructor))
6940         M->dropAttr<DLLExportAttr>();
6941 
6942       if (M->hasAttr<DLLExportAttr>()) {
6943         // Define after any fields with in-class initializers have been parsed.
6944         DelayedDllExportMemberFunctions.push_back(M);
6945       }
6946     }
6947 
6948     // Define defaulted constexpr virtual functions that override a base class
6949     // function right away.
6950     // FIXME: We can defer doing this until the vtable is marked as used.
6951     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6952       DefineDefaultedFunction(*this, M, M->getLocation());
6953 
6954     if (!Incomplete)
6955       CheckCompletedMemberFunction(M);
6956   };
6957 
6958   // Check the destructor before any other member function. We need to
6959   // determine whether it's trivial in order to determine whether the claas
6960   // type is a literal type, which is a prerequisite for determining whether
6961   // other special member functions are valid and whether they're implicitly
6962   // 'constexpr'.
6963   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6964     CompleteMemberFunction(Dtor);
6965 
6966   bool HasMethodWithOverrideControl = false,
6967        HasOverridingMethodWithoutOverrideControl = false;
6968   for (auto *D : Record->decls()) {
6969     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6970       // FIXME: We could do this check for dependent types with non-dependent
6971       // bases.
6972       if (!Record->isDependentType()) {
6973         // See if a method overloads virtual methods in a base
6974         // class without overriding any.
6975         if (!M->isStatic())
6976           DiagnoseHiddenVirtualMethods(M);
6977         if (M->hasAttr<OverrideAttr>())
6978           HasMethodWithOverrideControl = true;
6979         else if (M->size_overridden_methods() > 0)
6980           HasOverridingMethodWithoutOverrideControl = true;
6981       }
6982 
6983       if (!isa<CXXDestructorDecl>(M))
6984         CompleteMemberFunction(M);
6985     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6986       CheckForDefaultedFunction(
6987           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6988     }
6989   }
6990 
6991   if (HasOverridingMethodWithoutOverrideControl) {
6992     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6993     for (auto *M : Record->methods())
6994       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6995   }
6996 
6997   // Check the defaulted secondary comparisons after any other member functions.
6998   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6999     CheckExplicitlyDefaultedFunction(S, FD);
7000 
7001     // If this is a member function, we deferred checking it until now.
7002     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
7003       CheckCompletedMemberFunction(MD);
7004   }
7005 
7006   // ms_struct is a request to use the same ABI rules as MSVC.  Check
7007   // whether this class uses any C++ features that are implemented
7008   // completely differently in MSVC, and if so, emit a diagnostic.
7009   // That diagnostic defaults to an error, but we allow projects to
7010   // map it down to a warning (or ignore it).  It's a fairly common
7011   // practice among users of the ms_struct pragma to mass-annotate
7012   // headers, sweeping up a bunch of types that the project doesn't
7013   // really rely on MSVC-compatible layout for.  We must therefore
7014   // support "ms_struct except for C++ stuff" as a secondary ABI.
7015   // Don't emit this diagnostic if the feature was enabled as a
7016   // language option (as opposed to via a pragma or attribute), as
7017   // the option -mms-bitfields otherwise essentially makes it impossible
7018   // to build C++ code, unless this diagnostic is turned off.
7019   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7020       (Record->isPolymorphic() || Record->getNumBases())) {
7021     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7022   }
7023 
7024   checkClassLevelDLLAttribute(Record);
7025   checkClassLevelCodeSegAttribute(Record);
7026 
7027   bool ClangABICompat4 =
7028       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7029   TargetInfo::CallingConvKind CCK =
7030       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7031   bool CanPass = canPassInRegisters(*this, Record, CCK);
7032 
7033   // Do not change ArgPassingRestrictions if it has already been set to
7034   // APK_CanNeverPassInRegs.
7035   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
7036     Record->setArgPassingRestrictions(CanPass
7037                                           ? RecordDecl::APK_CanPassInRegs
7038                                           : RecordDecl::APK_CannotPassInRegs);
7039 
7040   // If canPassInRegisters returns true despite the record having a non-trivial
7041   // destructor, the record is destructed in the callee. This happens only when
7042   // the record or one of its subobjects has a field annotated with trivial_abi
7043   // or a field qualified with ObjC __strong/__weak.
7044   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7045     Record->setParamDestroyedInCallee(true);
7046   else if (Record->hasNonTrivialDestructor())
7047     Record->setParamDestroyedInCallee(CanPass);
7048 
7049   if (getLangOpts().ForceEmitVTables) {
7050     // If we want to emit all the vtables, we need to mark it as used.  This
7051     // is especially required for cases like vtable assumption loads.
7052     MarkVTableUsed(Record->getInnerLocStart(), Record);
7053   }
7054 
7055   if (getLangOpts().CUDA) {
7056     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7057       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7058     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7059       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7060   }
7061 }
7062 
7063 /// Look up the special member function that would be called by a special
7064 /// member function for a subobject of class type.
7065 ///
7066 /// \param Class The class type of the subobject.
7067 /// \param CSM The kind of special member function.
7068 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7069 /// \param ConstRHS True if this is a copy operation with a const object
7070 ///        on its RHS, that is, if the argument to the outer special member
7071 ///        function is 'const' and this is not a field marked 'mutable'.
7072 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7073     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7074     unsigned FieldQuals, bool ConstRHS) {
7075   unsigned LHSQuals = 0;
7076   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7077     LHSQuals = FieldQuals;
7078 
7079   unsigned RHSQuals = FieldQuals;
7080   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7081     RHSQuals = 0;
7082   else if (ConstRHS)
7083     RHSQuals |= Qualifiers::Const;
7084 
7085   return S.LookupSpecialMember(Class, CSM,
7086                                RHSQuals & Qualifiers::Const,
7087                                RHSQuals & Qualifiers::Volatile,
7088                                false,
7089                                LHSQuals & Qualifiers::Const,
7090                                LHSQuals & Qualifiers::Volatile);
7091 }
7092 
7093 class Sema::InheritedConstructorInfo {
7094   Sema &S;
7095   SourceLocation UseLoc;
7096 
7097   /// A mapping from the base classes through which the constructor was
7098   /// inherited to the using shadow declaration in that base class (or a null
7099   /// pointer if the constructor was declared in that base class).
7100   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7101       InheritedFromBases;
7102 
7103 public:
7104   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7105                            ConstructorUsingShadowDecl *Shadow)
7106       : S(S), UseLoc(UseLoc) {
7107     bool DiagnosedMultipleConstructedBases = false;
7108     CXXRecordDecl *ConstructedBase = nullptr;
7109     BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7110 
7111     // Find the set of such base class subobjects and check that there's a
7112     // unique constructed subobject.
7113     for (auto *D : Shadow->redecls()) {
7114       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7115       auto *DNominatedBase = DShadow->getNominatedBaseClass();
7116       auto *DConstructedBase = DShadow->getConstructedBaseClass();
7117 
7118       InheritedFromBases.insert(
7119           std::make_pair(DNominatedBase->getCanonicalDecl(),
7120                          DShadow->getNominatedBaseClassShadowDecl()));
7121       if (DShadow->constructsVirtualBase())
7122         InheritedFromBases.insert(
7123             std::make_pair(DConstructedBase->getCanonicalDecl(),
7124                            DShadow->getConstructedBaseClassShadowDecl()));
7125       else
7126         assert(DNominatedBase == DConstructedBase);
7127 
7128       // [class.inhctor.init]p2:
7129       //   If the constructor was inherited from multiple base class subobjects
7130       //   of type B, the program is ill-formed.
7131       if (!ConstructedBase) {
7132         ConstructedBase = DConstructedBase;
7133         ConstructedBaseIntroducer = D->getIntroducer();
7134       } else if (ConstructedBase != DConstructedBase &&
7135                  !Shadow->isInvalidDecl()) {
7136         if (!DiagnosedMultipleConstructedBases) {
7137           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7138               << Shadow->getTargetDecl();
7139           S.Diag(ConstructedBaseIntroducer->getLocation(),
7140                  diag::note_ambiguous_inherited_constructor_using)
7141               << ConstructedBase;
7142           DiagnosedMultipleConstructedBases = true;
7143         }
7144         S.Diag(D->getIntroducer()->getLocation(),
7145                diag::note_ambiguous_inherited_constructor_using)
7146             << DConstructedBase;
7147       }
7148     }
7149 
7150     if (DiagnosedMultipleConstructedBases)
7151       Shadow->setInvalidDecl();
7152   }
7153 
7154   /// Find the constructor to use for inherited construction of a base class,
7155   /// and whether that base class constructor inherits the constructor from a
7156   /// virtual base class (in which case it won't actually invoke it).
7157   std::pair<CXXConstructorDecl *, bool>
7158   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7159     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7160     if (It == InheritedFromBases.end())
7161       return std::make_pair(nullptr, false);
7162 
7163     // This is an intermediary class.
7164     if (It->second)
7165       return std::make_pair(
7166           S.findInheritingConstructor(UseLoc, Ctor, It->second),
7167           It->second->constructsVirtualBase());
7168 
7169     // This is the base class from which the constructor was inherited.
7170     return std::make_pair(Ctor, false);
7171   }
7172 };
7173 
7174 /// Is the special member function which would be selected to perform the
7175 /// specified operation on the specified class type a constexpr constructor?
7176 static bool
7177 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7178                          Sema::CXXSpecialMember CSM, unsigned Quals,
7179                          bool ConstRHS,
7180                          CXXConstructorDecl *InheritedCtor = nullptr,
7181                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7182   // If we're inheriting a constructor, see if we need to call it for this base
7183   // class.
7184   if (InheritedCtor) {
7185     assert(CSM == Sema::CXXDefaultConstructor);
7186     auto BaseCtor =
7187         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7188     if (BaseCtor)
7189       return BaseCtor->isConstexpr();
7190   }
7191 
7192   if (CSM == Sema::CXXDefaultConstructor)
7193     return ClassDecl->hasConstexprDefaultConstructor();
7194   if (CSM == Sema::CXXDestructor)
7195     return ClassDecl->hasConstexprDestructor();
7196 
7197   Sema::SpecialMemberOverloadResult SMOR =
7198       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7199   if (!SMOR.getMethod())
7200     // A constructor we wouldn't select can't be "involved in initializing"
7201     // anything.
7202     return true;
7203   return SMOR.getMethod()->isConstexpr();
7204 }
7205 
7206 /// Determine whether the specified special member function would be constexpr
7207 /// if it were implicitly defined.
7208 static bool defaultedSpecialMemberIsConstexpr(
7209     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7210     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7211     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7212   if (!S.getLangOpts().CPlusPlus11)
7213     return false;
7214 
7215   // C++11 [dcl.constexpr]p4:
7216   // In the definition of a constexpr constructor [...]
7217   bool Ctor = true;
7218   switch (CSM) {
7219   case Sema::CXXDefaultConstructor:
7220     if (Inherited)
7221       break;
7222     // Since default constructor lookup is essentially trivial (and cannot
7223     // involve, for instance, template instantiation), we compute whether a
7224     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7225     //
7226     // This is important for performance; we need to know whether the default
7227     // constructor is constexpr to determine whether the type is a literal type.
7228     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7229 
7230   case Sema::CXXCopyConstructor:
7231   case Sema::CXXMoveConstructor:
7232     // For copy or move constructors, we need to perform overload resolution.
7233     break;
7234 
7235   case Sema::CXXCopyAssignment:
7236   case Sema::CXXMoveAssignment:
7237     if (!S.getLangOpts().CPlusPlus14)
7238       return false;
7239     // In C++1y, we need to perform overload resolution.
7240     Ctor = false;
7241     break;
7242 
7243   case Sema::CXXDestructor:
7244     return ClassDecl->defaultedDestructorIsConstexpr();
7245 
7246   case Sema::CXXInvalid:
7247     return false;
7248   }
7249 
7250   //   -- if the class is a non-empty union, or for each non-empty anonymous
7251   //      union member of a non-union class, exactly one non-static data member
7252   //      shall be initialized; [DR1359]
7253   //
7254   // If we squint, this is guaranteed, since exactly one non-static data member
7255   // will be initialized (if the constructor isn't deleted), we just don't know
7256   // which one.
7257   if (Ctor && ClassDecl->isUnion())
7258     return CSM == Sema::CXXDefaultConstructor
7259                ? ClassDecl->hasInClassInitializer() ||
7260                      !ClassDecl->hasVariantMembers()
7261                : true;
7262 
7263   //   -- the class shall not have any virtual base classes;
7264   if (Ctor && ClassDecl->getNumVBases())
7265     return false;
7266 
7267   // C++1y [class.copy]p26:
7268   //   -- [the class] is a literal type, and
7269   if (!Ctor && !ClassDecl->isLiteral())
7270     return false;
7271 
7272   //   -- every constructor involved in initializing [...] base class
7273   //      sub-objects shall be a constexpr constructor;
7274   //   -- the assignment operator selected to copy/move each direct base
7275   //      class is a constexpr function, and
7276   for (const auto &B : ClassDecl->bases()) {
7277     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7278     if (!BaseType) continue;
7279 
7280     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7281     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7282                                   InheritedCtor, Inherited))
7283       return false;
7284   }
7285 
7286   //   -- every constructor involved in initializing non-static data members
7287   //      [...] shall be a constexpr constructor;
7288   //   -- every non-static data member and base class sub-object shall be
7289   //      initialized
7290   //   -- for each non-static data member of X that is of class type (or array
7291   //      thereof), the assignment operator selected to copy/move that member is
7292   //      a constexpr function
7293   for (const auto *F : ClassDecl->fields()) {
7294     if (F->isInvalidDecl())
7295       continue;
7296     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7297       continue;
7298     QualType BaseType = S.Context.getBaseElementType(F->getType());
7299     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7300       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7301       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7302                                     BaseType.getCVRQualifiers(),
7303                                     ConstArg && !F->isMutable()))
7304         return false;
7305     } else if (CSM == Sema::CXXDefaultConstructor) {
7306       return false;
7307     }
7308   }
7309 
7310   // All OK, it's constexpr!
7311   return true;
7312 }
7313 
7314 namespace {
7315 /// RAII object to register a defaulted function as having its exception
7316 /// specification computed.
7317 struct ComputingExceptionSpec {
7318   Sema &S;
7319 
7320   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7321       : S(S) {
7322     Sema::CodeSynthesisContext Ctx;
7323     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7324     Ctx.PointOfInstantiation = Loc;
7325     Ctx.Entity = FD;
7326     S.pushCodeSynthesisContext(Ctx);
7327   }
7328   ~ComputingExceptionSpec() {
7329     S.popCodeSynthesisContext();
7330   }
7331 };
7332 }
7333 
7334 static Sema::ImplicitExceptionSpecification
7335 ComputeDefaultedSpecialMemberExceptionSpec(
7336     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7337     Sema::InheritedConstructorInfo *ICI);
7338 
7339 static Sema::ImplicitExceptionSpecification
7340 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7341                                         FunctionDecl *FD,
7342                                         Sema::DefaultedComparisonKind DCK);
7343 
7344 static Sema::ImplicitExceptionSpecification
7345 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7346   auto DFK = S.getDefaultedFunctionKind(FD);
7347   if (DFK.isSpecialMember())
7348     return ComputeDefaultedSpecialMemberExceptionSpec(
7349         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7350   if (DFK.isComparison())
7351     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7352                                                    DFK.asComparison());
7353 
7354   auto *CD = cast<CXXConstructorDecl>(FD);
7355   assert(CD->getInheritedConstructor() &&
7356          "only defaulted functions and inherited constructors have implicit "
7357          "exception specs");
7358   Sema::InheritedConstructorInfo ICI(
7359       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7360   return ComputeDefaultedSpecialMemberExceptionSpec(
7361       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7362 }
7363 
7364 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7365                                                             CXXMethodDecl *MD) {
7366   FunctionProtoType::ExtProtoInfo EPI;
7367 
7368   // Build an exception specification pointing back at this member.
7369   EPI.ExceptionSpec.Type = EST_Unevaluated;
7370   EPI.ExceptionSpec.SourceDecl = MD;
7371 
7372   // Set the calling convention to the default for C++ instance methods.
7373   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7374       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7375                                             /*IsCXXMethod=*/true));
7376   return EPI;
7377 }
7378 
7379 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7380   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7381   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7382     return;
7383 
7384   // Evaluate the exception specification.
7385   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7386   auto ESI = IES.getExceptionSpec();
7387 
7388   // Update the type of the special member to use it.
7389   UpdateExceptionSpec(FD, ESI);
7390 }
7391 
7392 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7393   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7394 
7395   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7396   if (!DefKind) {
7397     assert(FD->getDeclContext()->isDependentContext());
7398     return;
7399   }
7400 
7401   if (DefKind.isComparison())
7402     UnusedPrivateFields.clear();
7403 
7404   if (DefKind.isSpecialMember()
7405           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7406                                                   DefKind.asSpecialMember())
7407           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7408     FD->setInvalidDecl();
7409 }
7410 
7411 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7412                                                  CXXSpecialMember CSM) {
7413   CXXRecordDecl *RD = MD->getParent();
7414 
7415   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7416          "not an explicitly-defaulted special member");
7417 
7418   // Defer all checking for special members of a dependent type.
7419   if (RD->isDependentType())
7420     return false;
7421 
7422   // Whether this was the first-declared instance of the constructor.
7423   // This affects whether we implicitly add an exception spec and constexpr.
7424   bool First = MD == MD->getCanonicalDecl();
7425 
7426   bool HadError = false;
7427 
7428   // C++11 [dcl.fct.def.default]p1:
7429   //   A function that is explicitly defaulted shall
7430   //     -- be a special member function [...] (checked elsewhere),
7431   //     -- have the same type (except for ref-qualifiers, and except that a
7432   //        copy operation can take a non-const reference) as an implicit
7433   //        declaration, and
7434   //     -- not have default arguments.
7435   // C++2a changes the second bullet to instead delete the function if it's
7436   // defaulted on its first declaration, unless it's "an assignment operator,
7437   // and its return type differs or its parameter type is not a reference".
7438   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7439   bool ShouldDeleteForTypeMismatch = false;
7440   unsigned ExpectedParams = 1;
7441   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7442     ExpectedParams = 0;
7443   if (MD->getNumParams() != ExpectedParams) {
7444     // This checks for default arguments: a copy or move constructor with a
7445     // default argument is classified as a default constructor, and assignment
7446     // operations and destructors can't have default arguments.
7447     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7448       << CSM << MD->getSourceRange();
7449     HadError = true;
7450   } else if (MD->isVariadic()) {
7451     if (DeleteOnTypeMismatch)
7452       ShouldDeleteForTypeMismatch = true;
7453     else {
7454       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7455         << CSM << MD->getSourceRange();
7456       HadError = true;
7457     }
7458   }
7459 
7460   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7461 
7462   bool CanHaveConstParam = false;
7463   if (CSM == CXXCopyConstructor)
7464     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7465   else if (CSM == CXXCopyAssignment)
7466     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7467 
7468   QualType ReturnType = Context.VoidTy;
7469   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7470     // Check for return type matching.
7471     ReturnType = Type->getReturnType();
7472 
7473     QualType DeclType = Context.getTypeDeclType(RD);
7474     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7475     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7476 
7477     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7478       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7479         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7480       HadError = true;
7481     }
7482 
7483     // A defaulted special member cannot have cv-qualifiers.
7484     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7485       if (DeleteOnTypeMismatch)
7486         ShouldDeleteForTypeMismatch = true;
7487       else {
7488         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7489           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7490         HadError = true;
7491       }
7492     }
7493   }
7494 
7495   // Check for parameter type matching.
7496   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7497   bool HasConstParam = false;
7498   if (ExpectedParams && ArgType->isReferenceType()) {
7499     // Argument must be reference to possibly-const T.
7500     QualType ReferentType = ArgType->getPointeeType();
7501     HasConstParam = ReferentType.isConstQualified();
7502 
7503     if (ReferentType.isVolatileQualified()) {
7504       if (DeleteOnTypeMismatch)
7505         ShouldDeleteForTypeMismatch = true;
7506       else {
7507         Diag(MD->getLocation(),
7508              diag::err_defaulted_special_member_volatile_param) << CSM;
7509         HadError = true;
7510       }
7511     }
7512 
7513     if (HasConstParam && !CanHaveConstParam) {
7514       if (DeleteOnTypeMismatch)
7515         ShouldDeleteForTypeMismatch = true;
7516       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7517         Diag(MD->getLocation(),
7518              diag::err_defaulted_special_member_copy_const_param)
7519           << (CSM == CXXCopyAssignment);
7520         // FIXME: Explain why this special member can't be const.
7521         HadError = true;
7522       } else {
7523         Diag(MD->getLocation(),
7524              diag::err_defaulted_special_member_move_const_param)
7525           << (CSM == CXXMoveAssignment);
7526         HadError = true;
7527       }
7528     }
7529   } else if (ExpectedParams) {
7530     // A copy assignment operator can take its argument by value, but a
7531     // defaulted one cannot.
7532     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7533     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7534     HadError = true;
7535   }
7536 
7537   // C++11 [dcl.fct.def.default]p2:
7538   //   An explicitly-defaulted function may be declared constexpr only if it
7539   //   would have been implicitly declared as constexpr,
7540   // Do not apply this rule to members of class templates, since core issue 1358
7541   // makes such functions always instantiate to constexpr functions. For
7542   // functions which cannot be constexpr (for non-constructors in C++11 and for
7543   // destructors in C++14 and C++17), this is checked elsewhere.
7544   //
7545   // FIXME: This should not apply if the member is deleted.
7546   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7547                                                      HasConstParam);
7548   if ((getLangOpts().CPlusPlus20 ||
7549        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7550                                   : isa<CXXConstructorDecl>(MD))) &&
7551       MD->isConstexpr() && !Constexpr &&
7552       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7553     Diag(MD->getBeginLoc(), MD->isConsteval()
7554                                 ? diag::err_incorrect_defaulted_consteval
7555                                 : diag::err_incorrect_defaulted_constexpr)
7556         << CSM;
7557     // FIXME: Explain why the special member can't be constexpr.
7558     HadError = true;
7559   }
7560 
7561   if (First) {
7562     // C++2a [dcl.fct.def.default]p3:
7563     //   If a function is explicitly defaulted on its first declaration, it is
7564     //   implicitly considered to be constexpr if the implicit declaration
7565     //   would be.
7566     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7567                                           ? ConstexprSpecKind::Consteval
7568                                           : ConstexprSpecKind::Constexpr)
7569                                    : ConstexprSpecKind::Unspecified);
7570 
7571     if (!Type->hasExceptionSpec()) {
7572       // C++2a [except.spec]p3:
7573       //   If a declaration of a function does not have a noexcept-specifier
7574       //   [and] is defaulted on its first declaration, [...] the exception
7575       //   specification is as specified below
7576       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7577       EPI.ExceptionSpec.Type = EST_Unevaluated;
7578       EPI.ExceptionSpec.SourceDecl = MD;
7579       MD->setType(Context.getFunctionType(ReturnType,
7580                                           llvm::makeArrayRef(&ArgType,
7581                                                              ExpectedParams),
7582                                           EPI));
7583     }
7584   }
7585 
7586   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7587     if (First) {
7588       SetDeclDeleted(MD, MD->getLocation());
7589       if (!inTemplateInstantiation() && !HadError) {
7590         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7591         if (ShouldDeleteForTypeMismatch) {
7592           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7593         } else {
7594           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7595         }
7596       }
7597       if (ShouldDeleteForTypeMismatch && !HadError) {
7598         Diag(MD->getLocation(),
7599              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7600       }
7601     } else {
7602       // C++11 [dcl.fct.def.default]p4:
7603       //   [For a] user-provided explicitly-defaulted function [...] if such a
7604       //   function is implicitly defined as deleted, the program is ill-formed.
7605       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7606       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7607       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7608       HadError = true;
7609     }
7610   }
7611 
7612   return HadError;
7613 }
7614 
7615 namespace {
7616 /// Helper class for building and checking a defaulted comparison.
7617 ///
7618 /// Defaulted functions are built in two phases:
7619 ///
7620 ///  * First, the set of operations that the function will perform are
7621 ///    identified, and some of them are checked. If any of the checked
7622 ///    operations is invalid in certain ways, the comparison function is
7623 ///    defined as deleted and no body is built.
7624 ///  * Then, if the function is not defined as deleted, the body is built.
7625 ///
7626 /// This is accomplished by performing two visitation steps over the eventual
7627 /// body of the function.
7628 template<typename Derived, typename ResultList, typename Result,
7629          typename Subobject>
7630 class DefaultedComparisonVisitor {
7631 public:
7632   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7633 
7634   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7635                              DefaultedComparisonKind DCK)
7636       : S(S), RD(RD), FD(FD), DCK(DCK) {
7637     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7638       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7639       // UnresolvedSet to avoid this copy.
7640       Fns.assign(Info->getUnqualifiedLookups().begin(),
7641                  Info->getUnqualifiedLookups().end());
7642     }
7643   }
7644 
7645   ResultList visit() {
7646     // The type of an lvalue naming a parameter of this function.
7647     QualType ParamLvalType =
7648         FD->getParamDecl(0)->getType().getNonReferenceType();
7649 
7650     ResultList Results;
7651 
7652     switch (DCK) {
7653     case DefaultedComparisonKind::None:
7654       llvm_unreachable("not a defaulted comparison");
7655 
7656     case DefaultedComparisonKind::Equal:
7657     case DefaultedComparisonKind::ThreeWay:
7658       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7659       return Results;
7660 
7661     case DefaultedComparisonKind::NotEqual:
7662     case DefaultedComparisonKind::Relational:
7663       Results.add(getDerived().visitExpandedSubobject(
7664           ParamLvalType, getDerived().getCompleteObject()));
7665       return Results;
7666     }
7667     llvm_unreachable("");
7668   }
7669 
7670 protected:
7671   Derived &getDerived() { return static_cast<Derived&>(*this); }
7672 
7673   /// Visit the expanded list of subobjects of the given type, as specified in
7674   /// C++2a [class.compare.default].
7675   ///
7676   /// \return \c true if the ResultList object said we're done, \c false if not.
7677   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7678                        Qualifiers Quals) {
7679     // C++2a [class.compare.default]p4:
7680     //   The direct base class subobjects of C
7681     for (CXXBaseSpecifier &Base : Record->bases())
7682       if (Results.add(getDerived().visitSubobject(
7683               S.Context.getQualifiedType(Base.getType(), Quals),
7684               getDerived().getBase(&Base))))
7685         return true;
7686 
7687     //   followed by the non-static data members of C
7688     for (FieldDecl *Field : Record->fields()) {
7689       // Recursively expand anonymous structs.
7690       if (Field->isAnonymousStructOrUnion()) {
7691         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7692                             Quals))
7693           return true;
7694         continue;
7695       }
7696 
7697       // Figure out the type of an lvalue denoting this field.
7698       Qualifiers FieldQuals = Quals;
7699       if (Field->isMutable())
7700         FieldQuals.removeConst();
7701       QualType FieldType =
7702           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7703 
7704       if (Results.add(getDerived().visitSubobject(
7705               FieldType, getDerived().getField(Field))))
7706         return true;
7707     }
7708 
7709     //   form a list of subobjects.
7710     return false;
7711   }
7712 
7713   Result visitSubobject(QualType Type, Subobject Subobj) {
7714     //   In that list, any subobject of array type is recursively expanded
7715     const ArrayType *AT = S.Context.getAsArrayType(Type);
7716     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7717       return getDerived().visitSubobjectArray(CAT->getElementType(),
7718                                               CAT->getSize(), Subobj);
7719     return getDerived().visitExpandedSubobject(Type, Subobj);
7720   }
7721 
7722   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7723                              Subobject Subobj) {
7724     return getDerived().visitSubobject(Type, Subobj);
7725   }
7726 
7727 protected:
7728   Sema &S;
7729   CXXRecordDecl *RD;
7730   FunctionDecl *FD;
7731   DefaultedComparisonKind DCK;
7732   UnresolvedSet<16> Fns;
7733 };
7734 
7735 /// Information about a defaulted comparison, as determined by
7736 /// DefaultedComparisonAnalyzer.
7737 struct DefaultedComparisonInfo {
7738   bool Deleted = false;
7739   bool Constexpr = true;
7740   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7741 
7742   static DefaultedComparisonInfo deleted() {
7743     DefaultedComparisonInfo Deleted;
7744     Deleted.Deleted = true;
7745     return Deleted;
7746   }
7747 
7748   bool add(const DefaultedComparisonInfo &R) {
7749     Deleted |= R.Deleted;
7750     Constexpr &= R.Constexpr;
7751     Category = commonComparisonType(Category, R.Category);
7752     return Deleted;
7753   }
7754 };
7755 
7756 /// An element in the expanded list of subobjects of a defaulted comparison, as
7757 /// specified in C++2a [class.compare.default]p4.
7758 struct DefaultedComparisonSubobject {
7759   enum { CompleteObject, Member, Base } Kind;
7760   NamedDecl *Decl;
7761   SourceLocation Loc;
7762 };
7763 
7764 /// A visitor over the notional body of a defaulted comparison that determines
7765 /// whether that body would be deleted or constexpr.
7766 class DefaultedComparisonAnalyzer
7767     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7768                                         DefaultedComparisonInfo,
7769                                         DefaultedComparisonInfo,
7770                                         DefaultedComparisonSubobject> {
7771 public:
7772   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7773 
7774 private:
7775   DiagnosticKind Diagnose;
7776 
7777 public:
7778   using Base = DefaultedComparisonVisitor;
7779   using Result = DefaultedComparisonInfo;
7780   using Subobject = DefaultedComparisonSubobject;
7781 
7782   friend Base;
7783 
7784   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7785                               DefaultedComparisonKind DCK,
7786                               DiagnosticKind Diagnose = NoDiagnostics)
7787       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7788 
7789   Result visit() {
7790     if ((DCK == DefaultedComparisonKind::Equal ||
7791          DCK == DefaultedComparisonKind::ThreeWay) &&
7792         RD->hasVariantMembers()) {
7793       // C++2a [class.compare.default]p2 [P2002R0]:
7794       //   A defaulted comparison operator function for class C is defined as
7795       //   deleted if [...] C has variant members.
7796       if (Diagnose == ExplainDeleted) {
7797         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7798           << FD << RD->isUnion() << RD;
7799       }
7800       return Result::deleted();
7801     }
7802 
7803     return Base::visit();
7804   }
7805 
7806 private:
7807   Subobject getCompleteObject() {
7808     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7809   }
7810 
7811   Subobject getBase(CXXBaseSpecifier *Base) {
7812     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7813                      Base->getBaseTypeLoc()};
7814   }
7815 
7816   Subobject getField(FieldDecl *Field) {
7817     return Subobject{Subobject::Member, Field, Field->getLocation()};
7818   }
7819 
7820   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7821     // C++2a [class.compare.default]p2 [P2002R0]:
7822     //   A defaulted <=> or == operator function for class C is defined as
7823     //   deleted if any non-static data member of C is of reference type
7824     if (Type->isReferenceType()) {
7825       if (Diagnose == ExplainDeleted) {
7826         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7827             << FD << RD;
7828       }
7829       return Result::deleted();
7830     }
7831 
7832     // [...] Let xi be an lvalue denoting the ith element [...]
7833     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7834     Expr *Args[] = {&Xi, &Xi};
7835 
7836     // All operators start by trying to apply that same operator recursively.
7837     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7838     assert(OO != OO_None && "not an overloaded operator!");
7839     return visitBinaryOperator(OO, Args, Subobj);
7840   }
7841 
7842   Result
7843   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7844                       Subobject Subobj,
7845                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7846     // Note that there is no need to consider rewritten candidates here if
7847     // we've already found there is no viable 'operator<=>' candidate (and are
7848     // considering synthesizing a '<=>' from '==' and '<').
7849     OverloadCandidateSet CandidateSet(
7850         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7851         OverloadCandidateSet::OperatorRewriteInfo(
7852             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7853 
7854     /// C++2a [class.compare.default]p1 [P2002R0]:
7855     ///   [...] the defaulted function itself is never a candidate for overload
7856     ///   resolution [...]
7857     CandidateSet.exclude(FD);
7858 
7859     if (Args[0]->getType()->isOverloadableType())
7860       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7861     else
7862       // FIXME: We determine whether this is a valid expression by checking to
7863       // see if there's a viable builtin operator candidate for it. That isn't
7864       // really what the rules ask us to do, but should give the right results.
7865       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7866 
7867     Result R;
7868 
7869     OverloadCandidateSet::iterator Best;
7870     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7871     case OR_Success: {
7872       // C++2a [class.compare.secondary]p2 [P2002R0]:
7873       //   The operator function [...] is defined as deleted if [...] the
7874       //   candidate selected by overload resolution is not a rewritten
7875       //   candidate.
7876       if ((DCK == DefaultedComparisonKind::NotEqual ||
7877            DCK == DefaultedComparisonKind::Relational) &&
7878           !Best->RewriteKind) {
7879         if (Diagnose == ExplainDeleted) {
7880           if (Best->Function) {
7881             S.Diag(Best->Function->getLocation(),
7882                    diag::note_defaulted_comparison_not_rewritten_callee)
7883                 << FD;
7884           } else {
7885             assert(Best->Conversions.size() == 2 &&
7886                    Best->Conversions[0].isUserDefined() &&
7887                    "non-user-defined conversion from class to built-in "
7888                    "comparison");
7889             S.Diag(Best->Conversions[0]
7890                        .UserDefined.FoundConversionFunction.getDecl()
7891                        ->getLocation(),
7892                    diag::note_defaulted_comparison_not_rewritten_conversion)
7893                 << FD;
7894           }
7895         }
7896         return Result::deleted();
7897       }
7898 
7899       // Throughout C++2a [class.compare]: if overload resolution does not
7900       // result in a usable function, the candidate function is defined as
7901       // deleted. This requires that we selected an accessible function.
7902       //
7903       // Note that this only considers the access of the function when named
7904       // within the type of the subobject, and not the access path for any
7905       // derived-to-base conversion.
7906       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7907       if (ArgClass && Best->FoundDecl.getDecl() &&
7908           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7909         QualType ObjectType = Subobj.Kind == Subobject::Member
7910                                   ? Args[0]->getType()
7911                                   : S.Context.getRecordType(RD);
7912         if (!S.isMemberAccessibleForDeletion(
7913                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7914                 Diagnose == ExplainDeleted
7915                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7916                           << FD << Subobj.Kind << Subobj.Decl
7917                     : S.PDiag()))
7918           return Result::deleted();
7919       }
7920 
7921       bool NeedsDeducing =
7922           OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7923 
7924       if (FunctionDecl *BestFD = Best->Function) {
7925         // C++2a [class.compare.default]p3 [P2002R0]:
7926         //   A defaulted comparison function is constexpr-compatible if
7927         //   [...] no overlod resolution performed [...] results in a
7928         //   non-constexpr function.
7929         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7930         // If it's not constexpr, explain why not.
7931         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7932           if (Subobj.Kind != Subobject::CompleteObject)
7933             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7934               << Subobj.Kind << Subobj.Decl;
7935           S.Diag(BestFD->getLocation(),
7936                  diag::note_defaulted_comparison_not_constexpr_here);
7937           // Bail out after explaining; we don't want any more notes.
7938           return Result::deleted();
7939         }
7940         R.Constexpr &= BestFD->isConstexpr();
7941 
7942         if (NeedsDeducing) {
7943           // If any callee has an undeduced return type, deduce it now.
7944           // FIXME: It's not clear how a failure here should be handled. For
7945           // now, we produce an eager diagnostic, because that is forward
7946           // compatible with most (all?) other reasonable options.
7947           if (BestFD->getReturnType()->isUndeducedType() &&
7948               S.DeduceReturnType(BestFD, FD->getLocation(),
7949                                  /*Diagnose=*/false)) {
7950             // Don't produce a duplicate error when asked to explain why the
7951             // comparison is deleted: we diagnosed that when initially checking
7952             // the defaulted operator.
7953             if (Diagnose == NoDiagnostics) {
7954               S.Diag(
7955                   FD->getLocation(),
7956                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7957                   << Subobj.Kind << Subobj.Decl;
7958               S.Diag(
7959                   Subobj.Loc,
7960                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7961                   << Subobj.Kind << Subobj.Decl;
7962               S.Diag(BestFD->getLocation(),
7963                      diag::note_defaulted_comparison_cannot_deduce_callee)
7964                   << Subobj.Kind << Subobj.Decl;
7965             }
7966             return Result::deleted();
7967           }
7968           auto *Info = S.Context.CompCategories.lookupInfoForType(
7969               BestFD->getCallResultType());
7970           if (!Info) {
7971             if (Diagnose == ExplainDeleted) {
7972               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7973                   << Subobj.Kind << Subobj.Decl
7974                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7975               S.Diag(BestFD->getLocation(),
7976                      diag::note_defaulted_comparison_cannot_deduce_callee)
7977                   << Subobj.Kind << Subobj.Decl;
7978             }
7979             return Result::deleted();
7980           }
7981           R.Category = Info->Kind;
7982         }
7983       } else {
7984         QualType T = Best->BuiltinParamTypes[0];
7985         assert(T == Best->BuiltinParamTypes[1] &&
7986                "builtin comparison for different types?");
7987         assert(Best->BuiltinParamTypes[2].isNull() &&
7988                "invalid builtin comparison");
7989 
7990         if (NeedsDeducing) {
7991           Optional<ComparisonCategoryType> Cat =
7992               getComparisonCategoryForBuiltinCmp(T);
7993           assert(Cat && "no category for builtin comparison?");
7994           R.Category = *Cat;
7995         }
7996       }
7997 
7998       // Note that we might be rewriting to a different operator. That call is
7999       // not considered until we come to actually build the comparison function.
8000       break;
8001     }
8002 
8003     case OR_Ambiguous:
8004       if (Diagnose == ExplainDeleted) {
8005         unsigned Kind = 0;
8006         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8007           Kind = OO == OO_EqualEqual ? 1 : 2;
8008         CandidateSet.NoteCandidates(
8009             PartialDiagnosticAt(
8010                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8011                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
8012             S, OCD_AmbiguousCandidates, Args);
8013       }
8014       R = Result::deleted();
8015       break;
8016 
8017     case OR_Deleted:
8018       if (Diagnose == ExplainDeleted) {
8019         if ((DCK == DefaultedComparisonKind::NotEqual ||
8020              DCK == DefaultedComparisonKind::Relational) &&
8021             !Best->RewriteKind) {
8022           S.Diag(Best->Function->getLocation(),
8023                  diag::note_defaulted_comparison_not_rewritten_callee)
8024               << FD;
8025         } else {
8026           S.Diag(Subobj.Loc,
8027                  diag::note_defaulted_comparison_calls_deleted)
8028               << FD << Subobj.Kind << Subobj.Decl;
8029           S.NoteDeletedFunction(Best->Function);
8030         }
8031       }
8032       R = Result::deleted();
8033       break;
8034 
8035     case OR_No_Viable_Function:
8036       // If there's no usable candidate, we're done unless we can rewrite a
8037       // '<=>' in terms of '==' and '<'.
8038       if (OO == OO_Spaceship &&
8039           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8040         // For any kind of comparison category return type, we need a usable
8041         // '==' and a usable '<'.
8042         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8043                                        &CandidateSet)))
8044           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8045         break;
8046       }
8047 
8048       if (Diagnose == ExplainDeleted) {
8049         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8050             << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
8051 
8052         // For a three-way comparison, list both the candidates for the
8053         // original operator and the candidates for the synthesized operator.
8054         if (SpaceshipCandidates) {
8055           SpaceshipCandidates->NoteCandidates(
8056               S, Args,
8057               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8058                                                       Args, FD->getLocation()));
8059           S.Diag(Subobj.Loc,
8060                  diag::note_defaulted_comparison_no_viable_function_synthesized)
8061               << (OO == OO_EqualEqual ? 0 : 1);
8062         }
8063 
8064         CandidateSet.NoteCandidates(
8065             S, Args,
8066             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8067                                             FD->getLocation()));
8068       }
8069       R = Result::deleted();
8070       break;
8071     }
8072 
8073     return R;
8074   }
8075 };
8076 
8077 /// A list of statements.
8078 struct StmtListResult {
8079   bool IsInvalid = false;
8080   llvm::SmallVector<Stmt*, 16> Stmts;
8081 
8082   bool add(const StmtResult &S) {
8083     IsInvalid |= S.isInvalid();
8084     if (IsInvalid)
8085       return true;
8086     Stmts.push_back(S.get());
8087     return false;
8088   }
8089 };
8090 
8091 /// A visitor over the notional body of a defaulted comparison that synthesizes
8092 /// the actual body.
8093 class DefaultedComparisonSynthesizer
8094     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8095                                         StmtListResult, StmtResult,
8096                                         std::pair<ExprResult, ExprResult>> {
8097   SourceLocation Loc;
8098   unsigned ArrayDepth = 0;
8099 
8100 public:
8101   using Base = DefaultedComparisonVisitor;
8102   using ExprPair = std::pair<ExprResult, ExprResult>;
8103 
8104   friend Base;
8105 
8106   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8107                                  DefaultedComparisonKind DCK,
8108                                  SourceLocation BodyLoc)
8109       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8110 
8111   /// Build a suitable function body for this defaulted comparison operator.
8112   StmtResult build() {
8113     Sema::CompoundScopeRAII CompoundScope(S);
8114 
8115     StmtListResult Stmts = visit();
8116     if (Stmts.IsInvalid)
8117       return StmtError();
8118 
8119     ExprResult RetVal;
8120     switch (DCK) {
8121     case DefaultedComparisonKind::None:
8122       llvm_unreachable("not a defaulted comparison");
8123 
8124     case DefaultedComparisonKind::Equal: {
8125       // C++2a [class.eq]p3:
8126       //   [...] compar[e] the corresponding elements [...] until the first
8127       //   index i where xi == yi yields [...] false. If no such index exists,
8128       //   V is true. Otherwise, V is false.
8129       //
8130       // Join the comparisons with '&&'s and return the result. Use a right
8131       // fold (traversing the conditions right-to-left), because that
8132       // short-circuits more naturally.
8133       auto OldStmts = std::move(Stmts.Stmts);
8134       Stmts.Stmts.clear();
8135       ExprResult CmpSoFar;
8136       // Finish a particular comparison chain.
8137       auto FinishCmp = [&] {
8138         if (Expr *Prior = CmpSoFar.get()) {
8139           // Convert the last expression to 'return ...;'
8140           if (RetVal.isUnset() && Stmts.Stmts.empty())
8141             RetVal = CmpSoFar;
8142           // Convert any prior comparison to 'if (!(...)) return false;'
8143           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8144             return true;
8145           CmpSoFar = ExprResult();
8146         }
8147         return false;
8148       };
8149       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8150         Expr *E = dyn_cast<Expr>(EAsStmt);
8151         if (!E) {
8152           // Found an array comparison.
8153           if (FinishCmp() || Stmts.add(EAsStmt))
8154             return StmtError();
8155           continue;
8156         }
8157 
8158         if (CmpSoFar.isUnset()) {
8159           CmpSoFar = E;
8160           continue;
8161         }
8162         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8163         if (CmpSoFar.isInvalid())
8164           return StmtError();
8165       }
8166       if (FinishCmp())
8167         return StmtError();
8168       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8169       //   If no such index exists, V is true.
8170       if (RetVal.isUnset())
8171         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8172       break;
8173     }
8174 
8175     case DefaultedComparisonKind::ThreeWay: {
8176       // Per C++2a [class.spaceship]p3, as a fallback add:
8177       // return static_cast<R>(std::strong_ordering::equal);
8178       QualType StrongOrdering = S.CheckComparisonCategoryType(
8179           ComparisonCategoryType::StrongOrdering, Loc,
8180           Sema::ComparisonCategoryUsage::DefaultedOperator);
8181       if (StrongOrdering.isNull())
8182         return StmtError();
8183       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8184                              .getValueInfo(ComparisonCategoryResult::Equal)
8185                              ->VD;
8186       RetVal = getDecl(EqualVD);
8187       if (RetVal.isInvalid())
8188         return StmtError();
8189       RetVal = buildStaticCastToR(RetVal.get());
8190       break;
8191     }
8192 
8193     case DefaultedComparisonKind::NotEqual:
8194     case DefaultedComparisonKind::Relational:
8195       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8196       break;
8197     }
8198 
8199     // Build the final return statement.
8200     if (RetVal.isInvalid())
8201       return StmtError();
8202     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8203     if (ReturnStmt.isInvalid())
8204       return StmtError();
8205     Stmts.Stmts.push_back(ReturnStmt.get());
8206 
8207     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8208   }
8209 
8210 private:
8211   ExprResult getDecl(ValueDecl *VD) {
8212     return S.BuildDeclarationNameExpr(
8213         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8214   }
8215 
8216   ExprResult getParam(unsigned I) {
8217     ParmVarDecl *PD = FD->getParamDecl(I);
8218     return getDecl(PD);
8219   }
8220 
8221   ExprPair getCompleteObject() {
8222     unsigned Param = 0;
8223     ExprResult LHS;
8224     if (isa<CXXMethodDecl>(FD)) {
8225       // LHS is '*this'.
8226       LHS = S.ActOnCXXThis(Loc);
8227       if (!LHS.isInvalid())
8228         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8229     } else {
8230       LHS = getParam(Param++);
8231     }
8232     ExprResult RHS = getParam(Param++);
8233     assert(Param == FD->getNumParams());
8234     return {LHS, RHS};
8235   }
8236 
8237   ExprPair getBase(CXXBaseSpecifier *Base) {
8238     ExprPair Obj = getCompleteObject();
8239     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8240       return {ExprError(), ExprError()};
8241     CXXCastPath Path = {Base};
8242     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8243                                 CK_DerivedToBase, VK_LValue, &Path),
8244             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8245                                 CK_DerivedToBase, VK_LValue, &Path)};
8246   }
8247 
8248   ExprPair getField(FieldDecl *Field) {
8249     ExprPair Obj = getCompleteObject();
8250     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8251       return {ExprError(), ExprError()};
8252 
8253     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8254     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8255     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8256                                       CXXScopeSpec(), Field, Found, NameInfo),
8257             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8258                                       CXXScopeSpec(), Field, Found, NameInfo)};
8259   }
8260 
8261   // FIXME: When expanding a subobject, register a note in the code synthesis
8262   // stack to say which subobject we're comparing.
8263 
8264   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8265     if (Cond.isInvalid())
8266       return StmtError();
8267 
8268     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8269     if (NotCond.isInvalid())
8270       return StmtError();
8271 
8272     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8273     assert(!False.isInvalid() && "should never fail");
8274     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8275     if (ReturnFalse.isInvalid())
8276       return StmtError();
8277 
8278     return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8279                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8280                                           Sema::ConditionKind::Boolean),
8281                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8282   }
8283 
8284   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8285                                  ExprPair Subobj) {
8286     QualType SizeType = S.Context.getSizeType();
8287     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8288 
8289     // Build 'size_t i$n = 0'.
8290     IdentifierInfo *IterationVarName = nullptr;
8291     {
8292       SmallString<8> Str;
8293       llvm::raw_svector_ostream OS(Str);
8294       OS << "i" << ArrayDepth;
8295       IterationVarName = &S.Context.Idents.get(OS.str());
8296     }
8297     VarDecl *IterationVar = VarDecl::Create(
8298         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8299         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8300     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8301     IterationVar->setInit(
8302         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8303     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8304 
8305     auto IterRef = [&] {
8306       ExprResult Ref = S.BuildDeclarationNameExpr(
8307           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8308           IterationVar);
8309       assert(!Ref.isInvalid() && "can't reference our own variable?");
8310       return Ref.get();
8311     };
8312 
8313     // Build 'i$n != Size'.
8314     ExprResult Cond = S.CreateBuiltinBinOp(
8315         Loc, BO_NE, IterRef(),
8316         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8317     assert(!Cond.isInvalid() && "should never fail");
8318 
8319     // Build '++i$n'.
8320     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8321     assert(!Inc.isInvalid() && "should never fail");
8322 
8323     // Build 'a[i$n]' and 'b[i$n]'.
8324     auto Index = [&](ExprResult E) {
8325       if (E.isInvalid())
8326         return ExprError();
8327       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8328     };
8329     Subobj.first = Index(Subobj.first);
8330     Subobj.second = Index(Subobj.second);
8331 
8332     // Compare the array elements.
8333     ++ArrayDepth;
8334     StmtResult Substmt = visitSubobject(Type, Subobj);
8335     --ArrayDepth;
8336 
8337     if (Substmt.isInvalid())
8338       return StmtError();
8339 
8340     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8341     // For outer levels or for an 'operator<=>' we already have a suitable
8342     // statement that returns as necessary.
8343     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8344       assert(DCK == DefaultedComparisonKind::Equal &&
8345              "should have non-expression statement");
8346       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8347       if (Substmt.isInvalid())
8348         return StmtError();
8349     }
8350 
8351     // Build 'for (...) ...'
8352     return S.ActOnForStmt(Loc, Loc, Init,
8353                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8354                                            Sema::ConditionKind::Boolean),
8355                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8356                           Substmt.get());
8357   }
8358 
8359   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8360     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8361       return StmtError();
8362 
8363     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8364     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8365     ExprResult Op;
8366     if (Type->isOverloadableType())
8367       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8368                                    Obj.second.get(), /*PerformADL=*/true,
8369                                    /*AllowRewrittenCandidates=*/true, FD);
8370     else
8371       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8372     if (Op.isInvalid())
8373       return StmtError();
8374 
8375     switch (DCK) {
8376     case DefaultedComparisonKind::None:
8377       llvm_unreachable("not a defaulted comparison");
8378 
8379     case DefaultedComparisonKind::Equal:
8380       // Per C++2a [class.eq]p2, each comparison is individually contextually
8381       // converted to bool.
8382       Op = S.PerformContextuallyConvertToBool(Op.get());
8383       if (Op.isInvalid())
8384         return StmtError();
8385       return Op.get();
8386 
8387     case DefaultedComparisonKind::ThreeWay: {
8388       // Per C++2a [class.spaceship]p3, form:
8389       //   if (R cmp = static_cast<R>(op); cmp != 0)
8390       //     return cmp;
8391       QualType R = FD->getReturnType();
8392       Op = buildStaticCastToR(Op.get());
8393       if (Op.isInvalid())
8394         return StmtError();
8395 
8396       // R cmp = ...;
8397       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8398       VarDecl *VD =
8399           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8400                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8401       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8402       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8403 
8404       // cmp != 0
8405       ExprResult VDRef = getDecl(VD);
8406       if (VDRef.isInvalid())
8407         return StmtError();
8408       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8409       Expr *Zero =
8410           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8411       ExprResult Comp;
8412       if (VDRef.get()->getType()->isOverloadableType())
8413         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8414                                        true, FD);
8415       else
8416         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8417       if (Comp.isInvalid())
8418         return StmtError();
8419       Sema::ConditionResult Cond = S.ActOnCondition(
8420           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8421       if (Cond.isInvalid())
8422         return StmtError();
8423 
8424       // return cmp;
8425       VDRef = getDecl(VD);
8426       if (VDRef.isInvalid())
8427         return StmtError();
8428       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8429       if (ReturnStmt.isInvalid())
8430         return StmtError();
8431 
8432       // if (...)
8433       return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8434                            Loc, ReturnStmt.get(),
8435                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8436     }
8437 
8438     case DefaultedComparisonKind::NotEqual:
8439     case DefaultedComparisonKind::Relational:
8440       // C++2a [class.compare.secondary]p2:
8441       //   Otherwise, the operator function yields x @ y.
8442       return Op.get();
8443     }
8444     llvm_unreachable("");
8445   }
8446 
8447   /// Build "static_cast<R>(E)".
8448   ExprResult buildStaticCastToR(Expr *E) {
8449     QualType R = FD->getReturnType();
8450     assert(!R->isUndeducedType() && "type should have been deduced already");
8451 
8452     // Don't bother forming a no-op cast in the common case.
8453     if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8454       return E;
8455     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8456                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8457                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8458   }
8459 };
8460 }
8461 
8462 /// Perform the unqualified lookups that might be needed to form a defaulted
8463 /// comparison function for the given operator.
8464 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8465                                                   UnresolvedSetImpl &Operators,
8466                                                   OverloadedOperatorKind Op) {
8467   auto Lookup = [&](OverloadedOperatorKind OO) {
8468     Self.LookupOverloadedOperatorName(OO, S, Operators);
8469   };
8470 
8471   // Every defaulted operator looks up itself.
8472   Lookup(Op);
8473   // ... and the rewritten form of itself, if any.
8474   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8475     Lookup(ExtraOp);
8476 
8477   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8478   // synthesize a three-way comparison from '<' and '=='. In a dependent
8479   // context, we also need to look up '==' in case we implicitly declare a
8480   // defaulted 'operator=='.
8481   if (Op == OO_Spaceship) {
8482     Lookup(OO_ExclaimEqual);
8483     Lookup(OO_Less);
8484     Lookup(OO_EqualEqual);
8485   }
8486 }
8487 
8488 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8489                                               DefaultedComparisonKind DCK) {
8490   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8491 
8492   // Perform any unqualified lookups we're going to need to default this
8493   // function.
8494   if (S) {
8495     UnresolvedSet<32> Operators;
8496     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8497                                           FD->getOverloadedOperator());
8498     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8499         Context, Operators.pairs()));
8500   }
8501 
8502   // C++2a [class.compare.default]p1:
8503   //   A defaulted comparison operator function for some class C shall be a
8504   //   non-template function declared in the member-specification of C that is
8505   //    -- a non-static const member of C having one parameter of type
8506   //       const C&, or
8507   //    -- a friend of C having two parameters of type const C& or two
8508   //       parameters of type C.
8509 
8510   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8511   bool IsMethod = isa<CXXMethodDecl>(FD);
8512   if (IsMethod) {
8513     auto *MD = cast<CXXMethodDecl>(FD);
8514     assert(!MD->isStatic() && "comparison function cannot be a static member");
8515 
8516     // If we're out-of-class, this is the class we're comparing.
8517     if (!RD)
8518       RD = MD->getParent();
8519 
8520     if (!MD->isConst()) {
8521       SourceLocation InsertLoc;
8522       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8523         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8524       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8525       // corresponding defaulted 'operator<=>' already.
8526       if (!MD->isImplicit()) {
8527         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8528             << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8529       }
8530 
8531       // Add the 'const' to the type to recover.
8532       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8533       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8534       EPI.TypeQuals.addConst();
8535       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8536                                           FPT->getParamTypes(), EPI));
8537     }
8538   }
8539 
8540   if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8541     // Let's not worry about using a variadic template pack here -- who would do
8542     // such a thing?
8543     Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8544         << int(IsMethod) << int(DCK);
8545     return true;
8546   }
8547 
8548   const ParmVarDecl *KnownParm = nullptr;
8549   for (const ParmVarDecl *Param : FD->parameters()) {
8550     QualType ParmTy = Param->getType();
8551     if (ParmTy->isDependentType())
8552       continue;
8553     if (!KnownParm) {
8554       auto CTy = ParmTy;
8555       // Is it `T const &`?
8556       bool Ok = !IsMethod;
8557       QualType ExpectedTy;
8558       if (RD)
8559         ExpectedTy = Context.getRecordType(RD);
8560       if (auto *Ref = CTy->getAs<ReferenceType>()) {
8561         CTy = Ref->getPointeeType();
8562         if (RD)
8563           ExpectedTy.addConst();
8564         Ok = true;
8565       }
8566 
8567       // Is T a class?
8568       if (!Ok) {
8569       } else if (RD) {
8570         if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8571           Ok = false;
8572       } else if (auto *CRD = CTy->getAsRecordDecl()) {
8573         RD = cast<CXXRecordDecl>(CRD);
8574       } else {
8575         Ok = false;
8576       }
8577 
8578       if (Ok) {
8579         KnownParm = Param;
8580       } else {
8581         // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8582         // corresponding defaulted 'operator<=>' already.
8583         if (!FD->isImplicit()) {
8584           if (RD) {
8585             QualType PlainTy = Context.getRecordType(RD);
8586             QualType RefTy =
8587                 Context.getLValueReferenceType(PlainTy.withConst());
8588             Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8589                 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8590                 << Param->getSourceRange();
8591           } else {
8592             assert(!IsMethod && "should know expected type for method");
8593             Diag(FD->getLocation(),
8594                  diag::err_defaulted_comparison_param_unknown)
8595                 << int(DCK) << ParmTy << Param->getSourceRange();
8596           }
8597         }
8598         return true;
8599       }
8600     } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8601       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8602           << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8603           << ParmTy << Param->getSourceRange();
8604       return true;
8605     }
8606   }
8607 
8608   assert(RD && "must have determined class");
8609   if (IsMethod) {
8610   } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8611     // In-class, must be a friend decl.
8612     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8613   } else {
8614     // Out of class, require the defaulted comparison to be a friend (of a
8615     // complete type).
8616     if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8617                             diag::err_defaulted_comparison_not_friend, int(DCK),
8618                             int(1)))
8619       return true;
8620 
8621     if (llvm::find_if(RD->friends(), [&](const FriendDecl *F) {
8622           return FD->getCanonicalDecl() ==
8623                  F->getFriendDecl()->getCanonicalDecl();
8624         }) == RD->friends().end()) {
8625       Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8626           << int(DCK) << int(0) << RD;
8627       Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8628       return true;
8629     }
8630   }
8631 
8632   // C++2a [class.eq]p1, [class.rel]p1:
8633   //   A [defaulted comparison other than <=>] shall have a declared return
8634   //   type bool.
8635   if (DCK != DefaultedComparisonKind::ThreeWay &&
8636       !FD->getDeclaredReturnType()->isDependentType() &&
8637       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8638     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8639         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8640         << FD->getReturnTypeSourceRange();
8641     return true;
8642   }
8643   // C++2a [class.spaceship]p2 [P2002R0]:
8644   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8645   //   R shall not contain a placeholder type.
8646   if (DCK == DefaultedComparisonKind::ThreeWay &&
8647       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8648       !Context.hasSameType(FD->getDeclaredReturnType(),
8649                            Context.getAutoDeductType())) {
8650     Diag(FD->getLocation(),
8651          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8652         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8653         << FD->getReturnTypeSourceRange();
8654     return true;
8655   }
8656 
8657   // For a defaulted function in a dependent class, defer all remaining checks
8658   // until instantiation.
8659   if (RD->isDependentType())
8660     return false;
8661 
8662   // Determine whether the function should be defined as deleted.
8663   DefaultedComparisonInfo Info =
8664       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8665 
8666   bool First = FD == FD->getCanonicalDecl();
8667 
8668   // If we want to delete the function, then do so; there's nothing else to
8669   // check in that case.
8670   if (Info.Deleted) {
8671     if (!First) {
8672       // C++11 [dcl.fct.def.default]p4:
8673       //   [For a] user-provided explicitly-defaulted function [...] if such a
8674       //   function is implicitly defined as deleted, the program is ill-formed.
8675       //
8676       // This is really just a consequence of the general rule that you can
8677       // only delete a function on its first declaration.
8678       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8679           << FD->isImplicit() << (int)DCK;
8680       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8681                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8682           .visit();
8683       return true;
8684     }
8685 
8686     SetDeclDeleted(FD, FD->getLocation());
8687     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8688       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8689           << (int)DCK;
8690       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8691                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8692           .visit();
8693     }
8694     return false;
8695   }
8696 
8697   // C++2a [class.spaceship]p2:
8698   //   The return type is deduced as the common comparison type of R0, R1, ...
8699   if (DCK == DefaultedComparisonKind::ThreeWay &&
8700       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8701     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8702     if (RetLoc.isInvalid())
8703       RetLoc = FD->getBeginLoc();
8704     // FIXME: Should we really care whether we have the complete type and the
8705     // 'enumerator' constants here? A forward declaration seems sufficient.
8706     QualType Cat = CheckComparisonCategoryType(
8707         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8708     if (Cat.isNull())
8709       return true;
8710     Context.adjustDeducedFunctionResultType(
8711         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8712   }
8713 
8714   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8715   //   An explicitly-defaulted function that is not defined as deleted may be
8716   //   declared constexpr or consteval only if it is constexpr-compatible.
8717   // C++2a [class.compare.default]p3 [P2002R0]:
8718   //   A defaulted comparison function is constexpr-compatible if it satisfies
8719   //   the requirements for a constexpr function [...]
8720   // The only relevant requirements are that the parameter and return types are
8721   // literal types. The remaining conditions are checked by the analyzer.
8722   if (FD->isConstexpr()) {
8723     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8724         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8725         !Info.Constexpr) {
8726       Diag(FD->getBeginLoc(),
8727            diag::err_incorrect_defaulted_comparison_constexpr)
8728           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8729       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8730                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8731           .visit();
8732     }
8733   }
8734 
8735   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8736   //   If a constexpr-compatible function is explicitly defaulted on its first
8737   //   declaration, it is implicitly considered to be constexpr.
8738   // FIXME: Only applying this to the first declaration seems problematic, as
8739   // simple reorderings can affect the meaning of the program.
8740   if (First && !FD->isConstexpr() && Info.Constexpr)
8741     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8742 
8743   // C++2a [except.spec]p3:
8744   //   If a declaration of a function does not have a noexcept-specifier
8745   //   [and] is defaulted on its first declaration, [...] the exception
8746   //   specification is as specified below
8747   if (FD->getExceptionSpecType() == EST_None) {
8748     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8749     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8750     EPI.ExceptionSpec.Type = EST_Unevaluated;
8751     EPI.ExceptionSpec.SourceDecl = FD;
8752     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8753                                         FPT->getParamTypes(), EPI));
8754   }
8755 
8756   return false;
8757 }
8758 
8759 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8760                                              FunctionDecl *Spaceship) {
8761   Sema::CodeSynthesisContext Ctx;
8762   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8763   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8764   Ctx.Entity = Spaceship;
8765   pushCodeSynthesisContext(Ctx);
8766 
8767   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8768     EqualEqual->setImplicit();
8769 
8770   popCodeSynthesisContext();
8771 }
8772 
8773 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8774                                      DefaultedComparisonKind DCK) {
8775   assert(FD->isDefaulted() && !FD->isDeleted() &&
8776          !FD->doesThisDeclarationHaveABody());
8777   if (FD->willHaveBody() || FD->isInvalidDecl())
8778     return;
8779 
8780   SynthesizedFunctionScope Scope(*this, FD);
8781 
8782   // Add a context note for diagnostics produced after this point.
8783   Scope.addContextNote(UseLoc);
8784 
8785   {
8786     // Build and set up the function body.
8787     // The first parameter has type maybe-ref-to maybe-const T, use that to get
8788     // the type of the class being compared.
8789     auto PT = FD->getParamDecl(0)->getType();
8790     CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
8791     SourceLocation BodyLoc =
8792         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8793     StmtResult Body =
8794         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8795     if (Body.isInvalid()) {
8796       FD->setInvalidDecl();
8797       return;
8798     }
8799     FD->setBody(Body.get());
8800     FD->markUsed(Context);
8801   }
8802 
8803   // The exception specification is needed because we are defining the
8804   // function. Note that this will reuse the body we just built.
8805   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8806 
8807   if (ASTMutationListener *L = getASTMutationListener())
8808     L->CompletedImplicitDefinition(FD);
8809 }
8810 
8811 static Sema::ImplicitExceptionSpecification
8812 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8813                                         FunctionDecl *FD,
8814                                         Sema::DefaultedComparisonKind DCK) {
8815   ComputingExceptionSpec CES(S, FD, Loc);
8816   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8817 
8818   if (FD->isInvalidDecl())
8819     return ExceptSpec;
8820 
8821   // The common case is that we just defined the comparison function. In that
8822   // case, just look at whether the body can throw.
8823   if (FD->hasBody()) {
8824     ExceptSpec.CalledStmt(FD->getBody());
8825   } else {
8826     // Otherwise, build a body so we can check it. This should ideally only
8827     // happen when we're not actually marking the function referenced. (This is
8828     // only really important for efficiency: we don't want to build and throw
8829     // away bodies for comparison functions more than we strictly need to.)
8830 
8831     // Pretend to synthesize the function body in an unevaluated context.
8832     // Note that we can't actually just go ahead and define the function here:
8833     // we are not permitted to mark its callees as referenced.
8834     Sema::SynthesizedFunctionScope Scope(S, FD);
8835     EnterExpressionEvaluationContext Context(
8836         S, Sema::ExpressionEvaluationContext::Unevaluated);
8837 
8838     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8839     SourceLocation BodyLoc =
8840         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8841     StmtResult Body =
8842         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8843     if (!Body.isInvalid())
8844       ExceptSpec.CalledStmt(Body.get());
8845 
8846     // FIXME: Can we hold onto this body and just transform it to potentially
8847     // evaluated when we're asked to define the function rather than rebuilding
8848     // it? Either that, or we should only build the bits of the body that we
8849     // need (the expressions, not the statements).
8850   }
8851 
8852   return ExceptSpec;
8853 }
8854 
8855 void Sema::CheckDelayedMemberExceptionSpecs() {
8856   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8857   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8858 
8859   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8860   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8861 
8862   // Perform any deferred checking of exception specifications for virtual
8863   // destructors.
8864   for (auto &Check : Overriding)
8865     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8866 
8867   // Perform any deferred checking of exception specifications for befriended
8868   // special members.
8869   for (auto &Check : Equivalent)
8870     CheckEquivalentExceptionSpec(Check.second, Check.first);
8871 }
8872 
8873 namespace {
8874 /// CRTP base class for visiting operations performed by a special member
8875 /// function (or inherited constructor).
8876 template<typename Derived>
8877 struct SpecialMemberVisitor {
8878   Sema &S;
8879   CXXMethodDecl *MD;
8880   Sema::CXXSpecialMember CSM;
8881   Sema::InheritedConstructorInfo *ICI;
8882 
8883   // Properties of the special member, computed for convenience.
8884   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8885 
8886   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8887                        Sema::InheritedConstructorInfo *ICI)
8888       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8889     switch (CSM) {
8890     case Sema::CXXDefaultConstructor:
8891     case Sema::CXXCopyConstructor:
8892     case Sema::CXXMoveConstructor:
8893       IsConstructor = true;
8894       break;
8895     case Sema::CXXCopyAssignment:
8896     case Sema::CXXMoveAssignment:
8897       IsAssignment = true;
8898       break;
8899     case Sema::CXXDestructor:
8900       break;
8901     case Sema::CXXInvalid:
8902       llvm_unreachable("invalid special member kind");
8903     }
8904 
8905     if (MD->getNumParams()) {
8906       if (const ReferenceType *RT =
8907               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8908         ConstArg = RT->getPointeeType().isConstQualified();
8909     }
8910   }
8911 
8912   Derived &getDerived() { return static_cast<Derived&>(*this); }
8913 
8914   /// Is this a "move" special member?
8915   bool isMove() const {
8916     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8917   }
8918 
8919   /// Look up the corresponding special member in the given class.
8920   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8921                                              unsigned Quals, bool IsMutable) {
8922     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8923                                        ConstArg && !IsMutable);
8924   }
8925 
8926   /// Look up the constructor for the specified base class to see if it's
8927   /// overridden due to this being an inherited constructor.
8928   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8929     if (!ICI)
8930       return {};
8931     assert(CSM == Sema::CXXDefaultConstructor);
8932     auto *BaseCtor =
8933       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8934     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8935       return MD;
8936     return {};
8937   }
8938 
8939   /// A base or member subobject.
8940   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8941 
8942   /// Get the location to use for a subobject in diagnostics.
8943   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8944     // FIXME: For an indirect virtual base, the direct base leading to
8945     // the indirect virtual base would be a more useful choice.
8946     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8947       return B->getBaseTypeLoc();
8948     else
8949       return Subobj.get<FieldDecl*>()->getLocation();
8950   }
8951 
8952   enum BasesToVisit {
8953     /// Visit all non-virtual (direct) bases.
8954     VisitNonVirtualBases,
8955     /// Visit all direct bases, virtual or not.
8956     VisitDirectBases,
8957     /// Visit all non-virtual bases, and all virtual bases if the class
8958     /// is not abstract.
8959     VisitPotentiallyConstructedBases,
8960     /// Visit all direct or virtual bases.
8961     VisitAllBases
8962   };
8963 
8964   // Visit the bases and members of the class.
8965   bool visit(BasesToVisit Bases) {
8966     CXXRecordDecl *RD = MD->getParent();
8967 
8968     if (Bases == VisitPotentiallyConstructedBases)
8969       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8970 
8971     for (auto &B : RD->bases())
8972       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8973           getDerived().visitBase(&B))
8974         return true;
8975 
8976     if (Bases == VisitAllBases)
8977       for (auto &B : RD->vbases())
8978         if (getDerived().visitBase(&B))
8979           return true;
8980 
8981     for (auto *F : RD->fields())
8982       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8983           getDerived().visitField(F))
8984         return true;
8985 
8986     return false;
8987   }
8988 };
8989 }
8990 
8991 namespace {
8992 struct SpecialMemberDeletionInfo
8993     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8994   bool Diagnose;
8995 
8996   SourceLocation Loc;
8997 
8998   bool AllFieldsAreConst;
8999 
9000   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9001                             Sema::CXXSpecialMember CSM,
9002                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9003       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9004         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9005 
9006   bool inUnion() const { return MD->getParent()->isUnion(); }
9007 
9008   Sema::CXXSpecialMember getEffectiveCSM() {
9009     return ICI ? Sema::CXXInvalid : CSM;
9010   }
9011 
9012   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9013 
9014   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9015   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9016 
9017   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9018   bool shouldDeleteForField(FieldDecl *FD);
9019   bool shouldDeleteForAllConstMembers();
9020 
9021   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9022                                      unsigned Quals);
9023   bool shouldDeleteForSubobjectCall(Subobject Subobj,
9024                                     Sema::SpecialMemberOverloadResult SMOR,
9025                                     bool IsDtorCallInCtor);
9026 
9027   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9028 };
9029 }
9030 
9031 /// Is the given special member inaccessible when used on the given
9032 /// sub-object.
9033 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9034                                              CXXMethodDecl *target) {
9035   /// If we're operating on a base class, the object type is the
9036   /// type of this special member.
9037   QualType objectTy;
9038   AccessSpecifier access = target->getAccess();
9039   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9040     objectTy = S.Context.getTypeDeclType(MD->getParent());
9041     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9042 
9043   // If we're operating on a field, the object type is the type of the field.
9044   } else {
9045     objectTy = S.Context.getTypeDeclType(target->getParent());
9046   }
9047 
9048   return S.isMemberAccessibleForDeletion(
9049       target->getParent(), DeclAccessPair::make(target, access), objectTy);
9050 }
9051 
9052 /// Check whether we should delete a special member due to the implicit
9053 /// definition containing a call to a special member of a subobject.
9054 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9055     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9056     bool IsDtorCallInCtor) {
9057   CXXMethodDecl *Decl = SMOR.getMethod();
9058   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9059 
9060   int DiagKind = -1;
9061 
9062   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9063     DiagKind = !Decl ? 0 : 1;
9064   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9065     DiagKind = 2;
9066   else if (!isAccessible(Subobj, Decl))
9067     DiagKind = 3;
9068   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9069            !Decl->isTrivial()) {
9070     // A member of a union must have a trivial corresponding special member.
9071     // As a weird special case, a destructor call from a union's constructor
9072     // must be accessible and non-deleted, but need not be trivial. Such a
9073     // destructor is never actually called, but is semantically checked as
9074     // if it were.
9075     DiagKind = 4;
9076   }
9077 
9078   if (DiagKind == -1)
9079     return false;
9080 
9081   if (Diagnose) {
9082     if (Field) {
9083       S.Diag(Field->getLocation(),
9084              diag::note_deleted_special_member_class_subobject)
9085         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9086         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9087     } else {
9088       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9089       S.Diag(Base->getBeginLoc(),
9090              diag::note_deleted_special_member_class_subobject)
9091           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9092           << Base->getType() << DiagKind << IsDtorCallInCtor
9093           << /*IsObjCPtr*/false;
9094     }
9095 
9096     if (DiagKind == 1)
9097       S.NoteDeletedFunction(Decl);
9098     // FIXME: Explain inaccessibility if DiagKind == 3.
9099   }
9100 
9101   return true;
9102 }
9103 
9104 /// Check whether we should delete a special member function due to having a
9105 /// direct or virtual base class or non-static data member of class type M.
9106 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9107     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9108   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9109   bool IsMutable = Field && Field->isMutable();
9110 
9111   // C++11 [class.ctor]p5:
9112   // -- any direct or virtual base class, or non-static data member with no
9113   //    brace-or-equal-initializer, has class type M (or array thereof) and
9114   //    either M has no default constructor or overload resolution as applied
9115   //    to M's default constructor results in an ambiguity or in a function
9116   //    that is deleted or inaccessible
9117   // C++11 [class.copy]p11, C++11 [class.copy]p23:
9118   // -- a direct or virtual base class B that cannot be copied/moved because
9119   //    overload resolution, as applied to B's corresponding special member,
9120   //    results in an ambiguity or a function that is deleted or inaccessible
9121   //    from the defaulted special member
9122   // C++11 [class.dtor]p5:
9123   // -- any direct or virtual base class [...] has a type with a destructor
9124   //    that is deleted or inaccessible
9125   if (!(CSM == Sema::CXXDefaultConstructor &&
9126         Field && Field->hasInClassInitializer()) &&
9127       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9128                                    false))
9129     return true;
9130 
9131   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9132   // -- any direct or virtual base class or non-static data member has a
9133   //    type with a destructor that is deleted or inaccessible
9134   if (IsConstructor) {
9135     Sema::SpecialMemberOverloadResult SMOR =
9136         S.LookupSpecialMember(Class, Sema::CXXDestructor,
9137                               false, false, false, false, false);
9138     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9139       return true;
9140   }
9141 
9142   return false;
9143 }
9144 
9145 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9146     FieldDecl *FD, QualType FieldType) {
9147   // The defaulted special functions are defined as deleted if this is a variant
9148   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9149   // type under ARC.
9150   if (!FieldType.hasNonTrivialObjCLifetime())
9151     return false;
9152 
9153   // Don't make the defaulted default constructor defined as deleted if the
9154   // member has an in-class initializer.
9155   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9156     return false;
9157 
9158   if (Diagnose) {
9159     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9160     S.Diag(FD->getLocation(),
9161            diag::note_deleted_special_member_class_subobject)
9162         << getEffectiveCSM() << ParentClass << /*IsField*/true
9163         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9164   }
9165 
9166   return true;
9167 }
9168 
9169 /// Check whether we should delete a special member function due to the class
9170 /// having a particular direct or virtual base class.
9171 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9172   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9173   // If program is correct, BaseClass cannot be null, but if it is, the error
9174   // must be reported elsewhere.
9175   if (!BaseClass)
9176     return false;
9177   // If we have an inheriting constructor, check whether we're calling an
9178   // inherited constructor instead of a default constructor.
9179   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9180   if (auto *BaseCtor = SMOR.getMethod()) {
9181     // Note that we do not check access along this path; other than that,
9182     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9183     // FIXME: Check that the base has a usable destructor! Sink this into
9184     // shouldDeleteForClassSubobject.
9185     if (BaseCtor->isDeleted() && Diagnose) {
9186       S.Diag(Base->getBeginLoc(),
9187              diag::note_deleted_special_member_class_subobject)
9188           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9189           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9190           << /*IsObjCPtr*/false;
9191       S.NoteDeletedFunction(BaseCtor);
9192     }
9193     return BaseCtor->isDeleted();
9194   }
9195   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9196 }
9197 
9198 /// Check whether we should delete a special member function due to the class
9199 /// having a particular non-static data member.
9200 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9201   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9202   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9203 
9204   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9205     return true;
9206 
9207   if (CSM == Sema::CXXDefaultConstructor) {
9208     // For a default constructor, all references must be initialized in-class
9209     // and, if a union, it must have a non-const member.
9210     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9211       if (Diagnose)
9212         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9213           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9214       return true;
9215     }
9216     // C++11 [class.ctor]p5: any non-variant non-static data member of
9217     // const-qualified type (or array thereof) with no
9218     // brace-or-equal-initializer does not have a user-provided default
9219     // constructor.
9220     if (!inUnion() && FieldType.isConstQualified() &&
9221         !FD->hasInClassInitializer() &&
9222         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
9223       if (Diagnose)
9224         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9225           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9226       return true;
9227     }
9228 
9229     if (inUnion() && !FieldType.isConstQualified())
9230       AllFieldsAreConst = false;
9231   } else if (CSM == Sema::CXXCopyConstructor) {
9232     // For a copy constructor, data members must not be of rvalue reference
9233     // type.
9234     if (FieldType->isRValueReferenceType()) {
9235       if (Diagnose)
9236         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9237           << MD->getParent() << FD << FieldType;
9238       return true;
9239     }
9240   } else if (IsAssignment) {
9241     // For an assignment operator, data members must not be of reference type.
9242     if (FieldType->isReferenceType()) {
9243       if (Diagnose)
9244         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9245           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9246       return true;
9247     }
9248     if (!FieldRecord && FieldType.isConstQualified()) {
9249       // C++11 [class.copy]p23:
9250       // -- a non-static data member of const non-class type (or array thereof)
9251       if (Diagnose)
9252         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9253           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9254       return true;
9255     }
9256   }
9257 
9258   if (FieldRecord) {
9259     // Some additional restrictions exist on the variant members.
9260     if (!inUnion() && FieldRecord->isUnion() &&
9261         FieldRecord->isAnonymousStructOrUnion()) {
9262       bool AllVariantFieldsAreConst = true;
9263 
9264       // FIXME: Handle anonymous unions declared within anonymous unions.
9265       for (auto *UI : FieldRecord->fields()) {
9266         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9267 
9268         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9269           return true;
9270 
9271         if (!UnionFieldType.isConstQualified())
9272           AllVariantFieldsAreConst = false;
9273 
9274         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9275         if (UnionFieldRecord &&
9276             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9277                                           UnionFieldType.getCVRQualifiers()))
9278           return true;
9279       }
9280 
9281       // At least one member in each anonymous union must be non-const
9282       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9283           !FieldRecord->field_empty()) {
9284         if (Diagnose)
9285           S.Diag(FieldRecord->getLocation(),
9286                  diag::note_deleted_default_ctor_all_const)
9287             << !!ICI << MD->getParent() << /*anonymous union*/1;
9288         return true;
9289       }
9290 
9291       // Don't check the implicit member of the anonymous union type.
9292       // This is technically non-conformant but supported, and we have a
9293       // diagnostic for this elsewhere.
9294       return false;
9295     }
9296 
9297     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9298                                       FieldType.getCVRQualifiers()))
9299       return true;
9300   }
9301 
9302   return false;
9303 }
9304 
9305 /// C++11 [class.ctor] p5:
9306 ///   A defaulted default constructor for a class X is defined as deleted if
9307 /// X is a union and all of its variant members are of const-qualified type.
9308 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9309   // This is a silly definition, because it gives an empty union a deleted
9310   // default constructor. Don't do that.
9311   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9312     bool AnyFields = false;
9313     for (auto *F : MD->getParent()->fields())
9314       if ((AnyFields = !F->isUnnamedBitfield()))
9315         break;
9316     if (!AnyFields)
9317       return false;
9318     if (Diagnose)
9319       S.Diag(MD->getParent()->getLocation(),
9320              diag::note_deleted_default_ctor_all_const)
9321         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9322     return true;
9323   }
9324   return false;
9325 }
9326 
9327 /// Determine whether a defaulted special member function should be defined as
9328 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9329 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9330 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9331                                      InheritedConstructorInfo *ICI,
9332                                      bool Diagnose) {
9333   if (MD->isInvalidDecl())
9334     return false;
9335   CXXRecordDecl *RD = MD->getParent();
9336   assert(!RD->isDependentType() && "do deletion after instantiation");
9337   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9338     return false;
9339 
9340   // C++11 [expr.lambda.prim]p19:
9341   //   The closure type associated with a lambda-expression has a
9342   //   deleted (8.4.3) default constructor and a deleted copy
9343   //   assignment operator.
9344   // C++2a adds back these operators if the lambda has no lambda-capture.
9345   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9346       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9347     if (Diagnose)
9348       Diag(RD->getLocation(), diag::note_lambda_decl);
9349     return true;
9350   }
9351 
9352   // For an anonymous struct or union, the copy and assignment special members
9353   // will never be used, so skip the check. For an anonymous union declared at
9354   // namespace scope, the constructor and destructor are used.
9355   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9356       RD->isAnonymousStructOrUnion())
9357     return false;
9358 
9359   // C++11 [class.copy]p7, p18:
9360   //   If the class definition declares a move constructor or move assignment
9361   //   operator, an implicitly declared copy constructor or copy assignment
9362   //   operator is defined as deleted.
9363   if (MD->isImplicit() &&
9364       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9365     CXXMethodDecl *UserDeclaredMove = nullptr;
9366 
9367     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9368     // deletion of the corresponding copy operation, not both copy operations.
9369     // MSVC 2015 has adopted the standards conforming behavior.
9370     bool DeletesOnlyMatchingCopy =
9371         getLangOpts().MSVCCompat &&
9372         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9373 
9374     if (RD->hasUserDeclaredMoveConstructor() &&
9375         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9376       if (!Diagnose) return true;
9377 
9378       // Find any user-declared move constructor.
9379       for (auto *I : RD->ctors()) {
9380         if (I->isMoveConstructor()) {
9381           UserDeclaredMove = I;
9382           break;
9383         }
9384       }
9385       assert(UserDeclaredMove);
9386     } else if (RD->hasUserDeclaredMoveAssignment() &&
9387                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9388       if (!Diagnose) return true;
9389 
9390       // Find any user-declared move assignment operator.
9391       for (auto *I : RD->methods()) {
9392         if (I->isMoveAssignmentOperator()) {
9393           UserDeclaredMove = I;
9394           break;
9395         }
9396       }
9397       assert(UserDeclaredMove);
9398     }
9399 
9400     if (UserDeclaredMove) {
9401       Diag(UserDeclaredMove->getLocation(),
9402            diag::note_deleted_copy_user_declared_move)
9403         << (CSM == CXXCopyAssignment) << RD
9404         << UserDeclaredMove->isMoveAssignmentOperator();
9405       return true;
9406     }
9407   }
9408 
9409   // Do access control from the special member function
9410   ContextRAII MethodContext(*this, MD);
9411 
9412   // C++11 [class.dtor]p5:
9413   // -- for a virtual destructor, lookup of the non-array deallocation function
9414   //    results in an ambiguity or in a function that is deleted or inaccessible
9415   if (CSM == CXXDestructor && MD->isVirtual()) {
9416     FunctionDecl *OperatorDelete = nullptr;
9417     DeclarationName Name =
9418       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9419     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9420                                  OperatorDelete, /*Diagnose*/false)) {
9421       if (Diagnose)
9422         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9423       return true;
9424     }
9425   }
9426 
9427   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9428 
9429   // Per DR1611, do not consider virtual bases of constructors of abstract
9430   // classes, since we are not going to construct them.
9431   // Per DR1658, do not consider virtual bases of destructors of abstract
9432   // classes either.
9433   // Per DR2180, for assignment operators we only assign (and thus only
9434   // consider) direct bases.
9435   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9436                                  : SMI.VisitPotentiallyConstructedBases))
9437     return true;
9438 
9439   if (SMI.shouldDeleteForAllConstMembers())
9440     return true;
9441 
9442   if (getLangOpts().CUDA) {
9443     // We should delete the special member in CUDA mode if target inference
9444     // failed.
9445     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9446     // is treated as certain special member, which may not reflect what special
9447     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9448     // expects CSM to match MD, therefore recalculate CSM.
9449     assert(ICI || CSM == getSpecialMember(MD));
9450     auto RealCSM = CSM;
9451     if (ICI)
9452       RealCSM = getSpecialMember(MD);
9453 
9454     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9455                                                    SMI.ConstArg, Diagnose);
9456   }
9457 
9458   return false;
9459 }
9460 
9461 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9462   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9463   assert(DFK && "not a defaultable function");
9464   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9465 
9466   if (DFK.isSpecialMember()) {
9467     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9468                               nullptr, /*Diagnose=*/true);
9469   } else {
9470     DefaultedComparisonAnalyzer(
9471         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9472         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9473         .visit();
9474   }
9475 }
9476 
9477 /// Perform lookup for a special member of the specified kind, and determine
9478 /// whether it is trivial. If the triviality can be determined without the
9479 /// lookup, skip it. This is intended for use when determining whether a
9480 /// special member of a containing object is trivial, and thus does not ever
9481 /// perform overload resolution for default constructors.
9482 ///
9483 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9484 /// member that was most likely to be intended to be trivial, if any.
9485 ///
9486 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9487 /// determine whether the special member is trivial.
9488 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9489                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9490                                      bool ConstRHS,
9491                                      Sema::TrivialABIHandling TAH,
9492                                      CXXMethodDecl **Selected) {
9493   if (Selected)
9494     *Selected = nullptr;
9495 
9496   switch (CSM) {
9497   case Sema::CXXInvalid:
9498     llvm_unreachable("not a special member");
9499 
9500   case Sema::CXXDefaultConstructor:
9501     // C++11 [class.ctor]p5:
9502     //   A default constructor is trivial if:
9503     //    - all the [direct subobjects] have trivial default constructors
9504     //
9505     // Note, no overload resolution is performed in this case.
9506     if (RD->hasTrivialDefaultConstructor())
9507       return true;
9508 
9509     if (Selected) {
9510       // If there's a default constructor which could have been trivial, dig it
9511       // out. Otherwise, if there's any user-provided default constructor, point
9512       // to that as an example of why there's not a trivial one.
9513       CXXConstructorDecl *DefCtor = nullptr;
9514       if (RD->needsImplicitDefaultConstructor())
9515         S.DeclareImplicitDefaultConstructor(RD);
9516       for (auto *CI : RD->ctors()) {
9517         if (!CI->isDefaultConstructor())
9518           continue;
9519         DefCtor = CI;
9520         if (!DefCtor->isUserProvided())
9521           break;
9522       }
9523 
9524       *Selected = DefCtor;
9525     }
9526 
9527     return false;
9528 
9529   case Sema::CXXDestructor:
9530     // C++11 [class.dtor]p5:
9531     //   A destructor is trivial if:
9532     //    - all the direct [subobjects] have trivial destructors
9533     if (RD->hasTrivialDestructor() ||
9534         (TAH == Sema::TAH_ConsiderTrivialABI &&
9535          RD->hasTrivialDestructorForCall()))
9536       return true;
9537 
9538     if (Selected) {
9539       if (RD->needsImplicitDestructor())
9540         S.DeclareImplicitDestructor(RD);
9541       *Selected = RD->getDestructor();
9542     }
9543 
9544     return false;
9545 
9546   case Sema::CXXCopyConstructor:
9547     // C++11 [class.copy]p12:
9548     //   A copy constructor is trivial if:
9549     //    - the constructor selected to copy each direct [subobject] is trivial
9550     if (RD->hasTrivialCopyConstructor() ||
9551         (TAH == Sema::TAH_ConsiderTrivialABI &&
9552          RD->hasTrivialCopyConstructorForCall())) {
9553       if (Quals == Qualifiers::Const)
9554         // We must either select the trivial copy constructor or reach an
9555         // ambiguity; no need to actually perform overload resolution.
9556         return true;
9557     } else if (!Selected) {
9558       return false;
9559     }
9560     // In C++98, we are not supposed to perform overload resolution here, but we
9561     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9562     // cases like B as having a non-trivial copy constructor:
9563     //   struct A { template<typename T> A(T&); };
9564     //   struct B { mutable A a; };
9565     goto NeedOverloadResolution;
9566 
9567   case Sema::CXXCopyAssignment:
9568     // C++11 [class.copy]p25:
9569     //   A copy assignment operator is trivial if:
9570     //    - the assignment operator selected to copy each direct [subobject] is
9571     //      trivial
9572     if (RD->hasTrivialCopyAssignment()) {
9573       if (Quals == Qualifiers::Const)
9574         return true;
9575     } else if (!Selected) {
9576       return false;
9577     }
9578     // In C++98, we are not supposed to perform overload resolution here, but we
9579     // treat that as a language defect.
9580     goto NeedOverloadResolution;
9581 
9582   case Sema::CXXMoveConstructor:
9583   case Sema::CXXMoveAssignment:
9584   NeedOverloadResolution:
9585     Sema::SpecialMemberOverloadResult SMOR =
9586         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9587 
9588     // The standard doesn't describe how to behave if the lookup is ambiguous.
9589     // We treat it as not making the member non-trivial, just like the standard
9590     // mandates for the default constructor. This should rarely matter, because
9591     // the member will also be deleted.
9592     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9593       return true;
9594 
9595     if (!SMOR.getMethod()) {
9596       assert(SMOR.getKind() ==
9597              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9598       return false;
9599     }
9600 
9601     // We deliberately don't check if we found a deleted special member. We're
9602     // not supposed to!
9603     if (Selected)
9604       *Selected = SMOR.getMethod();
9605 
9606     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9607         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9608       return SMOR.getMethod()->isTrivialForCall();
9609     return SMOR.getMethod()->isTrivial();
9610   }
9611 
9612   llvm_unreachable("unknown special method kind");
9613 }
9614 
9615 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9616   for (auto *CI : RD->ctors())
9617     if (!CI->isImplicit())
9618       return CI;
9619 
9620   // Look for constructor templates.
9621   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9622   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9623     if (CXXConstructorDecl *CD =
9624           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9625       return CD;
9626   }
9627 
9628   return nullptr;
9629 }
9630 
9631 /// The kind of subobject we are checking for triviality. The values of this
9632 /// enumeration are used in diagnostics.
9633 enum TrivialSubobjectKind {
9634   /// The subobject is a base class.
9635   TSK_BaseClass,
9636   /// The subobject is a non-static data member.
9637   TSK_Field,
9638   /// The object is actually the complete object.
9639   TSK_CompleteObject
9640 };
9641 
9642 /// Check whether the special member selected for a given type would be trivial.
9643 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9644                                       QualType SubType, bool ConstRHS,
9645                                       Sema::CXXSpecialMember CSM,
9646                                       TrivialSubobjectKind Kind,
9647                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9648   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9649   if (!SubRD)
9650     return true;
9651 
9652   CXXMethodDecl *Selected;
9653   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9654                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9655     return true;
9656 
9657   if (Diagnose) {
9658     if (ConstRHS)
9659       SubType.addConst();
9660 
9661     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9662       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9663         << Kind << SubType.getUnqualifiedType();
9664       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9665         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9666     } else if (!Selected)
9667       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9668         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9669     else if (Selected->isUserProvided()) {
9670       if (Kind == TSK_CompleteObject)
9671         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9672           << Kind << SubType.getUnqualifiedType() << CSM;
9673       else {
9674         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9675           << Kind << SubType.getUnqualifiedType() << CSM;
9676         S.Diag(Selected->getLocation(), diag::note_declared_at);
9677       }
9678     } else {
9679       if (Kind != TSK_CompleteObject)
9680         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9681           << Kind << SubType.getUnqualifiedType() << CSM;
9682 
9683       // Explain why the defaulted or deleted special member isn't trivial.
9684       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9685                                Diagnose);
9686     }
9687   }
9688 
9689   return false;
9690 }
9691 
9692 /// Check whether the members of a class type allow a special member to be
9693 /// trivial.
9694 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9695                                      Sema::CXXSpecialMember CSM,
9696                                      bool ConstArg,
9697                                      Sema::TrivialABIHandling TAH,
9698                                      bool Diagnose) {
9699   for (const auto *FI : RD->fields()) {
9700     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9701       continue;
9702 
9703     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9704 
9705     // Pretend anonymous struct or union members are members of this class.
9706     if (FI->isAnonymousStructOrUnion()) {
9707       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9708                                     CSM, ConstArg, TAH, Diagnose))
9709         return false;
9710       continue;
9711     }
9712 
9713     // C++11 [class.ctor]p5:
9714     //   A default constructor is trivial if [...]
9715     //    -- no non-static data member of its class has a
9716     //       brace-or-equal-initializer
9717     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9718       if (Diagnose)
9719         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9720             << FI;
9721       return false;
9722     }
9723 
9724     // Objective C ARC 4.3.5:
9725     //   [...] nontrivally ownership-qualified types are [...] not trivially
9726     //   default constructible, copy constructible, move constructible, copy
9727     //   assignable, move assignable, or destructible [...]
9728     if (FieldType.hasNonTrivialObjCLifetime()) {
9729       if (Diagnose)
9730         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9731           << RD << FieldType.getObjCLifetime();
9732       return false;
9733     }
9734 
9735     bool ConstRHS = ConstArg && !FI->isMutable();
9736     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9737                                    CSM, TSK_Field, TAH, Diagnose))
9738       return false;
9739   }
9740 
9741   return true;
9742 }
9743 
9744 /// Diagnose why the specified class does not have a trivial special member of
9745 /// the given kind.
9746 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9747   QualType Ty = Context.getRecordType(RD);
9748 
9749   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9750   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9751                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9752                             /*Diagnose*/true);
9753 }
9754 
9755 /// Determine whether a defaulted or deleted special member function is trivial,
9756 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9757 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9758 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9759                                   TrivialABIHandling TAH, bool Diagnose) {
9760   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9761 
9762   CXXRecordDecl *RD = MD->getParent();
9763 
9764   bool ConstArg = false;
9765 
9766   // C++11 [class.copy]p12, p25: [DR1593]
9767   //   A [special member] is trivial if [...] its parameter-type-list is
9768   //   equivalent to the parameter-type-list of an implicit declaration [...]
9769   switch (CSM) {
9770   case CXXDefaultConstructor:
9771   case CXXDestructor:
9772     // Trivial default constructors and destructors cannot have parameters.
9773     break;
9774 
9775   case CXXCopyConstructor:
9776   case CXXCopyAssignment: {
9777     // Trivial copy operations always have const, non-volatile parameter types.
9778     ConstArg = true;
9779     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9780     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9781     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9782       if (Diagnose)
9783         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9784           << Param0->getSourceRange() << Param0->getType()
9785           << Context.getLValueReferenceType(
9786                Context.getRecordType(RD).withConst());
9787       return false;
9788     }
9789     break;
9790   }
9791 
9792   case CXXMoveConstructor:
9793   case CXXMoveAssignment: {
9794     // Trivial move operations always have non-cv-qualified parameters.
9795     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9796     const RValueReferenceType *RT =
9797       Param0->getType()->getAs<RValueReferenceType>();
9798     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9799       if (Diagnose)
9800         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9801           << Param0->getSourceRange() << Param0->getType()
9802           << Context.getRValueReferenceType(Context.getRecordType(RD));
9803       return false;
9804     }
9805     break;
9806   }
9807 
9808   case CXXInvalid:
9809     llvm_unreachable("not a special member");
9810   }
9811 
9812   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9813     if (Diagnose)
9814       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9815            diag::note_nontrivial_default_arg)
9816         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9817     return false;
9818   }
9819   if (MD->isVariadic()) {
9820     if (Diagnose)
9821       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9822     return false;
9823   }
9824 
9825   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9826   //   A copy/move [constructor or assignment operator] is trivial if
9827   //    -- the [member] selected to copy/move each direct base class subobject
9828   //       is trivial
9829   //
9830   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9831   //   A [default constructor or destructor] is trivial if
9832   //    -- all the direct base classes have trivial [default constructors or
9833   //       destructors]
9834   for (const auto &BI : RD->bases())
9835     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9836                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9837       return false;
9838 
9839   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9840   //   A copy/move [constructor or assignment operator] for a class X is
9841   //   trivial if
9842   //    -- for each non-static data member of X that is of class type (or array
9843   //       thereof), the constructor selected to copy/move that member is
9844   //       trivial
9845   //
9846   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9847   //   A [default constructor or destructor] is trivial if
9848   //    -- for all of the non-static data members of its class that are of class
9849   //       type (or array thereof), each such class has a trivial [default
9850   //       constructor or destructor]
9851   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9852     return false;
9853 
9854   // C++11 [class.dtor]p5:
9855   //   A destructor is trivial if [...]
9856   //    -- the destructor is not virtual
9857   if (CSM == CXXDestructor && MD->isVirtual()) {
9858     if (Diagnose)
9859       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9860     return false;
9861   }
9862 
9863   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9864   //   A [special member] for class X is trivial if [...]
9865   //    -- class X has no virtual functions and no virtual base classes
9866   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9867     if (!Diagnose)
9868       return false;
9869 
9870     if (RD->getNumVBases()) {
9871       // Check for virtual bases. We already know that the corresponding
9872       // member in all bases is trivial, so vbases must all be direct.
9873       CXXBaseSpecifier &BS = *RD->vbases_begin();
9874       assert(BS.isVirtual());
9875       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9876       return false;
9877     }
9878 
9879     // Must have a virtual method.
9880     for (const auto *MI : RD->methods()) {
9881       if (MI->isVirtual()) {
9882         SourceLocation MLoc = MI->getBeginLoc();
9883         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9884         return false;
9885       }
9886     }
9887 
9888     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9889   }
9890 
9891   // Looks like it's trivial!
9892   return true;
9893 }
9894 
9895 namespace {
9896 struct FindHiddenVirtualMethod {
9897   Sema *S;
9898   CXXMethodDecl *Method;
9899   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9900   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9901 
9902 private:
9903   /// Check whether any most overridden method from MD in Methods
9904   static bool CheckMostOverridenMethods(
9905       const CXXMethodDecl *MD,
9906       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9907     if (MD->size_overridden_methods() == 0)
9908       return Methods.count(MD->getCanonicalDecl());
9909     for (const CXXMethodDecl *O : MD->overridden_methods())
9910       if (CheckMostOverridenMethods(O, Methods))
9911         return true;
9912     return false;
9913   }
9914 
9915 public:
9916   /// Member lookup function that determines whether a given C++
9917   /// method overloads virtual methods in a base class without overriding any,
9918   /// to be used with CXXRecordDecl::lookupInBases().
9919   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9920     RecordDecl *BaseRecord =
9921         Specifier->getType()->castAs<RecordType>()->getDecl();
9922 
9923     DeclarationName Name = Method->getDeclName();
9924     assert(Name.getNameKind() == DeclarationName::Identifier);
9925 
9926     bool foundSameNameMethod = false;
9927     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9928     for (Path.Decls = BaseRecord->lookup(Name).begin();
9929          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9930       NamedDecl *D = *Path.Decls;
9931       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9932         MD = MD->getCanonicalDecl();
9933         foundSameNameMethod = true;
9934         // Interested only in hidden virtual methods.
9935         if (!MD->isVirtual())
9936           continue;
9937         // If the method we are checking overrides a method from its base
9938         // don't warn about the other overloaded methods. Clang deviates from
9939         // GCC by only diagnosing overloads of inherited virtual functions that
9940         // do not override any other virtual functions in the base. GCC's
9941         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9942         // function from a base class. These cases may be better served by a
9943         // warning (not specific to virtual functions) on call sites when the
9944         // call would select a different function from the base class, were it
9945         // visible.
9946         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9947         if (!S->IsOverload(Method, MD, false))
9948           return true;
9949         // Collect the overload only if its hidden.
9950         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9951           overloadedMethods.push_back(MD);
9952       }
9953     }
9954 
9955     if (foundSameNameMethod)
9956       OverloadedMethods.append(overloadedMethods.begin(),
9957                                overloadedMethods.end());
9958     return foundSameNameMethod;
9959   }
9960 };
9961 } // end anonymous namespace
9962 
9963 /// Add the most overridden methods from MD to Methods
9964 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9965                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9966   if (MD->size_overridden_methods() == 0)
9967     Methods.insert(MD->getCanonicalDecl());
9968   else
9969     for (const CXXMethodDecl *O : MD->overridden_methods())
9970       AddMostOverridenMethods(O, Methods);
9971 }
9972 
9973 /// Check if a method overloads virtual methods in a base class without
9974 /// overriding any.
9975 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9976                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9977   if (!MD->getDeclName().isIdentifier())
9978     return;
9979 
9980   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9981                      /*bool RecordPaths=*/false,
9982                      /*bool DetectVirtual=*/false);
9983   FindHiddenVirtualMethod FHVM;
9984   FHVM.Method = MD;
9985   FHVM.S = this;
9986 
9987   // Keep the base methods that were overridden or introduced in the subclass
9988   // by 'using' in a set. A base method not in this set is hidden.
9989   CXXRecordDecl *DC = MD->getParent();
9990   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9991   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9992     NamedDecl *ND = *I;
9993     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9994       ND = shad->getTargetDecl();
9995     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9996       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9997   }
9998 
9999   if (DC->lookupInBases(FHVM, Paths))
10000     OverloadedMethods = FHVM.OverloadedMethods;
10001 }
10002 
10003 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10004                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10005   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10006     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10007     PartialDiagnostic PD = PDiag(
10008          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10009     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10010     Diag(overloadedMD->getLocation(), PD);
10011   }
10012 }
10013 
10014 /// Diagnose methods which overload virtual methods in a base class
10015 /// without overriding any.
10016 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10017   if (MD->isInvalidDecl())
10018     return;
10019 
10020   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10021     return;
10022 
10023   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10024   FindHiddenVirtualMethods(MD, OverloadedMethods);
10025   if (!OverloadedMethods.empty()) {
10026     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10027       << MD << (OverloadedMethods.size() > 1);
10028 
10029     NoteHiddenVirtualMethods(MD, OverloadedMethods);
10030   }
10031 }
10032 
10033 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10034   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10035     // No diagnostics if this is a template instantiation.
10036     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10037       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10038            diag::ext_cannot_use_trivial_abi) << &RD;
10039       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10040            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10041     }
10042     RD.dropAttr<TrivialABIAttr>();
10043   };
10044 
10045   // Ill-formed if the copy and move constructors are deleted.
10046   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10047     // If the type is dependent, then assume it might have
10048     // implicit copy or move ctor because we won't know yet at this point.
10049     if (RD.isDependentType())
10050       return true;
10051     if (RD.needsImplicitCopyConstructor() &&
10052         !RD.defaultedCopyConstructorIsDeleted())
10053       return true;
10054     if (RD.needsImplicitMoveConstructor() &&
10055         !RD.defaultedMoveConstructorIsDeleted())
10056       return true;
10057     for (const CXXConstructorDecl *CD : RD.ctors())
10058       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10059         return true;
10060     return false;
10061   };
10062 
10063   if (!HasNonDeletedCopyOrMoveConstructor()) {
10064     PrintDiagAndRemoveAttr(0);
10065     return;
10066   }
10067 
10068   // Ill-formed if the struct has virtual functions.
10069   if (RD.isPolymorphic()) {
10070     PrintDiagAndRemoveAttr(1);
10071     return;
10072   }
10073 
10074   for (const auto &B : RD.bases()) {
10075     // Ill-formed if the base class is non-trivial for the purpose of calls or a
10076     // virtual base.
10077     if (!B.getType()->isDependentType() &&
10078         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10079       PrintDiagAndRemoveAttr(2);
10080       return;
10081     }
10082 
10083     if (B.isVirtual()) {
10084       PrintDiagAndRemoveAttr(3);
10085       return;
10086     }
10087   }
10088 
10089   for (const auto *FD : RD.fields()) {
10090     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10091     // non-trivial for the purpose of calls.
10092     QualType FT = FD->getType();
10093     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10094       PrintDiagAndRemoveAttr(4);
10095       return;
10096     }
10097 
10098     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10099       if (!RT->isDependentType() &&
10100           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10101         PrintDiagAndRemoveAttr(5);
10102         return;
10103       }
10104   }
10105 }
10106 
10107 void Sema::ActOnFinishCXXMemberSpecification(
10108     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10109     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10110   if (!TagDecl)
10111     return;
10112 
10113   AdjustDeclIfTemplate(TagDecl);
10114 
10115   for (const ParsedAttr &AL : AttrList) {
10116     if (AL.getKind() != ParsedAttr::AT_Visibility)
10117       continue;
10118     AL.setInvalid();
10119     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10120   }
10121 
10122   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
10123               // strict aliasing violation!
10124               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
10125               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
10126 
10127   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10128 }
10129 
10130 /// Find the equality comparison functions that should be implicitly declared
10131 /// in a given class definition, per C++2a [class.compare.default]p3.
10132 static void findImplicitlyDeclaredEqualityComparisons(
10133     ASTContext &Ctx, CXXRecordDecl *RD,
10134     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10135   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10136   if (!RD->lookup(EqEq).empty())
10137     // Member operator== explicitly declared: no implicit operator==s.
10138     return;
10139 
10140   // Traverse friends looking for an '==' or a '<=>'.
10141   for (FriendDecl *Friend : RD->friends()) {
10142     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10143     if (!FD) continue;
10144 
10145     if (FD->getOverloadedOperator() == OO_EqualEqual) {
10146       // Friend operator== explicitly declared: no implicit operator==s.
10147       Spaceships.clear();
10148       return;
10149     }
10150 
10151     if (FD->getOverloadedOperator() == OO_Spaceship &&
10152         FD->isExplicitlyDefaulted())
10153       Spaceships.push_back(FD);
10154   }
10155 
10156   // Look for members named 'operator<=>'.
10157   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10158   for (NamedDecl *ND : RD->lookup(Cmp)) {
10159     // Note that we could find a non-function here (either a function template
10160     // or a using-declaration). Neither case results in an implicit
10161     // 'operator=='.
10162     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10163       if (FD->isExplicitlyDefaulted())
10164         Spaceships.push_back(FD);
10165   }
10166 }
10167 
10168 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10169 /// special functions, such as the default constructor, copy
10170 /// constructor, or destructor, to the given C++ class (C++
10171 /// [special]p1).  This routine can only be executed just before the
10172 /// definition of the class is complete.
10173 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10174   // Don't add implicit special members to templated classes.
10175   // FIXME: This means unqualified lookups for 'operator=' within a class
10176   // template don't work properly.
10177   if (!ClassDecl->isDependentType()) {
10178     if (ClassDecl->needsImplicitDefaultConstructor()) {
10179       ++getASTContext().NumImplicitDefaultConstructors;
10180 
10181       if (ClassDecl->hasInheritedConstructor())
10182         DeclareImplicitDefaultConstructor(ClassDecl);
10183     }
10184 
10185     if (ClassDecl->needsImplicitCopyConstructor()) {
10186       ++getASTContext().NumImplicitCopyConstructors;
10187 
10188       // If the properties or semantics of the copy constructor couldn't be
10189       // determined while the class was being declared, force a declaration
10190       // of it now.
10191       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10192           ClassDecl->hasInheritedConstructor())
10193         DeclareImplicitCopyConstructor(ClassDecl);
10194       // For the MS ABI we need to know whether the copy ctor is deleted. A
10195       // prerequisite for deleting the implicit copy ctor is that the class has
10196       // a move ctor or move assignment that is either user-declared or whose
10197       // semantics are inherited from a subobject. FIXME: We should provide a
10198       // more direct way for CodeGen to ask whether the constructor was deleted.
10199       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10200                (ClassDecl->hasUserDeclaredMoveConstructor() ||
10201                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10202                 ClassDecl->hasUserDeclaredMoveAssignment() ||
10203                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10204         DeclareImplicitCopyConstructor(ClassDecl);
10205     }
10206 
10207     if (getLangOpts().CPlusPlus11 &&
10208         ClassDecl->needsImplicitMoveConstructor()) {
10209       ++getASTContext().NumImplicitMoveConstructors;
10210 
10211       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10212           ClassDecl->hasInheritedConstructor())
10213         DeclareImplicitMoveConstructor(ClassDecl);
10214     }
10215 
10216     if (ClassDecl->needsImplicitCopyAssignment()) {
10217       ++getASTContext().NumImplicitCopyAssignmentOperators;
10218 
10219       // If we have a dynamic class, then the copy assignment operator may be
10220       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10221       // it shows up in the right place in the vtable and that we diagnose
10222       // problems with the implicit exception specification.
10223       if (ClassDecl->isDynamicClass() ||
10224           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10225           ClassDecl->hasInheritedAssignment())
10226         DeclareImplicitCopyAssignment(ClassDecl);
10227     }
10228 
10229     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10230       ++getASTContext().NumImplicitMoveAssignmentOperators;
10231 
10232       // Likewise for the move assignment operator.
10233       if (ClassDecl->isDynamicClass() ||
10234           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10235           ClassDecl->hasInheritedAssignment())
10236         DeclareImplicitMoveAssignment(ClassDecl);
10237     }
10238 
10239     if (ClassDecl->needsImplicitDestructor()) {
10240       ++getASTContext().NumImplicitDestructors;
10241 
10242       // If we have a dynamic class, then the destructor may be virtual, so we
10243       // have to declare the destructor immediately. This ensures that, e.g., it
10244       // shows up in the right place in the vtable and that we diagnose problems
10245       // with the implicit exception specification.
10246       if (ClassDecl->isDynamicClass() ||
10247           ClassDecl->needsOverloadResolutionForDestructor())
10248         DeclareImplicitDestructor(ClassDecl);
10249     }
10250   }
10251 
10252   // C++2a [class.compare.default]p3:
10253   //   If the member-specification does not explicitly declare any member or
10254   //   friend named operator==, an == operator function is declared implicitly
10255   //   for each defaulted three-way comparison operator function defined in
10256   //   the member-specification
10257   // FIXME: Consider doing this lazily.
10258   // We do this during the initial parse for a class template, not during
10259   // instantiation, so that we can handle unqualified lookups for 'operator=='
10260   // when parsing the template.
10261   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10262     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10263     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10264                                               DefaultedSpaceships);
10265     for (auto *FD : DefaultedSpaceships)
10266       DeclareImplicitEqualityComparison(ClassDecl, FD);
10267   }
10268 }
10269 
10270 unsigned
10271 Sema::ActOnReenterTemplateScope(Decl *D,
10272                                 llvm::function_ref<Scope *()> EnterScope) {
10273   if (!D)
10274     return 0;
10275   AdjustDeclIfTemplate(D);
10276 
10277   // In order to get name lookup right, reenter template scopes in order from
10278   // outermost to innermost.
10279   SmallVector<TemplateParameterList *, 4> ParameterLists;
10280   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10281 
10282   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10283     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10284       ParameterLists.push_back(DD->getTemplateParameterList(i));
10285 
10286     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10287       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10288         ParameterLists.push_back(FTD->getTemplateParameters());
10289     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10290       LookupDC = VD->getDeclContext();
10291 
10292       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10293         ParameterLists.push_back(VTD->getTemplateParameters());
10294       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10295         ParameterLists.push_back(PSD->getTemplateParameters());
10296     }
10297   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10298     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10299       ParameterLists.push_back(TD->getTemplateParameterList(i));
10300 
10301     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10302       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10303         ParameterLists.push_back(CTD->getTemplateParameters());
10304       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10305         ParameterLists.push_back(PSD->getTemplateParameters());
10306     }
10307   }
10308   // FIXME: Alias declarations and concepts.
10309 
10310   unsigned Count = 0;
10311   Scope *InnermostTemplateScope = nullptr;
10312   for (TemplateParameterList *Params : ParameterLists) {
10313     // Ignore explicit specializations; they don't contribute to the template
10314     // depth.
10315     if (Params->size() == 0)
10316       continue;
10317 
10318     InnermostTemplateScope = EnterScope();
10319     for (NamedDecl *Param : *Params) {
10320       if (Param->getDeclName()) {
10321         InnermostTemplateScope->AddDecl(Param);
10322         IdResolver.AddDecl(Param);
10323       }
10324     }
10325     ++Count;
10326   }
10327 
10328   // Associate the new template scopes with the corresponding entities.
10329   if (InnermostTemplateScope) {
10330     assert(LookupDC && "no enclosing DeclContext for template lookup");
10331     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10332   }
10333 
10334   return Count;
10335 }
10336 
10337 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10338   if (!RecordD) return;
10339   AdjustDeclIfTemplate(RecordD);
10340   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10341   PushDeclContext(S, Record);
10342 }
10343 
10344 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10345   if (!RecordD) return;
10346   PopDeclContext();
10347 }
10348 
10349 /// This is used to implement the constant expression evaluation part of the
10350 /// attribute enable_if extension. There is nothing in standard C++ which would
10351 /// require reentering parameters.
10352 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10353   if (!Param)
10354     return;
10355 
10356   S->AddDecl(Param);
10357   if (Param->getDeclName())
10358     IdResolver.AddDecl(Param);
10359 }
10360 
10361 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10362 /// parsing a top-level (non-nested) C++ class, and we are now
10363 /// parsing those parts of the given Method declaration that could
10364 /// not be parsed earlier (C++ [class.mem]p2), such as default
10365 /// arguments. This action should enter the scope of the given
10366 /// Method declaration as if we had just parsed the qualified method
10367 /// name. However, it should not bring the parameters into scope;
10368 /// that will be performed by ActOnDelayedCXXMethodParameter.
10369 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10370 }
10371 
10372 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10373 /// C++ method declaration. We're (re-)introducing the given
10374 /// function parameter into scope for use in parsing later parts of
10375 /// the method declaration. For example, we could see an
10376 /// ActOnParamDefaultArgument event for this parameter.
10377 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10378   if (!ParamD)
10379     return;
10380 
10381   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10382 
10383   S->AddDecl(Param);
10384   if (Param->getDeclName())
10385     IdResolver.AddDecl(Param);
10386 }
10387 
10388 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10389 /// processing the delayed method declaration for Method. The method
10390 /// declaration is now considered finished. There may be a separate
10391 /// ActOnStartOfFunctionDef action later (not necessarily
10392 /// immediately!) for this method, if it was also defined inside the
10393 /// class body.
10394 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10395   if (!MethodD)
10396     return;
10397 
10398   AdjustDeclIfTemplate(MethodD);
10399 
10400   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10401 
10402   // Now that we have our default arguments, check the constructor
10403   // again. It could produce additional diagnostics or affect whether
10404   // the class has implicitly-declared destructors, among other
10405   // things.
10406   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10407     CheckConstructor(Constructor);
10408 
10409   // Check the default arguments, which we may have added.
10410   if (!Method->isInvalidDecl())
10411     CheckCXXDefaultArguments(Method);
10412 }
10413 
10414 // Emit the given diagnostic for each non-address-space qualifier.
10415 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10416 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10417   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10418   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10419     bool DiagOccured = false;
10420     FTI.MethodQualifiers->forEachQualifier(
10421         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10422                                    SourceLocation SL) {
10423           // This diagnostic should be emitted on any qualifier except an addr
10424           // space qualifier. However, forEachQualifier currently doesn't visit
10425           // addr space qualifiers, so there's no way to write this condition
10426           // right now; we just diagnose on everything.
10427           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10428           DiagOccured = true;
10429         });
10430     if (DiagOccured)
10431       D.setInvalidType();
10432   }
10433 }
10434 
10435 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10436 /// the well-formedness of the constructor declarator @p D with type @p
10437 /// R. If there are any errors in the declarator, this routine will
10438 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10439 /// will be updated to reflect a well-formed type for the constructor and
10440 /// returned.
10441 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10442                                           StorageClass &SC) {
10443   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10444 
10445   // C++ [class.ctor]p3:
10446   //   A constructor shall not be virtual (10.3) or static (9.4). A
10447   //   constructor can be invoked for a const, volatile or const
10448   //   volatile object. A constructor shall not be declared const,
10449   //   volatile, or const volatile (9.3.2).
10450   if (isVirtual) {
10451     if (!D.isInvalidType())
10452       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10453         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10454         << SourceRange(D.getIdentifierLoc());
10455     D.setInvalidType();
10456   }
10457   if (SC == SC_Static) {
10458     if (!D.isInvalidType())
10459       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10460         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10461         << SourceRange(D.getIdentifierLoc());
10462     D.setInvalidType();
10463     SC = SC_None;
10464   }
10465 
10466   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10467     diagnoseIgnoredQualifiers(
10468         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10469         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10470         D.getDeclSpec().getRestrictSpecLoc(),
10471         D.getDeclSpec().getAtomicSpecLoc());
10472     D.setInvalidType();
10473   }
10474 
10475   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10476 
10477   // C++0x [class.ctor]p4:
10478   //   A constructor shall not be declared with a ref-qualifier.
10479   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10480   if (FTI.hasRefQualifier()) {
10481     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10482       << FTI.RefQualifierIsLValueRef
10483       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10484     D.setInvalidType();
10485   }
10486 
10487   // Rebuild the function type "R" without any type qualifiers (in
10488   // case any of the errors above fired) and with "void" as the
10489   // return type, since constructors don't have return types.
10490   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10491   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10492     return R;
10493 
10494   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10495   EPI.TypeQuals = Qualifiers();
10496   EPI.RefQualifier = RQ_None;
10497 
10498   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10499 }
10500 
10501 /// CheckConstructor - Checks a fully-formed constructor for
10502 /// well-formedness, issuing any diagnostics required. Returns true if
10503 /// the constructor declarator is invalid.
10504 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10505   CXXRecordDecl *ClassDecl
10506     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10507   if (!ClassDecl)
10508     return Constructor->setInvalidDecl();
10509 
10510   // C++ [class.copy]p3:
10511   //   A declaration of a constructor for a class X is ill-formed if
10512   //   its first parameter is of type (optionally cv-qualified) X and
10513   //   either there are no other parameters or else all other
10514   //   parameters have default arguments.
10515   if (!Constructor->isInvalidDecl() &&
10516       Constructor->hasOneParamOrDefaultArgs() &&
10517       Constructor->getTemplateSpecializationKind() !=
10518           TSK_ImplicitInstantiation) {
10519     QualType ParamType = Constructor->getParamDecl(0)->getType();
10520     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10521     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10522       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10523       const char *ConstRef
10524         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10525                                                         : " const &";
10526       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10527         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10528 
10529       // FIXME: Rather that making the constructor invalid, we should endeavor
10530       // to fix the type.
10531       Constructor->setInvalidDecl();
10532     }
10533   }
10534 }
10535 
10536 /// CheckDestructor - Checks a fully-formed destructor definition for
10537 /// well-formedness, issuing any diagnostics required.  Returns true
10538 /// on error.
10539 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10540   CXXRecordDecl *RD = Destructor->getParent();
10541 
10542   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10543     SourceLocation Loc;
10544 
10545     if (!Destructor->isImplicit())
10546       Loc = Destructor->getLocation();
10547     else
10548       Loc = RD->getLocation();
10549 
10550     // If we have a virtual destructor, look up the deallocation function
10551     if (FunctionDecl *OperatorDelete =
10552             FindDeallocationFunctionForDestructor(Loc, RD)) {
10553       Expr *ThisArg = nullptr;
10554 
10555       // If the notional 'delete this' expression requires a non-trivial
10556       // conversion from 'this' to the type of a destroying operator delete's
10557       // first parameter, perform that conversion now.
10558       if (OperatorDelete->isDestroyingOperatorDelete()) {
10559         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10560         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10561           // C++ [class.dtor]p13:
10562           //   ... as if for the expression 'delete this' appearing in a
10563           //   non-virtual destructor of the destructor's class.
10564           ContextRAII SwitchContext(*this, Destructor);
10565           ExprResult This =
10566               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10567           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10568           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10569           if (This.isInvalid()) {
10570             // FIXME: Register this as a context note so that it comes out
10571             // in the right order.
10572             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10573             return true;
10574           }
10575           ThisArg = This.get();
10576         }
10577       }
10578 
10579       DiagnoseUseOfDecl(OperatorDelete, Loc);
10580       MarkFunctionReferenced(Loc, OperatorDelete);
10581       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10582     }
10583   }
10584 
10585   return false;
10586 }
10587 
10588 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10589 /// the well-formednes of the destructor declarator @p D with type @p
10590 /// R. If there are any errors in the declarator, this routine will
10591 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10592 /// will be updated to reflect a well-formed type for the destructor and
10593 /// returned.
10594 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10595                                          StorageClass& SC) {
10596   // C++ [class.dtor]p1:
10597   //   [...] A typedef-name that names a class is a class-name
10598   //   (7.1.3); however, a typedef-name that names a class shall not
10599   //   be used as the identifier in the declarator for a destructor
10600   //   declaration.
10601   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10602   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10603     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10604       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10605   else if (const TemplateSpecializationType *TST =
10606              DeclaratorType->getAs<TemplateSpecializationType>())
10607     if (TST->isTypeAlias())
10608       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10609         << DeclaratorType << 1;
10610 
10611   // C++ [class.dtor]p2:
10612   //   A destructor is used to destroy objects of its class type. A
10613   //   destructor takes no parameters, and no return type can be
10614   //   specified for it (not even void). The address of a destructor
10615   //   shall not be taken. A destructor shall not be static. A
10616   //   destructor can be invoked for a const, volatile or const
10617   //   volatile object. A destructor shall not be declared const,
10618   //   volatile or const volatile (9.3.2).
10619   if (SC == SC_Static) {
10620     if (!D.isInvalidType())
10621       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10622         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10623         << SourceRange(D.getIdentifierLoc())
10624         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10625 
10626     SC = SC_None;
10627   }
10628   if (!D.isInvalidType()) {
10629     // Destructors don't have return types, but the parser will
10630     // happily parse something like:
10631     //
10632     //   class X {
10633     //     float ~X();
10634     //   };
10635     //
10636     // The return type will be eliminated later.
10637     if (D.getDeclSpec().hasTypeSpecifier())
10638       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10639         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10640         << SourceRange(D.getIdentifierLoc());
10641     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10642       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10643                                 SourceLocation(),
10644                                 D.getDeclSpec().getConstSpecLoc(),
10645                                 D.getDeclSpec().getVolatileSpecLoc(),
10646                                 D.getDeclSpec().getRestrictSpecLoc(),
10647                                 D.getDeclSpec().getAtomicSpecLoc());
10648       D.setInvalidType();
10649     }
10650   }
10651 
10652   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10653 
10654   // C++0x [class.dtor]p2:
10655   //   A destructor shall not be declared with a ref-qualifier.
10656   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10657   if (FTI.hasRefQualifier()) {
10658     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10659       << FTI.RefQualifierIsLValueRef
10660       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10661     D.setInvalidType();
10662   }
10663 
10664   // Make sure we don't have any parameters.
10665   if (FTIHasNonVoidParameters(FTI)) {
10666     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10667 
10668     // Delete the parameters.
10669     FTI.freeParams();
10670     D.setInvalidType();
10671   }
10672 
10673   // Make sure the destructor isn't variadic.
10674   if (FTI.isVariadic) {
10675     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10676     D.setInvalidType();
10677   }
10678 
10679   // Rebuild the function type "R" without any type qualifiers or
10680   // parameters (in case any of the errors above fired) and with
10681   // "void" as the return type, since destructors don't have return
10682   // types.
10683   if (!D.isInvalidType())
10684     return R;
10685 
10686   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10687   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10688   EPI.Variadic = false;
10689   EPI.TypeQuals = Qualifiers();
10690   EPI.RefQualifier = RQ_None;
10691   return Context.getFunctionType(Context.VoidTy, None, EPI);
10692 }
10693 
10694 static void extendLeft(SourceRange &R, SourceRange Before) {
10695   if (Before.isInvalid())
10696     return;
10697   R.setBegin(Before.getBegin());
10698   if (R.getEnd().isInvalid())
10699     R.setEnd(Before.getEnd());
10700 }
10701 
10702 static void extendRight(SourceRange &R, SourceRange After) {
10703   if (After.isInvalid())
10704     return;
10705   if (R.getBegin().isInvalid())
10706     R.setBegin(After.getBegin());
10707   R.setEnd(After.getEnd());
10708 }
10709 
10710 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10711 /// well-formednes of the conversion function declarator @p D with
10712 /// type @p R. If there are any errors in the declarator, this routine
10713 /// will emit diagnostics and return true. Otherwise, it will return
10714 /// false. Either way, the type @p R will be updated to reflect a
10715 /// well-formed type for the conversion operator.
10716 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10717                                      StorageClass& SC) {
10718   // C++ [class.conv.fct]p1:
10719   //   Neither parameter types nor return type can be specified. The
10720   //   type of a conversion function (8.3.5) is "function taking no
10721   //   parameter returning conversion-type-id."
10722   if (SC == SC_Static) {
10723     if (!D.isInvalidType())
10724       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10725         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10726         << D.getName().getSourceRange();
10727     D.setInvalidType();
10728     SC = SC_None;
10729   }
10730 
10731   TypeSourceInfo *ConvTSI = nullptr;
10732   QualType ConvType =
10733       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10734 
10735   const DeclSpec &DS = D.getDeclSpec();
10736   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10737     // Conversion functions don't have return types, but the parser will
10738     // happily parse something like:
10739     //
10740     //   class X {
10741     //     float operator bool();
10742     //   };
10743     //
10744     // The return type will be changed later anyway.
10745     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10746       << SourceRange(DS.getTypeSpecTypeLoc())
10747       << SourceRange(D.getIdentifierLoc());
10748     D.setInvalidType();
10749   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10750     // It's also plausible that the user writes type qualifiers in the wrong
10751     // place, such as:
10752     //   struct S { const operator int(); };
10753     // FIXME: we could provide a fixit to move the qualifiers onto the
10754     // conversion type.
10755     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10756         << SourceRange(D.getIdentifierLoc()) << 0;
10757     D.setInvalidType();
10758   }
10759 
10760   const auto *Proto = R->castAs<FunctionProtoType>();
10761 
10762   // Make sure we don't have any parameters.
10763   if (Proto->getNumParams() > 0) {
10764     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10765 
10766     // Delete the parameters.
10767     D.getFunctionTypeInfo().freeParams();
10768     D.setInvalidType();
10769   } else if (Proto->isVariadic()) {
10770     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10771     D.setInvalidType();
10772   }
10773 
10774   // Diagnose "&operator bool()" and other such nonsense.  This
10775   // is actually a gcc extension which we don't support.
10776   if (Proto->getReturnType() != ConvType) {
10777     bool NeedsTypedef = false;
10778     SourceRange Before, After;
10779 
10780     // Walk the chunks and extract information on them for our diagnostic.
10781     bool PastFunctionChunk = false;
10782     for (auto &Chunk : D.type_objects()) {
10783       switch (Chunk.Kind) {
10784       case DeclaratorChunk::Function:
10785         if (!PastFunctionChunk) {
10786           if (Chunk.Fun.HasTrailingReturnType) {
10787             TypeSourceInfo *TRT = nullptr;
10788             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10789             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10790           }
10791           PastFunctionChunk = true;
10792           break;
10793         }
10794         LLVM_FALLTHROUGH;
10795       case DeclaratorChunk::Array:
10796         NeedsTypedef = true;
10797         extendRight(After, Chunk.getSourceRange());
10798         break;
10799 
10800       case DeclaratorChunk::Pointer:
10801       case DeclaratorChunk::BlockPointer:
10802       case DeclaratorChunk::Reference:
10803       case DeclaratorChunk::MemberPointer:
10804       case DeclaratorChunk::Pipe:
10805         extendLeft(Before, Chunk.getSourceRange());
10806         break;
10807 
10808       case DeclaratorChunk::Paren:
10809         extendLeft(Before, Chunk.Loc);
10810         extendRight(After, Chunk.EndLoc);
10811         break;
10812       }
10813     }
10814 
10815     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10816                          After.isValid()  ? After.getBegin() :
10817                                             D.getIdentifierLoc();
10818     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10819     DB << Before << After;
10820 
10821     if (!NeedsTypedef) {
10822       DB << /*don't need a typedef*/0;
10823 
10824       // If we can provide a correct fix-it hint, do so.
10825       if (After.isInvalid() && ConvTSI) {
10826         SourceLocation InsertLoc =
10827             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10828         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10829            << FixItHint::CreateInsertionFromRange(
10830                   InsertLoc, CharSourceRange::getTokenRange(Before))
10831            << FixItHint::CreateRemoval(Before);
10832       }
10833     } else if (!Proto->getReturnType()->isDependentType()) {
10834       DB << /*typedef*/1 << Proto->getReturnType();
10835     } else if (getLangOpts().CPlusPlus11) {
10836       DB << /*alias template*/2 << Proto->getReturnType();
10837     } else {
10838       DB << /*might not be fixable*/3;
10839     }
10840 
10841     // Recover by incorporating the other type chunks into the result type.
10842     // Note, this does *not* change the name of the function. This is compatible
10843     // with the GCC extension:
10844     //   struct S { &operator int(); } s;
10845     //   int &r = s.operator int(); // ok in GCC
10846     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10847     ConvType = Proto->getReturnType();
10848   }
10849 
10850   // C++ [class.conv.fct]p4:
10851   //   The conversion-type-id shall not represent a function type nor
10852   //   an array type.
10853   if (ConvType->isArrayType()) {
10854     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10855     ConvType = Context.getPointerType(ConvType);
10856     D.setInvalidType();
10857   } else if (ConvType->isFunctionType()) {
10858     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10859     ConvType = Context.getPointerType(ConvType);
10860     D.setInvalidType();
10861   }
10862 
10863   // Rebuild the function type "R" without any parameters (in case any
10864   // of the errors above fired) and with the conversion type as the
10865   // return type.
10866   if (D.isInvalidType())
10867     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10868 
10869   // C++0x explicit conversion operators.
10870   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10871     Diag(DS.getExplicitSpecLoc(),
10872          getLangOpts().CPlusPlus11
10873              ? diag::warn_cxx98_compat_explicit_conversion_functions
10874              : diag::ext_explicit_conversion_functions)
10875         << SourceRange(DS.getExplicitSpecRange());
10876 }
10877 
10878 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10879 /// the declaration of the given C++ conversion function. This routine
10880 /// is responsible for recording the conversion function in the C++
10881 /// class, if possible.
10882 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10883   assert(Conversion && "Expected to receive a conversion function declaration");
10884 
10885   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10886 
10887   // Make sure we aren't redeclaring the conversion function.
10888   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10889   // C++ [class.conv.fct]p1:
10890   //   [...] A conversion function is never used to convert a
10891   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10892   //   same object type (or a reference to it), to a (possibly
10893   //   cv-qualified) base class of that type (or a reference to it),
10894   //   or to (possibly cv-qualified) void.
10895   QualType ClassType
10896     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10897   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10898     ConvType = ConvTypeRef->getPointeeType();
10899   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10900       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10901     /* Suppress diagnostics for instantiations. */;
10902   else if (Conversion->size_overridden_methods() != 0)
10903     /* Suppress diagnostics for overriding virtual function in a base class. */;
10904   else if (ConvType->isRecordType()) {
10905     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10906     if (ConvType == ClassType)
10907       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10908         << ClassType;
10909     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10910       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10911         <<  ClassType << ConvType;
10912   } else if (ConvType->isVoidType()) {
10913     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10914       << ClassType << ConvType;
10915   }
10916 
10917   if (FunctionTemplateDecl *ConversionTemplate
10918                                 = Conversion->getDescribedFunctionTemplate())
10919     return ConversionTemplate;
10920 
10921   return Conversion;
10922 }
10923 
10924 namespace {
10925 /// Utility class to accumulate and print a diagnostic listing the invalid
10926 /// specifier(s) on a declaration.
10927 struct BadSpecifierDiagnoser {
10928   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10929       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10930   ~BadSpecifierDiagnoser() {
10931     Diagnostic << Specifiers;
10932   }
10933 
10934   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10935     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10936   }
10937   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10938     return check(SpecLoc,
10939                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10940   }
10941   void check(SourceLocation SpecLoc, const char *Spec) {
10942     if (SpecLoc.isInvalid()) return;
10943     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10944     if (!Specifiers.empty()) Specifiers += " ";
10945     Specifiers += Spec;
10946   }
10947 
10948   Sema &S;
10949   Sema::SemaDiagnosticBuilder Diagnostic;
10950   std::string Specifiers;
10951 };
10952 }
10953 
10954 /// Check the validity of a declarator that we parsed for a deduction-guide.
10955 /// These aren't actually declarators in the grammar, so we need to check that
10956 /// the user didn't specify any pieces that are not part of the deduction-guide
10957 /// grammar.
10958 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10959                                          StorageClass &SC) {
10960   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10961   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10962   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10963 
10964   // C++ [temp.deduct.guide]p3:
10965   //   A deduction-gide shall be declared in the same scope as the
10966   //   corresponding class template.
10967   if (!CurContext->getRedeclContext()->Equals(
10968           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10969     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10970       << GuidedTemplateDecl;
10971     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10972   }
10973 
10974   auto &DS = D.getMutableDeclSpec();
10975   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10976   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10977       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10978       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10979     BadSpecifierDiagnoser Diagnoser(
10980         *this, D.getIdentifierLoc(),
10981         diag::err_deduction_guide_invalid_specifier);
10982 
10983     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10984     DS.ClearStorageClassSpecs();
10985     SC = SC_None;
10986 
10987     // 'explicit' is permitted.
10988     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10989     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10990     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10991     DS.ClearConstexprSpec();
10992 
10993     Diagnoser.check(DS.getConstSpecLoc(), "const");
10994     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10995     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10996     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10997     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10998     DS.ClearTypeQualifiers();
10999 
11000     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11001     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11002     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11003     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11004     DS.ClearTypeSpecType();
11005   }
11006 
11007   if (D.isInvalidType())
11008     return;
11009 
11010   // Check the declarator is simple enough.
11011   bool FoundFunction = false;
11012   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11013     if (Chunk.Kind == DeclaratorChunk::Paren)
11014       continue;
11015     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11016       Diag(D.getDeclSpec().getBeginLoc(),
11017            diag::err_deduction_guide_with_complex_decl)
11018           << D.getSourceRange();
11019       break;
11020     }
11021     if (!Chunk.Fun.hasTrailingReturnType()) {
11022       Diag(D.getName().getBeginLoc(),
11023            diag::err_deduction_guide_no_trailing_return_type);
11024       break;
11025     }
11026 
11027     // Check that the return type is written as a specialization of
11028     // the template specified as the deduction-guide's name.
11029     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11030     TypeSourceInfo *TSI = nullptr;
11031     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11032     assert(TSI && "deduction guide has valid type but invalid return type?");
11033     bool AcceptableReturnType = false;
11034     bool MightInstantiateToSpecialization = false;
11035     if (auto RetTST =
11036             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
11037       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11038       bool TemplateMatches =
11039           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11040       // FIXME: We should consider other template kinds (using, qualified),
11041       // otherwise we will emit bogus diagnostics.
11042       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
11043         AcceptableReturnType = true;
11044       else {
11045         // This could still instantiate to the right type, unless we know it
11046         // names the wrong class template.
11047         auto *TD = SpecifiedName.getAsTemplateDecl();
11048         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11049                                              !TemplateMatches);
11050       }
11051     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11052       MightInstantiateToSpecialization = true;
11053     }
11054 
11055     if (!AcceptableReturnType) {
11056       Diag(TSI->getTypeLoc().getBeginLoc(),
11057            diag::err_deduction_guide_bad_trailing_return_type)
11058           << GuidedTemplate << TSI->getType()
11059           << MightInstantiateToSpecialization
11060           << TSI->getTypeLoc().getSourceRange();
11061     }
11062 
11063     // Keep going to check that we don't have any inner declarator pieces (we
11064     // could still have a function returning a pointer to a function).
11065     FoundFunction = true;
11066   }
11067 
11068   if (D.isFunctionDefinition())
11069     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11070 }
11071 
11072 //===----------------------------------------------------------------------===//
11073 // Namespace Handling
11074 //===----------------------------------------------------------------------===//
11075 
11076 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11077 /// reopened.
11078 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11079                                             SourceLocation Loc,
11080                                             IdentifierInfo *II, bool *IsInline,
11081                                             NamespaceDecl *PrevNS) {
11082   assert(*IsInline != PrevNS->isInline());
11083 
11084   // 'inline' must appear on the original definition, but not necessarily
11085   // on all extension definitions, so the note should point to the first
11086   // definition to avoid confusion.
11087   PrevNS = PrevNS->getFirstDecl();
11088 
11089   if (PrevNS->isInline())
11090     // The user probably just forgot the 'inline', so suggest that it
11091     // be added back.
11092     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11093       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11094   else
11095     S.Diag(Loc, diag::err_inline_namespace_mismatch);
11096 
11097   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11098   *IsInline = PrevNS->isInline();
11099 }
11100 
11101 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11102 /// definition.
11103 Decl *Sema::ActOnStartNamespaceDef(
11104     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
11105     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
11106     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
11107   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11108   // For anonymous namespace, take the location of the left brace.
11109   SourceLocation Loc = II ? IdentLoc : LBrace;
11110   bool IsInline = InlineLoc.isValid();
11111   bool IsInvalid = false;
11112   bool IsStd = false;
11113   bool AddToKnown = false;
11114   Scope *DeclRegionScope = NamespcScope->getParent();
11115 
11116   NamespaceDecl *PrevNS = nullptr;
11117   if (II) {
11118     // C++ [namespace.def]p2:
11119     //   The identifier in an original-namespace-definition shall not
11120     //   have been previously defined in the declarative region in
11121     //   which the original-namespace-definition appears. The
11122     //   identifier in an original-namespace-definition is the name of
11123     //   the namespace. Subsequently in that declarative region, it is
11124     //   treated as an original-namespace-name.
11125     //
11126     // Since namespace names are unique in their scope, and we don't
11127     // look through using directives, just look for any ordinary names
11128     // as if by qualified name lookup.
11129     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11130                    ForExternalRedeclaration);
11131     LookupQualifiedName(R, CurContext->getRedeclContext());
11132     NamedDecl *PrevDecl =
11133         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11134     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11135 
11136     if (PrevNS) {
11137       // This is an extended namespace definition.
11138       if (IsInline != PrevNS->isInline())
11139         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11140                                         &IsInline, PrevNS);
11141     } else if (PrevDecl) {
11142       // This is an invalid name redefinition.
11143       Diag(Loc, diag::err_redefinition_different_kind)
11144         << II;
11145       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11146       IsInvalid = true;
11147       // Continue on to push Namespc as current DeclContext and return it.
11148     } else if (II->isStr("std") &&
11149                CurContext->getRedeclContext()->isTranslationUnit()) {
11150       // This is the first "real" definition of the namespace "std", so update
11151       // our cache of the "std" namespace to point at this definition.
11152       PrevNS = getStdNamespace();
11153       IsStd = true;
11154       AddToKnown = !IsInline;
11155     } else {
11156       // We've seen this namespace for the first time.
11157       AddToKnown = !IsInline;
11158     }
11159   } else {
11160     // Anonymous namespaces.
11161 
11162     // Determine whether the parent already has an anonymous namespace.
11163     DeclContext *Parent = CurContext->getRedeclContext();
11164     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11165       PrevNS = TU->getAnonymousNamespace();
11166     } else {
11167       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11168       PrevNS = ND->getAnonymousNamespace();
11169     }
11170 
11171     if (PrevNS && IsInline != PrevNS->isInline())
11172       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11173                                       &IsInline, PrevNS);
11174   }
11175 
11176   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
11177                                                  StartLoc, Loc, II, PrevNS);
11178   if (IsInvalid)
11179     Namespc->setInvalidDecl();
11180 
11181   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11182   AddPragmaAttributes(DeclRegionScope, Namespc);
11183 
11184   // FIXME: Should we be merging attributes?
11185   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11186     PushNamespaceVisibilityAttr(Attr, Loc);
11187 
11188   if (IsStd)
11189     StdNamespace = Namespc;
11190   if (AddToKnown)
11191     KnownNamespaces[Namespc] = false;
11192 
11193   if (II) {
11194     PushOnScopeChains(Namespc, DeclRegionScope);
11195   } else {
11196     // Link the anonymous namespace into its parent.
11197     DeclContext *Parent = CurContext->getRedeclContext();
11198     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11199       TU->setAnonymousNamespace(Namespc);
11200     } else {
11201       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11202     }
11203 
11204     CurContext->addDecl(Namespc);
11205 
11206     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11207     //   behaves as if it were replaced by
11208     //     namespace unique { /* empty body */ }
11209     //     using namespace unique;
11210     //     namespace unique { namespace-body }
11211     //   where all occurrences of 'unique' in a translation unit are
11212     //   replaced by the same identifier and this identifier differs
11213     //   from all other identifiers in the entire program.
11214 
11215     // We just create the namespace with an empty name and then add an
11216     // implicit using declaration, just like the standard suggests.
11217     //
11218     // CodeGen enforces the "universally unique" aspect by giving all
11219     // declarations semantically contained within an anonymous
11220     // namespace internal linkage.
11221 
11222     if (!PrevNS) {
11223       UD = UsingDirectiveDecl::Create(Context, Parent,
11224                                       /* 'using' */ LBrace,
11225                                       /* 'namespace' */ SourceLocation(),
11226                                       /* qualifier */ NestedNameSpecifierLoc(),
11227                                       /* identifier */ SourceLocation(),
11228                                       Namespc,
11229                                       /* Ancestor */ Parent);
11230       UD->setImplicit();
11231       Parent->addDecl(UD);
11232     }
11233   }
11234 
11235   ActOnDocumentableDecl(Namespc);
11236 
11237   // Although we could have an invalid decl (i.e. the namespace name is a
11238   // redefinition), push it as current DeclContext and try to continue parsing.
11239   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11240   // for the namespace has the declarations that showed up in that particular
11241   // namespace definition.
11242   PushDeclContext(NamespcScope, Namespc);
11243   return Namespc;
11244 }
11245 
11246 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11247 /// is a namespace alias, returns the namespace it points to.
11248 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11249   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11250     return AD->getNamespace();
11251   return dyn_cast_or_null<NamespaceDecl>(D);
11252 }
11253 
11254 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11255 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11256 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11257   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11258   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11259   Namespc->setRBraceLoc(RBrace);
11260   PopDeclContext();
11261   if (Namespc->hasAttr<VisibilityAttr>())
11262     PopPragmaVisibility(true, RBrace);
11263   // If this namespace contains an export-declaration, export it now.
11264   if (DeferredExportedNamespaces.erase(Namespc))
11265     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11266 }
11267 
11268 CXXRecordDecl *Sema::getStdBadAlloc() const {
11269   return cast_or_null<CXXRecordDecl>(
11270                                   StdBadAlloc.get(Context.getExternalSource()));
11271 }
11272 
11273 EnumDecl *Sema::getStdAlignValT() const {
11274   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11275 }
11276 
11277 NamespaceDecl *Sema::getStdNamespace() const {
11278   return cast_or_null<NamespaceDecl>(
11279                                  StdNamespace.get(Context.getExternalSource()));
11280 }
11281 
11282 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11283   if (!StdExperimentalNamespaceCache) {
11284     if (auto Std = getStdNamespace()) {
11285       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11286                           SourceLocation(), LookupNamespaceName);
11287       if (!LookupQualifiedName(Result, Std) ||
11288           !(StdExperimentalNamespaceCache =
11289                 Result.getAsSingle<NamespaceDecl>()))
11290         Result.suppressDiagnostics();
11291     }
11292   }
11293   return StdExperimentalNamespaceCache;
11294 }
11295 
11296 namespace {
11297 
11298 enum UnsupportedSTLSelect {
11299   USS_InvalidMember,
11300   USS_MissingMember,
11301   USS_NonTrivial,
11302   USS_Other
11303 };
11304 
11305 struct InvalidSTLDiagnoser {
11306   Sema &S;
11307   SourceLocation Loc;
11308   QualType TyForDiags;
11309 
11310   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11311                       const VarDecl *VD = nullptr) {
11312     {
11313       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11314                << TyForDiags << ((int)Sel);
11315       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11316         assert(!Name.empty());
11317         D << Name;
11318       }
11319     }
11320     if (Sel == USS_InvalidMember) {
11321       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11322           << VD << VD->getSourceRange();
11323     }
11324     return QualType();
11325   }
11326 };
11327 } // namespace
11328 
11329 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11330                                            SourceLocation Loc,
11331                                            ComparisonCategoryUsage Usage) {
11332   assert(getLangOpts().CPlusPlus &&
11333          "Looking for comparison category type outside of C++.");
11334 
11335   // Use an elaborated type for diagnostics which has a name containing the
11336   // prepended 'std' namespace but not any inline namespace names.
11337   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11338     auto *NNS =
11339         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11340     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11341   };
11342 
11343   // Check if we've already successfully checked the comparison category type
11344   // before. If so, skip checking it again.
11345   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11346   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11347     // The only thing we need to check is that the type has a reachable
11348     // definition in the current context.
11349     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11350       return QualType();
11351 
11352     return Info->getType();
11353   }
11354 
11355   // If lookup failed
11356   if (!Info) {
11357     std::string NameForDiags = "std::";
11358     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11359     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11360         << NameForDiags << (int)Usage;
11361     return QualType();
11362   }
11363 
11364   assert(Info->Kind == Kind);
11365   assert(Info->Record);
11366 
11367   // Update the Record decl in case we encountered a forward declaration on our
11368   // first pass. FIXME: This is a bit of a hack.
11369   if (Info->Record->hasDefinition())
11370     Info->Record = Info->Record->getDefinition();
11371 
11372   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11373     return QualType();
11374 
11375   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11376 
11377   if (!Info->Record->isTriviallyCopyable())
11378     return UnsupportedSTLError(USS_NonTrivial);
11379 
11380   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11381     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11382     // Tolerate empty base classes.
11383     if (Base->isEmpty())
11384       continue;
11385     // Reject STL implementations which have at least one non-empty base.
11386     return UnsupportedSTLError();
11387   }
11388 
11389   // Check that the STL has implemented the types using a single integer field.
11390   // This expectation allows better codegen for builtin operators. We require:
11391   //   (1) The class has exactly one field.
11392   //   (2) The field is an integral or enumeration type.
11393   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11394   if (std::distance(FIt, FEnd) != 1 ||
11395       !FIt->getType()->isIntegralOrEnumerationType()) {
11396     return UnsupportedSTLError();
11397   }
11398 
11399   // Build each of the require values and store them in Info.
11400   for (ComparisonCategoryResult CCR :
11401        ComparisonCategories::getPossibleResultsForType(Kind)) {
11402     StringRef MemName = ComparisonCategories::getResultString(CCR);
11403     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11404 
11405     if (!ValInfo)
11406       return UnsupportedSTLError(USS_MissingMember, MemName);
11407 
11408     VarDecl *VD = ValInfo->VD;
11409     assert(VD && "should not be null!");
11410 
11411     // Attempt to diagnose reasons why the STL definition of this type
11412     // might be foobar, including it failing to be a constant expression.
11413     // TODO Handle more ways the lookup or result can be invalid.
11414     if (!VD->isStaticDataMember() ||
11415         !VD->isUsableInConstantExpressions(Context))
11416       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11417 
11418     // Attempt to evaluate the var decl as a constant expression and extract
11419     // the value of its first field as a ICE. If this fails, the STL
11420     // implementation is not supported.
11421     if (!ValInfo->hasValidIntValue())
11422       return UnsupportedSTLError();
11423 
11424     MarkVariableReferenced(Loc, VD);
11425   }
11426 
11427   // We've successfully built the required types and expressions. Update
11428   // the cache and return the newly cached value.
11429   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11430   return Info->getType();
11431 }
11432 
11433 /// Retrieve the special "std" namespace, which may require us to
11434 /// implicitly define the namespace.
11435 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11436   if (!StdNamespace) {
11437     // The "std" namespace has not yet been defined, so build one implicitly.
11438     StdNamespace = NamespaceDecl::Create(Context,
11439                                          Context.getTranslationUnitDecl(),
11440                                          /*Inline=*/false,
11441                                          SourceLocation(), SourceLocation(),
11442                                          &PP.getIdentifierTable().get("std"),
11443                                          /*PrevDecl=*/nullptr);
11444     getStdNamespace()->setImplicit(true);
11445   }
11446 
11447   return getStdNamespace();
11448 }
11449 
11450 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11451   assert(getLangOpts().CPlusPlus &&
11452          "Looking for std::initializer_list outside of C++.");
11453 
11454   // We're looking for implicit instantiations of
11455   // template <typename E> class std::initializer_list.
11456 
11457   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11458     return false;
11459 
11460   ClassTemplateDecl *Template = nullptr;
11461   const TemplateArgument *Arguments = nullptr;
11462 
11463   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11464 
11465     ClassTemplateSpecializationDecl *Specialization =
11466         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11467     if (!Specialization)
11468       return false;
11469 
11470     Template = Specialization->getSpecializedTemplate();
11471     Arguments = Specialization->getTemplateArgs().data();
11472   } else if (const TemplateSpecializationType *TST =
11473                  Ty->getAs<TemplateSpecializationType>()) {
11474     Template = dyn_cast_or_null<ClassTemplateDecl>(
11475         TST->getTemplateName().getAsTemplateDecl());
11476     Arguments = TST->getArgs();
11477   }
11478   if (!Template)
11479     return false;
11480 
11481   if (!StdInitializerList) {
11482     // Haven't recognized std::initializer_list yet, maybe this is it.
11483     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11484     if (TemplateClass->getIdentifier() !=
11485             &PP.getIdentifierTable().get("initializer_list") ||
11486         !getStdNamespace()->InEnclosingNamespaceSetOf(
11487             TemplateClass->getDeclContext()))
11488       return false;
11489     // This is a template called std::initializer_list, but is it the right
11490     // template?
11491     TemplateParameterList *Params = Template->getTemplateParameters();
11492     if (Params->getMinRequiredArguments() != 1)
11493       return false;
11494     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11495       return false;
11496 
11497     // It's the right template.
11498     StdInitializerList = Template;
11499   }
11500 
11501   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11502     return false;
11503 
11504   // This is an instance of std::initializer_list. Find the argument type.
11505   if (Element)
11506     *Element = Arguments[0].getAsType();
11507   return true;
11508 }
11509 
11510 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11511   NamespaceDecl *Std = S.getStdNamespace();
11512   if (!Std) {
11513     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11514     return nullptr;
11515   }
11516 
11517   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11518                       Loc, Sema::LookupOrdinaryName);
11519   if (!S.LookupQualifiedName(Result, Std)) {
11520     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11521     return nullptr;
11522   }
11523   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11524   if (!Template) {
11525     Result.suppressDiagnostics();
11526     // We found something weird. Complain about the first thing we found.
11527     NamedDecl *Found = *Result.begin();
11528     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11529     return nullptr;
11530   }
11531 
11532   // We found some template called std::initializer_list. Now verify that it's
11533   // correct.
11534   TemplateParameterList *Params = Template->getTemplateParameters();
11535   if (Params->getMinRequiredArguments() != 1 ||
11536       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11537     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11538     return nullptr;
11539   }
11540 
11541   return Template;
11542 }
11543 
11544 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11545   if (!StdInitializerList) {
11546     StdInitializerList = LookupStdInitializerList(*this, Loc);
11547     if (!StdInitializerList)
11548       return QualType();
11549   }
11550 
11551   TemplateArgumentListInfo Args(Loc, Loc);
11552   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11553                                        Context.getTrivialTypeSourceInfo(Element,
11554                                                                         Loc)));
11555   return Context.getCanonicalType(
11556       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11557 }
11558 
11559 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11560   // C++ [dcl.init.list]p2:
11561   //   A constructor is an initializer-list constructor if its first parameter
11562   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11563   //   std::initializer_list<E> for some type E, and either there are no other
11564   //   parameters or else all other parameters have default arguments.
11565   if (!Ctor->hasOneParamOrDefaultArgs())
11566     return false;
11567 
11568   QualType ArgType = Ctor->getParamDecl(0)->getType();
11569   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11570     ArgType = RT->getPointeeType().getUnqualifiedType();
11571 
11572   return isStdInitializerList(ArgType, nullptr);
11573 }
11574 
11575 /// Determine whether a using statement is in a context where it will be
11576 /// apply in all contexts.
11577 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11578   switch (CurContext->getDeclKind()) {
11579     case Decl::TranslationUnit:
11580       return true;
11581     case Decl::LinkageSpec:
11582       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11583     default:
11584       return false;
11585   }
11586 }
11587 
11588 namespace {
11589 
11590 // Callback to only accept typo corrections that are namespaces.
11591 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11592 public:
11593   bool ValidateCandidate(const TypoCorrection &candidate) override {
11594     if (NamedDecl *ND = candidate.getCorrectionDecl())
11595       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11596     return false;
11597   }
11598 
11599   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11600     return std::make_unique<NamespaceValidatorCCC>(*this);
11601   }
11602 };
11603 
11604 }
11605 
11606 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11607                                        CXXScopeSpec &SS,
11608                                        SourceLocation IdentLoc,
11609                                        IdentifierInfo *Ident) {
11610   R.clear();
11611   NamespaceValidatorCCC CCC{};
11612   if (TypoCorrection Corrected =
11613           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11614                         Sema::CTK_ErrorRecovery)) {
11615     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11616       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11617       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11618                               Ident->getName().equals(CorrectedStr);
11619       S.diagnoseTypo(Corrected,
11620                      S.PDiag(diag::err_using_directive_member_suggest)
11621                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11622                      S.PDiag(diag::note_namespace_defined_here));
11623     } else {
11624       S.diagnoseTypo(Corrected,
11625                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11626                      S.PDiag(diag::note_namespace_defined_here));
11627     }
11628     R.addDecl(Corrected.getFoundDecl());
11629     return true;
11630   }
11631   return false;
11632 }
11633 
11634 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11635                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11636                                 SourceLocation IdentLoc,
11637                                 IdentifierInfo *NamespcName,
11638                                 const ParsedAttributesView &AttrList) {
11639   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11640   assert(NamespcName && "Invalid NamespcName.");
11641   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11642 
11643   // This can only happen along a recovery path.
11644   while (S->isTemplateParamScope())
11645     S = S->getParent();
11646   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11647 
11648   UsingDirectiveDecl *UDir = nullptr;
11649   NestedNameSpecifier *Qualifier = nullptr;
11650   if (SS.isSet())
11651     Qualifier = SS.getScopeRep();
11652 
11653   // Lookup namespace name.
11654   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11655   LookupParsedName(R, S, &SS);
11656   if (R.isAmbiguous())
11657     return nullptr;
11658 
11659   if (R.empty()) {
11660     R.clear();
11661     // Allow "using namespace std;" or "using namespace ::std;" even if
11662     // "std" hasn't been defined yet, for GCC compatibility.
11663     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11664         NamespcName->isStr("std")) {
11665       Diag(IdentLoc, diag::ext_using_undefined_std);
11666       R.addDecl(getOrCreateStdNamespace());
11667       R.resolveKind();
11668     }
11669     // Otherwise, attempt typo correction.
11670     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11671   }
11672 
11673   if (!R.empty()) {
11674     NamedDecl *Named = R.getRepresentativeDecl();
11675     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11676     assert(NS && "expected namespace decl");
11677 
11678     // The use of a nested name specifier may trigger deprecation warnings.
11679     DiagnoseUseOfDecl(Named, IdentLoc);
11680 
11681     // C++ [namespace.udir]p1:
11682     //   A using-directive specifies that the names in the nominated
11683     //   namespace can be used in the scope in which the
11684     //   using-directive appears after the using-directive. During
11685     //   unqualified name lookup (3.4.1), the names appear as if they
11686     //   were declared in the nearest enclosing namespace which
11687     //   contains both the using-directive and the nominated
11688     //   namespace. [Note: in this context, "contains" means "contains
11689     //   directly or indirectly". ]
11690 
11691     // Find enclosing context containing both using-directive and
11692     // nominated namespace.
11693     DeclContext *CommonAncestor = NS;
11694     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11695       CommonAncestor = CommonAncestor->getParent();
11696 
11697     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11698                                       SS.getWithLocInContext(Context),
11699                                       IdentLoc, Named, CommonAncestor);
11700 
11701     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11702         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11703       Diag(IdentLoc, diag::warn_using_directive_in_header);
11704     }
11705 
11706     PushUsingDirective(S, UDir);
11707   } else {
11708     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11709   }
11710 
11711   if (UDir)
11712     ProcessDeclAttributeList(S, UDir, AttrList);
11713 
11714   return UDir;
11715 }
11716 
11717 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11718   // If the scope has an associated entity and the using directive is at
11719   // namespace or translation unit scope, add the UsingDirectiveDecl into
11720   // its lookup structure so qualified name lookup can find it.
11721   DeclContext *Ctx = S->getEntity();
11722   if (Ctx && !Ctx->isFunctionOrMethod())
11723     Ctx->addDecl(UDir);
11724   else
11725     // Otherwise, it is at block scope. The using-directives will affect lookup
11726     // only to the end of the scope.
11727     S->PushUsingDirective(UDir);
11728 }
11729 
11730 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11731                                   SourceLocation UsingLoc,
11732                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11733                                   UnqualifiedId &Name,
11734                                   SourceLocation EllipsisLoc,
11735                                   const ParsedAttributesView &AttrList) {
11736   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11737 
11738   if (SS.isEmpty()) {
11739     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11740     return nullptr;
11741   }
11742 
11743   switch (Name.getKind()) {
11744   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11745   case UnqualifiedIdKind::IK_Identifier:
11746   case UnqualifiedIdKind::IK_OperatorFunctionId:
11747   case UnqualifiedIdKind::IK_LiteralOperatorId:
11748   case UnqualifiedIdKind::IK_ConversionFunctionId:
11749     break;
11750 
11751   case UnqualifiedIdKind::IK_ConstructorName:
11752   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11753     // C++11 inheriting constructors.
11754     Diag(Name.getBeginLoc(),
11755          getLangOpts().CPlusPlus11
11756              ? diag::warn_cxx98_compat_using_decl_constructor
11757              : diag::err_using_decl_constructor)
11758         << SS.getRange();
11759 
11760     if (getLangOpts().CPlusPlus11) break;
11761 
11762     return nullptr;
11763 
11764   case UnqualifiedIdKind::IK_DestructorName:
11765     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11766     return nullptr;
11767 
11768   case UnqualifiedIdKind::IK_TemplateId:
11769     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11770         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11771     return nullptr;
11772 
11773   case UnqualifiedIdKind::IK_DeductionGuideName:
11774     llvm_unreachable("cannot parse qualified deduction guide name");
11775   }
11776 
11777   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11778   DeclarationName TargetName = TargetNameInfo.getName();
11779   if (!TargetName)
11780     return nullptr;
11781 
11782   // Warn about access declarations.
11783   if (UsingLoc.isInvalid()) {
11784     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11785                                  ? diag::err_access_decl
11786                                  : diag::warn_access_decl_deprecated)
11787         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11788   }
11789 
11790   if (EllipsisLoc.isInvalid()) {
11791     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11792         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11793       return nullptr;
11794   } else {
11795     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11796         !TargetNameInfo.containsUnexpandedParameterPack()) {
11797       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11798         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11799       EllipsisLoc = SourceLocation();
11800     }
11801   }
11802 
11803   NamedDecl *UD =
11804       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11805                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11806                             /*IsInstantiation*/ false,
11807                             AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11808   if (UD)
11809     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11810 
11811   return UD;
11812 }
11813 
11814 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
11815                                       SourceLocation UsingLoc,
11816                                       SourceLocation EnumLoc,
11817                                       const DeclSpec &DS) {
11818   switch (DS.getTypeSpecType()) {
11819   case DeclSpec::TST_error:
11820     // This will already have been diagnosed
11821     return nullptr;
11822 
11823   case DeclSpec::TST_enum:
11824     break;
11825 
11826   case DeclSpec::TST_typename:
11827     Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
11828     return nullptr;
11829 
11830   default:
11831     llvm_unreachable("unexpected DeclSpec type");
11832   }
11833 
11834   // As with enum-decls, we ignore attributes for now.
11835   auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
11836   if (auto *Def = Enum->getDefinition())
11837     Enum = Def;
11838 
11839   auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
11840                                        DS.getTypeSpecTypeNameLoc(), Enum);
11841   if (UD)
11842     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11843 
11844   return UD;
11845 }
11846 
11847 /// Determine whether a using declaration considers the given
11848 /// declarations as "equivalent", e.g., if they are redeclarations of
11849 /// the same entity or are both typedefs of the same type.
11850 static bool
11851 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11852   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11853     return true;
11854 
11855   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11856     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11857       return Context.hasSameType(TD1->getUnderlyingType(),
11858                                  TD2->getUnderlyingType());
11859 
11860   // Two using_if_exists using-declarations are equivalent if both are
11861   // unresolved.
11862   if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11863       isa<UnresolvedUsingIfExistsDecl>(D2))
11864     return true;
11865 
11866   return false;
11867 }
11868 
11869 
11870 /// Determines whether to create a using shadow decl for a particular
11871 /// decl, given the set of decls existing prior to this using lookup.
11872 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
11873                                 const LookupResult &Previous,
11874                                 UsingShadowDecl *&PrevShadow) {
11875   // Diagnose finding a decl which is not from a base class of the
11876   // current class.  We do this now because there are cases where this
11877   // function will silently decide not to build a shadow decl, which
11878   // will pre-empt further diagnostics.
11879   //
11880   // We don't need to do this in C++11 because we do the check once on
11881   // the qualifier.
11882   //
11883   // FIXME: diagnose the following if we care enough:
11884   //   struct A { int foo; };
11885   //   struct B : A { using A::foo; };
11886   //   template <class T> struct C : A {};
11887   //   template <class T> struct D : C<T> { using B::foo; } // <---
11888   // This is invalid (during instantiation) in C++03 because B::foo
11889   // resolves to the using decl in B, which is not a base class of D<T>.
11890   // We can't diagnose it immediately because C<T> is an unknown
11891   // specialization. The UsingShadowDecl in D<T> then points directly
11892   // to A::foo, which will look well-formed when we instantiate.
11893   // The right solution is to not collapse the shadow-decl chain.
11894   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
11895     if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
11896       DeclContext *OrigDC = Orig->getDeclContext();
11897 
11898       // Handle enums and anonymous structs.
11899       if (isa<EnumDecl>(OrigDC))
11900         OrigDC = OrigDC->getParent();
11901       CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11902       while (OrigRec->isAnonymousStructOrUnion())
11903         OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11904 
11905       if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11906         if (OrigDC == CurContext) {
11907           Diag(Using->getLocation(),
11908                diag::err_using_decl_nested_name_specifier_is_current_class)
11909               << Using->getQualifierLoc().getSourceRange();
11910           Diag(Orig->getLocation(), diag::note_using_decl_target);
11911           Using->setInvalidDecl();
11912           return true;
11913         }
11914 
11915         Diag(Using->getQualifierLoc().getBeginLoc(),
11916              diag::err_using_decl_nested_name_specifier_is_not_base_class)
11917             << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
11918             << Using->getQualifierLoc().getSourceRange();
11919         Diag(Orig->getLocation(), diag::note_using_decl_target);
11920         Using->setInvalidDecl();
11921         return true;
11922       }
11923     }
11924 
11925   if (Previous.empty()) return false;
11926 
11927   NamedDecl *Target = Orig;
11928   if (isa<UsingShadowDecl>(Target))
11929     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11930 
11931   // If the target happens to be one of the previous declarations, we
11932   // don't have a conflict.
11933   //
11934   // FIXME: but we might be increasing its access, in which case we
11935   // should redeclare it.
11936   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11937   bool FoundEquivalentDecl = false;
11938   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11939          I != E; ++I) {
11940     NamedDecl *D = (*I)->getUnderlyingDecl();
11941     // We can have UsingDecls in our Previous results because we use the same
11942     // LookupResult for checking whether the UsingDecl itself is a valid
11943     // redeclaration.
11944     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
11945       continue;
11946 
11947     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11948       // C++ [class.mem]p19:
11949       //   If T is the name of a class, then [every named member other than
11950       //   a non-static data member] shall have a name different from T
11951       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11952           !isa<IndirectFieldDecl>(Target) &&
11953           !isa<UnresolvedUsingValueDecl>(Target) &&
11954           DiagnoseClassNameShadow(
11955               CurContext,
11956               DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
11957         return true;
11958     }
11959 
11960     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11961       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11962         PrevShadow = Shadow;
11963       FoundEquivalentDecl = true;
11964     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11965       // We don't conflict with an existing using shadow decl of an equivalent
11966       // declaration, but we're not a redeclaration of it.
11967       FoundEquivalentDecl = true;
11968     }
11969 
11970     if (isVisible(D))
11971       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11972   }
11973 
11974   if (FoundEquivalentDecl)
11975     return false;
11976 
11977   // Always emit a diagnostic for a mismatch between an unresolved
11978   // using_if_exists and a resolved using declaration in either direction.
11979   if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
11980       (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
11981     if (!NonTag && !Tag)
11982       return false;
11983     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11984     Diag(Target->getLocation(), diag::note_using_decl_target);
11985     Diag((NonTag ? NonTag : Tag)->getLocation(),
11986          diag::note_using_decl_conflict);
11987     BUD->setInvalidDecl();
11988     return true;
11989   }
11990 
11991   if (FunctionDecl *FD = Target->getAsFunction()) {
11992     NamedDecl *OldDecl = nullptr;
11993     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11994                           /*IsForUsingDecl*/ true)) {
11995     case Ovl_Overload:
11996       return false;
11997 
11998     case Ovl_NonFunction:
11999       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12000       break;
12001 
12002     // We found a decl with the exact signature.
12003     case Ovl_Match:
12004       // If we're in a record, we want to hide the target, so we
12005       // return true (without a diagnostic) to tell the caller not to
12006       // build a shadow decl.
12007       if (CurContext->isRecord())
12008         return true;
12009 
12010       // If we're not in a record, this is an error.
12011       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12012       break;
12013     }
12014 
12015     Diag(Target->getLocation(), diag::note_using_decl_target);
12016     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12017     BUD->setInvalidDecl();
12018     return true;
12019   }
12020 
12021   // Target is not a function.
12022 
12023   if (isa<TagDecl>(Target)) {
12024     // No conflict between a tag and a non-tag.
12025     if (!Tag) return false;
12026 
12027     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12028     Diag(Target->getLocation(), diag::note_using_decl_target);
12029     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12030     BUD->setInvalidDecl();
12031     return true;
12032   }
12033 
12034   // No conflict between a tag and a non-tag.
12035   if (!NonTag) return false;
12036 
12037   Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12038   Diag(Target->getLocation(), diag::note_using_decl_target);
12039   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12040   BUD->setInvalidDecl();
12041   return true;
12042 }
12043 
12044 /// Determine whether a direct base class is a virtual base class.
12045 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12046   if (!Derived->getNumVBases())
12047     return false;
12048   for (auto &B : Derived->bases())
12049     if (B.getType()->getAsCXXRecordDecl() == Base)
12050       return B.isVirtual();
12051   llvm_unreachable("not a direct base class");
12052 }
12053 
12054 /// Builds a shadow declaration corresponding to a 'using' declaration.
12055 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12056                                             NamedDecl *Orig,
12057                                             UsingShadowDecl *PrevDecl) {
12058   // If we resolved to another shadow declaration, just coalesce them.
12059   NamedDecl *Target = Orig;
12060   if (isa<UsingShadowDecl>(Target)) {
12061     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12062     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12063   }
12064 
12065   NamedDecl *NonTemplateTarget = Target;
12066   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12067     NonTemplateTarget = TargetTD->getTemplatedDecl();
12068 
12069   UsingShadowDecl *Shadow;
12070   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12071     UsingDecl *Using = cast<UsingDecl>(BUD);
12072     bool IsVirtualBase =
12073         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12074                             Using->getQualifier()->getAsRecordDecl());
12075     Shadow = ConstructorUsingShadowDecl::Create(
12076         Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12077   } else {
12078     Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12079                                      Target->getDeclName(), BUD, Target);
12080   }
12081   BUD->addShadowDecl(Shadow);
12082 
12083   Shadow->setAccess(BUD->getAccess());
12084   if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12085     Shadow->setInvalidDecl();
12086 
12087   Shadow->setPreviousDecl(PrevDecl);
12088 
12089   if (S)
12090     PushOnScopeChains(Shadow, S);
12091   else
12092     CurContext->addDecl(Shadow);
12093 
12094 
12095   return Shadow;
12096 }
12097 
12098 /// Hides a using shadow declaration.  This is required by the current
12099 /// using-decl implementation when a resolvable using declaration in a
12100 /// class is followed by a declaration which would hide or override
12101 /// one or more of the using decl's targets; for example:
12102 ///
12103 ///   struct Base { void foo(int); };
12104 ///   struct Derived : Base {
12105 ///     using Base::foo;
12106 ///     void foo(int);
12107 ///   };
12108 ///
12109 /// The governing language is C++03 [namespace.udecl]p12:
12110 ///
12111 ///   When a using-declaration brings names from a base class into a
12112 ///   derived class scope, member functions in the derived class
12113 ///   override and/or hide member functions with the same name and
12114 ///   parameter types in a base class (rather than conflicting).
12115 ///
12116 /// There are two ways to implement this:
12117 ///   (1) optimistically create shadow decls when they're not hidden
12118 ///       by existing declarations, or
12119 ///   (2) don't create any shadow decls (or at least don't make them
12120 ///       visible) until we've fully parsed/instantiated the class.
12121 /// The problem with (1) is that we might have to retroactively remove
12122 /// a shadow decl, which requires several O(n) operations because the
12123 /// decl structures are (very reasonably) not designed for removal.
12124 /// (2) avoids this but is very fiddly and phase-dependent.
12125 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12126   if (Shadow->getDeclName().getNameKind() ==
12127         DeclarationName::CXXConversionFunctionName)
12128     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12129 
12130   // Remove it from the DeclContext...
12131   Shadow->getDeclContext()->removeDecl(Shadow);
12132 
12133   // ...and the scope, if applicable...
12134   if (S) {
12135     S->RemoveDecl(Shadow);
12136     IdResolver.RemoveDecl(Shadow);
12137   }
12138 
12139   // ...and the using decl.
12140   Shadow->getIntroducer()->removeShadowDecl(Shadow);
12141 
12142   // TODO: complain somehow if Shadow was used.  It shouldn't
12143   // be possible for this to happen, because...?
12144 }
12145 
12146 /// Find the base specifier for a base class with the given type.
12147 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12148                                                 QualType DesiredBase,
12149                                                 bool &AnyDependentBases) {
12150   // Check whether the named type is a direct base class.
12151   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12152     .getUnqualifiedType();
12153   for (auto &Base : Derived->bases()) {
12154     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12155     if (CanonicalDesiredBase == BaseType)
12156       return &Base;
12157     if (BaseType->isDependentType())
12158       AnyDependentBases = true;
12159   }
12160   return nullptr;
12161 }
12162 
12163 namespace {
12164 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12165 public:
12166   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12167                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12168       : HasTypenameKeyword(HasTypenameKeyword),
12169         IsInstantiation(IsInstantiation), OldNNS(NNS),
12170         RequireMemberOf(RequireMemberOf) {}
12171 
12172   bool ValidateCandidate(const TypoCorrection &Candidate) override {
12173     NamedDecl *ND = Candidate.getCorrectionDecl();
12174 
12175     // Keywords are not valid here.
12176     if (!ND || isa<NamespaceDecl>(ND))
12177       return false;
12178 
12179     // Completely unqualified names are invalid for a 'using' declaration.
12180     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12181       return false;
12182 
12183     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12184     // reject.
12185 
12186     if (RequireMemberOf) {
12187       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12188       if (FoundRecord && FoundRecord->isInjectedClassName()) {
12189         // No-one ever wants a using-declaration to name an injected-class-name
12190         // of a base class, unless they're declaring an inheriting constructor.
12191         ASTContext &Ctx = ND->getASTContext();
12192         if (!Ctx.getLangOpts().CPlusPlus11)
12193           return false;
12194         QualType FoundType = Ctx.getRecordType(FoundRecord);
12195 
12196         // Check that the injected-class-name is named as a member of its own
12197         // type; we don't want to suggest 'using Derived::Base;', since that
12198         // means something else.
12199         NestedNameSpecifier *Specifier =
12200             Candidate.WillReplaceSpecifier()
12201                 ? Candidate.getCorrectionSpecifier()
12202                 : OldNNS;
12203         if (!Specifier->getAsType() ||
12204             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12205           return false;
12206 
12207         // Check that this inheriting constructor declaration actually names a
12208         // direct base class of the current class.
12209         bool AnyDependentBases = false;
12210         if (!findDirectBaseWithType(RequireMemberOf,
12211                                     Ctx.getRecordType(FoundRecord),
12212                                     AnyDependentBases) &&
12213             !AnyDependentBases)
12214           return false;
12215       } else {
12216         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12217         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12218           return false;
12219 
12220         // FIXME: Check that the base class member is accessible?
12221       }
12222     } else {
12223       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12224       if (FoundRecord && FoundRecord->isInjectedClassName())
12225         return false;
12226     }
12227 
12228     if (isa<TypeDecl>(ND))
12229       return HasTypenameKeyword || !IsInstantiation;
12230 
12231     return !HasTypenameKeyword;
12232   }
12233 
12234   std::unique_ptr<CorrectionCandidateCallback> clone() override {
12235     return std::make_unique<UsingValidatorCCC>(*this);
12236   }
12237 
12238 private:
12239   bool HasTypenameKeyword;
12240   bool IsInstantiation;
12241   NestedNameSpecifier *OldNNS;
12242   CXXRecordDecl *RequireMemberOf;
12243 };
12244 } // end anonymous namespace
12245 
12246 /// Remove decls we can't actually see from a lookup being used to declare
12247 /// shadow using decls.
12248 ///
12249 /// \param S - The scope of the potential shadow decl
12250 /// \param Previous - The lookup of a potential shadow decl's name.
12251 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12252   // It is really dumb that we have to do this.
12253   LookupResult::Filter F = Previous.makeFilter();
12254   while (F.hasNext()) {
12255     NamedDecl *D = F.next();
12256     if (!isDeclInScope(D, CurContext, S))
12257       F.erase();
12258     // If we found a local extern declaration that's not ordinarily visible,
12259     // and this declaration is being added to a non-block scope, ignore it.
12260     // We're only checking for scope conflicts here, not also for violations
12261     // of the linkage rules.
12262     else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12263              !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12264       F.erase();
12265   }
12266   F.done();
12267 }
12268 
12269 /// Builds a using declaration.
12270 ///
12271 /// \param IsInstantiation - Whether this call arises from an
12272 ///   instantiation of an unresolved using declaration.  We treat
12273 ///   the lookup differently for these declarations.
12274 NamedDecl *Sema::BuildUsingDeclaration(
12275     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12276     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12277     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12278     const ParsedAttributesView &AttrList, bool IsInstantiation,
12279     bool IsUsingIfExists) {
12280   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12281   SourceLocation IdentLoc = NameInfo.getLoc();
12282   assert(IdentLoc.isValid() && "Invalid TargetName location.");
12283 
12284   // FIXME: We ignore attributes for now.
12285 
12286   // For an inheriting constructor declaration, the name of the using
12287   // declaration is the name of a constructor in this class, not in the
12288   // base class.
12289   DeclarationNameInfo UsingName = NameInfo;
12290   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12291     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12292       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12293           Context.getCanonicalType(Context.getRecordType(RD))));
12294 
12295   // Do the redeclaration lookup in the current scope.
12296   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12297                         ForVisibleRedeclaration);
12298   Previous.setHideTags(false);
12299   if (S) {
12300     LookupName(Previous, S);
12301 
12302     FilterUsingLookup(S, Previous);
12303   } else {
12304     assert(IsInstantiation && "no scope in non-instantiation");
12305     if (CurContext->isRecord())
12306       LookupQualifiedName(Previous, CurContext);
12307     else {
12308       // No redeclaration check is needed here; in non-member contexts we
12309       // diagnosed all possible conflicts with other using-declarations when
12310       // building the template:
12311       //
12312       // For a dependent non-type using declaration, the only valid case is
12313       // if we instantiate to a single enumerator. We check for conflicts
12314       // between shadow declarations we introduce, and we check in the template
12315       // definition for conflicts between a non-type using declaration and any
12316       // other declaration, which together covers all cases.
12317       //
12318       // A dependent typename using declaration will never successfully
12319       // instantiate, since it will always name a class member, so we reject
12320       // that in the template definition.
12321     }
12322   }
12323 
12324   // Check for invalid redeclarations.
12325   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12326                                   SS, IdentLoc, Previous))
12327     return nullptr;
12328 
12329   // 'using_if_exists' doesn't make sense on an inherited constructor.
12330   if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12331                              DeclarationName::CXXConstructorName) {
12332     Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12333     return nullptr;
12334   }
12335 
12336   DeclContext *LookupContext = computeDeclContext(SS);
12337   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12338   if (!LookupContext || EllipsisLoc.isValid()) {
12339     NamedDecl *D;
12340     // Dependent scope, or an unexpanded pack
12341     if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12342                                                   SS, NameInfo, IdentLoc))
12343       return nullptr;
12344 
12345     if (HasTypenameKeyword) {
12346       // FIXME: not all declaration name kinds are legal here
12347       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12348                                               UsingLoc, TypenameLoc,
12349                                               QualifierLoc,
12350                                               IdentLoc, NameInfo.getName(),
12351                                               EllipsisLoc);
12352     } else {
12353       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12354                                            QualifierLoc, NameInfo, EllipsisLoc);
12355     }
12356     D->setAccess(AS);
12357     CurContext->addDecl(D);
12358     ProcessDeclAttributeList(S, D, AttrList);
12359     return D;
12360   }
12361 
12362   auto Build = [&](bool Invalid) {
12363     UsingDecl *UD =
12364         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12365                           UsingName, HasTypenameKeyword);
12366     UD->setAccess(AS);
12367     CurContext->addDecl(UD);
12368     ProcessDeclAttributeList(S, UD, AttrList);
12369     UD->setInvalidDecl(Invalid);
12370     return UD;
12371   };
12372   auto BuildInvalid = [&]{ return Build(true); };
12373   auto BuildValid = [&]{ return Build(false); };
12374 
12375   if (RequireCompleteDeclContext(SS, LookupContext))
12376     return BuildInvalid();
12377 
12378   // Look up the target name.
12379   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12380 
12381   // Unlike most lookups, we don't always want to hide tag
12382   // declarations: tag names are visible through the using declaration
12383   // even if hidden by ordinary names, *except* in a dependent context
12384   // where they may be used by two-phase lookup.
12385   if (!IsInstantiation)
12386     R.setHideTags(false);
12387 
12388   // For the purposes of this lookup, we have a base object type
12389   // equal to that of the current context.
12390   if (CurContext->isRecord()) {
12391     R.setBaseObjectType(
12392                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12393   }
12394 
12395   LookupQualifiedName(R, LookupContext);
12396 
12397   // Validate the context, now we have a lookup
12398   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12399                               IdentLoc, &R))
12400     return nullptr;
12401 
12402   if (R.empty() && IsUsingIfExists)
12403     R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12404                                                   UsingName.getName()),
12405               AS_public);
12406 
12407   // Try to correct typos if possible. If constructor name lookup finds no
12408   // results, that means the named class has no explicit constructors, and we
12409   // suppressed declaring implicit ones (probably because it's dependent or
12410   // invalid).
12411   if (R.empty() &&
12412       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12413     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12414     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12415     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12416     auto *II = NameInfo.getName().getAsIdentifierInfo();
12417     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12418         CurContext->isStdNamespace() &&
12419         isa<TranslationUnitDecl>(LookupContext) &&
12420         getSourceManager().isInSystemHeader(UsingLoc))
12421       return nullptr;
12422     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12423                           dyn_cast<CXXRecordDecl>(CurContext));
12424     if (TypoCorrection Corrected =
12425             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12426                         CTK_ErrorRecovery)) {
12427       // We reject candidates where DroppedSpecifier == true, hence the
12428       // literal '0' below.
12429       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12430                                 << NameInfo.getName() << LookupContext << 0
12431                                 << SS.getRange());
12432 
12433       // If we picked a correction with no attached Decl we can't do anything
12434       // useful with it, bail out.
12435       NamedDecl *ND = Corrected.getCorrectionDecl();
12436       if (!ND)
12437         return BuildInvalid();
12438 
12439       // If we corrected to an inheriting constructor, handle it as one.
12440       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12441       if (RD && RD->isInjectedClassName()) {
12442         // The parent of the injected class name is the class itself.
12443         RD = cast<CXXRecordDecl>(RD->getParent());
12444 
12445         // Fix up the information we'll use to build the using declaration.
12446         if (Corrected.WillReplaceSpecifier()) {
12447           NestedNameSpecifierLocBuilder Builder;
12448           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12449                               QualifierLoc.getSourceRange());
12450           QualifierLoc = Builder.getWithLocInContext(Context);
12451         }
12452 
12453         // In this case, the name we introduce is the name of a derived class
12454         // constructor.
12455         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12456         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12457             Context.getCanonicalType(Context.getRecordType(CurClass))));
12458         UsingName.setNamedTypeInfo(nullptr);
12459         for (auto *Ctor : LookupConstructors(RD))
12460           R.addDecl(Ctor);
12461         R.resolveKind();
12462       } else {
12463         // FIXME: Pick up all the declarations if we found an overloaded
12464         // function.
12465         UsingName.setName(ND->getDeclName());
12466         R.addDecl(ND);
12467       }
12468     } else {
12469       Diag(IdentLoc, diag::err_no_member)
12470         << NameInfo.getName() << LookupContext << SS.getRange();
12471       return BuildInvalid();
12472     }
12473   }
12474 
12475   if (R.isAmbiguous())
12476     return BuildInvalid();
12477 
12478   if (HasTypenameKeyword) {
12479     // If we asked for a typename and got a non-type decl, error out.
12480     if (!R.getAsSingle<TypeDecl>() &&
12481         !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12482       Diag(IdentLoc, diag::err_using_typename_non_type);
12483       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12484         Diag((*I)->getUnderlyingDecl()->getLocation(),
12485              diag::note_using_decl_target);
12486       return BuildInvalid();
12487     }
12488   } else {
12489     // If we asked for a non-typename and we got a type, error out,
12490     // but only if this is an instantiation of an unresolved using
12491     // decl.  Otherwise just silently find the type name.
12492     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12493       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12494       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12495       return BuildInvalid();
12496     }
12497   }
12498 
12499   // C++14 [namespace.udecl]p6:
12500   // A using-declaration shall not name a namespace.
12501   if (R.getAsSingle<NamespaceDecl>()) {
12502     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12503       << SS.getRange();
12504     return BuildInvalid();
12505   }
12506 
12507   UsingDecl *UD = BuildValid();
12508 
12509   // Some additional rules apply to inheriting constructors.
12510   if (UsingName.getName().getNameKind() ==
12511         DeclarationName::CXXConstructorName) {
12512     // Suppress access diagnostics; the access check is instead performed at the
12513     // point of use for an inheriting constructor.
12514     R.suppressDiagnostics();
12515     if (CheckInheritingConstructorUsingDecl(UD))
12516       return UD;
12517   }
12518 
12519   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12520     UsingShadowDecl *PrevDecl = nullptr;
12521     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12522       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12523   }
12524 
12525   return UD;
12526 }
12527 
12528 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12529                                            SourceLocation UsingLoc,
12530                                            SourceLocation EnumLoc,
12531                                            SourceLocation NameLoc,
12532                                            EnumDecl *ED) {
12533   bool Invalid = false;
12534 
12535   if (CurContext->getRedeclContext()->isRecord()) {
12536     /// In class scope, check if this is a duplicate, for better a diagnostic.
12537     DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12538     LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12539                           ForVisibleRedeclaration);
12540 
12541     LookupName(Previous, S);
12542 
12543     for (NamedDecl *D : Previous)
12544       if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12545         if (UED->getEnumDecl() == ED) {
12546           Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12547               << SourceRange(EnumLoc, NameLoc);
12548           Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12549           Invalid = true;
12550           break;
12551         }
12552   }
12553 
12554   if (RequireCompleteEnumDecl(ED, NameLoc))
12555     Invalid = true;
12556 
12557   UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12558                                             EnumLoc, NameLoc, ED);
12559   UD->setAccess(AS);
12560   CurContext->addDecl(UD);
12561 
12562   if (Invalid) {
12563     UD->setInvalidDecl();
12564     return UD;
12565   }
12566 
12567   // Create the shadow decls for each enumerator
12568   for (EnumConstantDecl *EC : ED->enumerators()) {
12569     UsingShadowDecl *PrevDecl = nullptr;
12570     DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12571     LookupResult Previous(*this, DNI, LookupOrdinaryName,
12572                           ForVisibleRedeclaration);
12573     LookupName(Previous, S);
12574     FilterUsingLookup(S, Previous);
12575 
12576     if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12577       BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12578   }
12579 
12580   return UD;
12581 }
12582 
12583 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12584                                     ArrayRef<NamedDecl *> Expansions) {
12585   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12586          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12587          isa<UsingPackDecl>(InstantiatedFrom));
12588 
12589   auto *UPD =
12590       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12591   UPD->setAccess(InstantiatedFrom->getAccess());
12592   CurContext->addDecl(UPD);
12593   return UPD;
12594 }
12595 
12596 /// Additional checks for a using declaration referring to a constructor name.
12597 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12598   assert(!UD->hasTypename() && "expecting a constructor name");
12599 
12600   const Type *SourceType = UD->getQualifier()->getAsType();
12601   assert(SourceType &&
12602          "Using decl naming constructor doesn't have type in scope spec.");
12603   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12604 
12605   // Check whether the named type is a direct base class.
12606   bool AnyDependentBases = false;
12607   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12608                                       AnyDependentBases);
12609   if (!Base && !AnyDependentBases) {
12610     Diag(UD->getUsingLoc(),
12611          diag::err_using_decl_constructor_not_in_direct_base)
12612       << UD->getNameInfo().getSourceRange()
12613       << QualType(SourceType, 0) << TargetClass;
12614     UD->setInvalidDecl();
12615     return true;
12616   }
12617 
12618   if (Base)
12619     Base->setInheritConstructors();
12620 
12621   return false;
12622 }
12623 
12624 /// Checks that the given using declaration is not an invalid
12625 /// redeclaration.  Note that this is checking only for the using decl
12626 /// itself, not for any ill-formedness among the UsingShadowDecls.
12627 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12628                                        bool HasTypenameKeyword,
12629                                        const CXXScopeSpec &SS,
12630                                        SourceLocation NameLoc,
12631                                        const LookupResult &Prev) {
12632   NestedNameSpecifier *Qual = SS.getScopeRep();
12633 
12634   // C++03 [namespace.udecl]p8:
12635   // C++0x [namespace.udecl]p10:
12636   //   A using-declaration is a declaration and can therefore be used
12637   //   repeatedly where (and only where) multiple declarations are
12638   //   allowed.
12639   //
12640   // That's in non-member contexts.
12641   if (!CurContext->getRedeclContext()->isRecord()) {
12642     // A dependent qualifier outside a class can only ever resolve to an
12643     // enumeration type. Therefore it conflicts with any other non-type
12644     // declaration in the same scope.
12645     // FIXME: How should we check for dependent type-type conflicts at block
12646     // scope?
12647     if (Qual->isDependent() && !HasTypenameKeyword) {
12648       for (auto *D : Prev) {
12649         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12650           bool OldCouldBeEnumerator =
12651               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12652           Diag(NameLoc,
12653                OldCouldBeEnumerator ? diag::err_redefinition
12654                                     : diag::err_redefinition_different_kind)
12655               << Prev.getLookupName();
12656           Diag(D->getLocation(), diag::note_previous_definition);
12657           return true;
12658         }
12659       }
12660     }
12661     return false;
12662   }
12663 
12664   const NestedNameSpecifier *CNNS =
12665       Context.getCanonicalNestedNameSpecifier(Qual);
12666   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12667     NamedDecl *D = *I;
12668 
12669     bool DTypename;
12670     NestedNameSpecifier *DQual;
12671     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12672       DTypename = UD->hasTypename();
12673       DQual = UD->getQualifier();
12674     } else if (UnresolvedUsingValueDecl *UD
12675                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12676       DTypename = false;
12677       DQual = UD->getQualifier();
12678     } else if (UnresolvedUsingTypenameDecl *UD
12679                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12680       DTypename = true;
12681       DQual = UD->getQualifier();
12682     } else continue;
12683 
12684     // using decls differ if one says 'typename' and the other doesn't.
12685     // FIXME: non-dependent using decls?
12686     if (HasTypenameKeyword != DTypename) continue;
12687 
12688     // using decls differ if they name different scopes (but note that
12689     // template instantiation can cause this check to trigger when it
12690     // didn't before instantiation).
12691     if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12692       continue;
12693 
12694     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12695     Diag(D->getLocation(), diag::note_using_decl) << 1;
12696     return true;
12697   }
12698 
12699   return false;
12700 }
12701 
12702 /// Checks that the given nested-name qualifier used in a using decl
12703 /// in the current context is appropriately related to the current
12704 /// scope.  If an error is found, diagnoses it and returns true.
12705 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12706 /// result of that lookup. UD is likewise nullptr, except when we have an
12707 /// already-populated UsingDecl whose shadow decls contain the same information
12708 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12709 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12710                                    const CXXScopeSpec &SS,
12711                                    const DeclarationNameInfo &NameInfo,
12712                                    SourceLocation NameLoc,
12713                                    const LookupResult *R, const UsingDecl *UD) {
12714   DeclContext *NamedContext = computeDeclContext(SS);
12715   assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
12716          "resolvable context must have exactly one set of decls");
12717 
12718   // C++ 20 permits using an enumerator that does not have a class-hierarchy
12719   // relationship.
12720   bool Cxx20Enumerator = false;
12721   if (NamedContext) {
12722     EnumConstantDecl *EC = nullptr;
12723     if (R)
12724       EC = R->getAsSingle<EnumConstantDecl>();
12725     else if (UD && UD->shadow_size() == 1)
12726       EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12727     if (EC)
12728       Cxx20Enumerator = getLangOpts().CPlusPlus20;
12729 
12730     if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12731       // C++14 [namespace.udecl]p7:
12732       // A using-declaration shall not name a scoped enumerator.
12733       // C++20 p1099 permits enumerators.
12734       if (EC && R && ED->isScoped())
12735         Diag(SS.getBeginLoc(),
12736              getLangOpts().CPlusPlus20
12737                  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12738                  : diag::ext_using_decl_scoped_enumerator)
12739             << SS.getRange();
12740 
12741       // We want to consider the scope of the enumerator
12742       NamedContext = ED->getDeclContext();
12743     }
12744   }
12745 
12746   if (!CurContext->isRecord()) {
12747     // C++03 [namespace.udecl]p3:
12748     // C++0x [namespace.udecl]p8:
12749     //   A using-declaration for a class member shall be a member-declaration.
12750     // C++20 [namespace.udecl]p7
12751     //   ... other than an enumerator ...
12752 
12753     // If we weren't able to compute a valid scope, it might validly be a
12754     // dependent class or enumeration scope. If we have a 'typename' keyword,
12755     // the scope must resolve to a class type.
12756     if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12757                      : !HasTypename)
12758       return false; // OK
12759 
12760     Diag(NameLoc,
12761          Cxx20Enumerator
12762              ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12763              : diag::err_using_decl_can_not_refer_to_class_member)
12764         << SS.getRange();
12765 
12766     if (Cxx20Enumerator)
12767       return false; // OK
12768 
12769     auto *RD = NamedContext
12770                    ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12771                    : nullptr;
12772     if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12773       // See if there's a helpful fixit
12774 
12775       if (!R) {
12776         // We will have already diagnosed the problem on the template
12777         // definition,  Maybe we should do so again?
12778       } else if (R->getAsSingle<TypeDecl>()) {
12779         if (getLangOpts().CPlusPlus11) {
12780           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12781           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12782             << 0 // alias declaration
12783             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12784                                           NameInfo.getName().getAsString() +
12785                                               " = ");
12786         } else {
12787           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12788           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12789           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12790             << 1 // typedef declaration
12791             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12792             << FixItHint::CreateInsertion(
12793                    InsertLoc, " " + NameInfo.getName().getAsString());
12794         }
12795       } else if (R->getAsSingle<VarDecl>()) {
12796         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12797         // repeating the type of the static data member here.
12798         FixItHint FixIt;
12799         if (getLangOpts().CPlusPlus11) {
12800           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12801           FixIt = FixItHint::CreateReplacement(
12802               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12803         }
12804 
12805         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12806           << 2 // reference declaration
12807           << FixIt;
12808       } else if (R->getAsSingle<EnumConstantDecl>()) {
12809         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12810         // repeating the type of the enumeration here, and we can't do so if
12811         // the type is anonymous.
12812         FixItHint FixIt;
12813         if (getLangOpts().CPlusPlus11) {
12814           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12815           FixIt = FixItHint::CreateReplacement(
12816               UsingLoc,
12817               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12818         }
12819 
12820         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12821           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12822           << FixIt;
12823       }
12824     }
12825 
12826     return true; // Fail
12827   }
12828 
12829   // If the named context is dependent, we can't decide much.
12830   if (!NamedContext) {
12831     // FIXME: in C++0x, we can diagnose if we can prove that the
12832     // nested-name-specifier does not refer to a base class, which is
12833     // still possible in some cases.
12834 
12835     // Otherwise we have to conservatively report that things might be
12836     // okay.
12837     return false;
12838   }
12839 
12840   // The current scope is a record.
12841   if (!NamedContext->isRecord()) {
12842     // Ideally this would point at the last name in the specifier,
12843     // but we don't have that level of source info.
12844     Diag(SS.getBeginLoc(),
12845          Cxx20Enumerator
12846              ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12847              : diag::err_using_decl_nested_name_specifier_is_not_class)
12848         << SS.getScopeRep() << SS.getRange();
12849 
12850     if (Cxx20Enumerator)
12851       return false; // OK
12852 
12853     return true;
12854   }
12855 
12856   if (!NamedContext->isDependentContext() &&
12857       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12858     return true;
12859 
12860   if (getLangOpts().CPlusPlus11) {
12861     // C++11 [namespace.udecl]p3:
12862     //   In a using-declaration used as a member-declaration, the
12863     //   nested-name-specifier shall name a base class of the class
12864     //   being defined.
12865 
12866     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12867                                  cast<CXXRecordDecl>(NamedContext))) {
12868 
12869       if (Cxx20Enumerator) {
12870         Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12871             << SS.getRange();
12872         return false;
12873       }
12874 
12875       if (CurContext == NamedContext) {
12876         Diag(SS.getBeginLoc(),
12877              diag::err_using_decl_nested_name_specifier_is_current_class)
12878             << SS.getRange();
12879         return !getLangOpts().CPlusPlus20;
12880       }
12881 
12882       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12883         Diag(SS.getBeginLoc(),
12884              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12885             << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12886             << SS.getRange();
12887       }
12888       return true;
12889     }
12890 
12891     return false;
12892   }
12893 
12894   // C++03 [namespace.udecl]p4:
12895   //   A using-declaration used as a member-declaration shall refer
12896   //   to a member of a base class of the class being defined [etc.].
12897 
12898   // Salient point: SS doesn't have to name a base class as long as
12899   // lookup only finds members from base classes.  Therefore we can
12900   // diagnose here only if we can prove that that can't happen,
12901   // i.e. if the class hierarchies provably don't intersect.
12902 
12903   // TODO: it would be nice if "definitely valid" results were cached
12904   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12905   // need to be repeated.
12906 
12907   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12908   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12909     Bases.insert(Base);
12910     return true;
12911   };
12912 
12913   // Collect all bases. Return false if we find a dependent base.
12914   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12915     return false;
12916 
12917   // Returns true if the base is dependent or is one of the accumulated base
12918   // classes.
12919   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12920     return !Bases.count(Base);
12921   };
12922 
12923   // Return false if the class has a dependent base or if it or one
12924   // of its bases is present in the base set of the current context.
12925   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12926       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12927     return false;
12928 
12929   Diag(SS.getRange().getBegin(),
12930        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12931     << SS.getScopeRep()
12932     << cast<CXXRecordDecl>(CurContext)
12933     << SS.getRange();
12934 
12935   return true;
12936 }
12937 
12938 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12939                                   MultiTemplateParamsArg TemplateParamLists,
12940                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12941                                   const ParsedAttributesView &AttrList,
12942                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12943   // Skip up to the relevant declaration scope.
12944   while (S->isTemplateParamScope())
12945     S = S->getParent();
12946   assert((S->getFlags() & Scope::DeclScope) &&
12947          "got alias-declaration outside of declaration scope");
12948 
12949   if (Type.isInvalid())
12950     return nullptr;
12951 
12952   bool Invalid = false;
12953   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12954   TypeSourceInfo *TInfo = nullptr;
12955   GetTypeFromParser(Type.get(), &TInfo);
12956 
12957   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12958     return nullptr;
12959 
12960   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12961                                       UPPC_DeclarationType)) {
12962     Invalid = true;
12963     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12964                                              TInfo->getTypeLoc().getBeginLoc());
12965   }
12966 
12967   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12968                         TemplateParamLists.size()
12969                             ? forRedeclarationInCurContext()
12970                             : ForVisibleRedeclaration);
12971   LookupName(Previous, S);
12972 
12973   // Warn about shadowing the name of a template parameter.
12974   if (Previous.isSingleResult() &&
12975       Previous.getFoundDecl()->isTemplateParameter()) {
12976     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12977     Previous.clear();
12978   }
12979 
12980   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12981          "name in alias declaration must be an identifier");
12982   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12983                                                Name.StartLocation,
12984                                                Name.Identifier, TInfo);
12985 
12986   NewTD->setAccess(AS);
12987 
12988   if (Invalid)
12989     NewTD->setInvalidDecl();
12990 
12991   ProcessDeclAttributeList(S, NewTD, AttrList);
12992   AddPragmaAttributes(S, NewTD);
12993 
12994   CheckTypedefForVariablyModifiedType(S, NewTD);
12995   Invalid |= NewTD->isInvalidDecl();
12996 
12997   bool Redeclaration = false;
12998 
12999   NamedDecl *NewND;
13000   if (TemplateParamLists.size()) {
13001     TypeAliasTemplateDecl *OldDecl = nullptr;
13002     TemplateParameterList *OldTemplateParams = nullptr;
13003 
13004     if (TemplateParamLists.size() != 1) {
13005       Diag(UsingLoc, diag::err_alias_template_extra_headers)
13006         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13007          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13008     }
13009     TemplateParameterList *TemplateParams = TemplateParamLists[0];
13010 
13011     // Check that we can declare a template here.
13012     if (CheckTemplateDeclScope(S, TemplateParams))
13013       return nullptr;
13014 
13015     // Only consider previous declarations in the same scope.
13016     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13017                          /*ExplicitInstantiationOrSpecialization*/false);
13018     if (!Previous.empty()) {
13019       Redeclaration = true;
13020 
13021       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13022       if (!OldDecl && !Invalid) {
13023         Diag(UsingLoc, diag::err_redefinition_different_kind)
13024           << Name.Identifier;
13025 
13026         NamedDecl *OldD = Previous.getRepresentativeDecl();
13027         if (OldD->getLocation().isValid())
13028           Diag(OldD->getLocation(), diag::note_previous_definition);
13029 
13030         Invalid = true;
13031       }
13032 
13033       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13034         if (TemplateParameterListsAreEqual(TemplateParams,
13035                                            OldDecl->getTemplateParameters(),
13036                                            /*Complain=*/true,
13037                                            TPL_TemplateMatch))
13038           OldTemplateParams =
13039               OldDecl->getMostRecentDecl()->getTemplateParameters();
13040         else
13041           Invalid = true;
13042 
13043         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13044         if (!Invalid &&
13045             !Context.hasSameType(OldTD->getUnderlyingType(),
13046                                  NewTD->getUnderlyingType())) {
13047           // FIXME: The C++0x standard does not clearly say this is ill-formed,
13048           // but we can't reasonably accept it.
13049           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13050             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13051           if (OldTD->getLocation().isValid())
13052             Diag(OldTD->getLocation(), diag::note_previous_definition);
13053           Invalid = true;
13054         }
13055       }
13056     }
13057 
13058     // Merge any previous default template arguments into our parameters,
13059     // and check the parameter list.
13060     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13061                                    TPC_TypeAliasTemplate))
13062       return nullptr;
13063 
13064     TypeAliasTemplateDecl *NewDecl =
13065       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13066                                     Name.Identifier, TemplateParams,
13067                                     NewTD);
13068     NewTD->setDescribedAliasTemplate(NewDecl);
13069 
13070     NewDecl->setAccess(AS);
13071 
13072     if (Invalid)
13073       NewDecl->setInvalidDecl();
13074     else if (OldDecl) {
13075       NewDecl->setPreviousDecl(OldDecl);
13076       CheckRedeclarationInModule(NewDecl, OldDecl);
13077     }
13078 
13079     NewND = NewDecl;
13080   } else {
13081     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13082       setTagNameForLinkagePurposes(TD, NewTD);
13083       handleTagNumbering(TD, S);
13084     }
13085     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13086     NewND = NewTD;
13087   }
13088 
13089   PushOnScopeChains(NewND, S);
13090   ActOnDocumentableDecl(NewND);
13091   return NewND;
13092 }
13093 
13094 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13095                                    SourceLocation AliasLoc,
13096                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
13097                                    SourceLocation IdentLoc,
13098                                    IdentifierInfo *Ident) {
13099 
13100   // Lookup the namespace name.
13101   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13102   LookupParsedName(R, S, &SS);
13103 
13104   if (R.isAmbiguous())
13105     return nullptr;
13106 
13107   if (R.empty()) {
13108     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13109       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13110       return nullptr;
13111     }
13112   }
13113   assert(!R.isAmbiguous() && !R.empty());
13114   NamedDecl *ND = R.getRepresentativeDecl();
13115 
13116   // Check if we have a previous declaration with the same name.
13117   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13118                      ForVisibleRedeclaration);
13119   LookupName(PrevR, S);
13120 
13121   // Check we're not shadowing a template parameter.
13122   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13123     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13124     PrevR.clear();
13125   }
13126 
13127   // Filter out any other lookup result from an enclosing scope.
13128   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13129                        /*AllowInlineNamespace*/false);
13130 
13131   // Find the previous declaration and check that we can redeclare it.
13132   NamespaceAliasDecl *Prev = nullptr;
13133   if (PrevR.isSingleResult()) {
13134     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13135     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13136       // We already have an alias with the same name that points to the same
13137       // namespace; check that it matches.
13138       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13139         Prev = AD;
13140       } else if (isVisible(PrevDecl)) {
13141         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13142           << Alias;
13143         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13144           << AD->getNamespace();
13145         return nullptr;
13146       }
13147     } else if (isVisible(PrevDecl)) {
13148       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13149                             ? diag::err_redefinition
13150                             : diag::err_redefinition_different_kind;
13151       Diag(AliasLoc, DiagID) << Alias;
13152       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13153       return nullptr;
13154     }
13155   }
13156 
13157   // The use of a nested name specifier may trigger deprecation warnings.
13158   DiagnoseUseOfDecl(ND, IdentLoc);
13159 
13160   NamespaceAliasDecl *AliasDecl =
13161     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13162                                Alias, SS.getWithLocInContext(Context),
13163                                IdentLoc, ND);
13164   if (Prev)
13165     AliasDecl->setPreviousDecl(Prev);
13166 
13167   PushOnScopeChains(AliasDecl, S);
13168   return AliasDecl;
13169 }
13170 
13171 namespace {
13172 struct SpecialMemberExceptionSpecInfo
13173     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13174   SourceLocation Loc;
13175   Sema::ImplicitExceptionSpecification ExceptSpec;
13176 
13177   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13178                                  Sema::CXXSpecialMember CSM,
13179                                  Sema::InheritedConstructorInfo *ICI,
13180                                  SourceLocation Loc)
13181       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13182 
13183   bool visitBase(CXXBaseSpecifier *Base);
13184   bool visitField(FieldDecl *FD);
13185 
13186   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13187                            unsigned Quals);
13188 
13189   void visitSubobjectCall(Subobject Subobj,
13190                           Sema::SpecialMemberOverloadResult SMOR);
13191 };
13192 }
13193 
13194 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13195   auto *RT = Base->getType()->getAs<RecordType>();
13196   if (!RT)
13197     return false;
13198 
13199   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13200   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13201   if (auto *BaseCtor = SMOR.getMethod()) {
13202     visitSubobjectCall(Base, BaseCtor);
13203     return false;
13204   }
13205 
13206   visitClassSubobject(BaseClass, Base, 0);
13207   return false;
13208 }
13209 
13210 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13211   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13212     Expr *E = FD->getInClassInitializer();
13213     if (!E)
13214       // FIXME: It's a little wasteful to build and throw away a
13215       // CXXDefaultInitExpr here.
13216       // FIXME: We should have a single context note pointing at Loc, and
13217       // this location should be MD->getLocation() instead, since that's
13218       // the location where we actually use the default init expression.
13219       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13220     if (E)
13221       ExceptSpec.CalledExpr(E);
13222   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13223                             ->getAs<RecordType>()) {
13224     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13225                         FD->getType().getCVRQualifiers());
13226   }
13227   return false;
13228 }
13229 
13230 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13231                                                          Subobject Subobj,
13232                                                          unsigned Quals) {
13233   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13234   bool IsMutable = Field && Field->isMutable();
13235   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13236 }
13237 
13238 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13239     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13240   // Note, if lookup fails, it doesn't matter what exception specification we
13241   // choose because the special member will be deleted.
13242   if (CXXMethodDecl *MD = SMOR.getMethod())
13243     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13244 }
13245 
13246 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13247   llvm::APSInt Result;
13248   ExprResult Converted = CheckConvertedConstantExpression(
13249       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13250   ExplicitSpec.setExpr(Converted.get());
13251   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13252     ExplicitSpec.setKind(Result.getBoolValue()
13253                              ? ExplicitSpecKind::ResolvedTrue
13254                              : ExplicitSpecKind::ResolvedFalse);
13255     return true;
13256   }
13257   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13258   return false;
13259 }
13260 
13261 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13262   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13263   if (!ExplicitExpr->isTypeDependent())
13264     tryResolveExplicitSpecifier(ES);
13265   return ES;
13266 }
13267 
13268 static Sema::ImplicitExceptionSpecification
13269 ComputeDefaultedSpecialMemberExceptionSpec(
13270     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13271     Sema::InheritedConstructorInfo *ICI) {
13272   ComputingExceptionSpec CES(S, MD, Loc);
13273 
13274   CXXRecordDecl *ClassDecl = MD->getParent();
13275 
13276   // C++ [except.spec]p14:
13277   //   An implicitly declared special member function (Clause 12) shall have an
13278   //   exception-specification. [...]
13279   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13280   if (ClassDecl->isInvalidDecl())
13281     return Info.ExceptSpec;
13282 
13283   // FIXME: If this diagnostic fires, we're probably missing a check for
13284   // attempting to resolve an exception specification before it's known
13285   // at a higher level.
13286   if (S.RequireCompleteType(MD->getLocation(),
13287                             S.Context.getRecordType(ClassDecl),
13288                             diag::err_exception_spec_incomplete_type))
13289     return Info.ExceptSpec;
13290 
13291   // C++1z [except.spec]p7:
13292   //   [Look for exceptions thrown by] a constructor selected [...] to
13293   //   initialize a potentially constructed subobject,
13294   // C++1z [except.spec]p8:
13295   //   The exception specification for an implicitly-declared destructor, or a
13296   //   destructor without a noexcept-specifier, is potentially-throwing if and
13297   //   only if any of the destructors for any of its potentially constructed
13298   //   subojects is potentially throwing.
13299   // FIXME: We respect the first rule but ignore the "potentially constructed"
13300   // in the second rule to resolve a core issue (no number yet) that would have
13301   // us reject:
13302   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13303   //   struct B : A {};
13304   //   struct C : B { void f(); };
13305   // ... due to giving B::~B() a non-throwing exception specification.
13306   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13307                                 : Info.VisitAllBases);
13308 
13309   return Info.ExceptSpec;
13310 }
13311 
13312 namespace {
13313 /// RAII object to register a special member as being currently declared.
13314 struct DeclaringSpecialMember {
13315   Sema &S;
13316   Sema::SpecialMemberDecl D;
13317   Sema::ContextRAII SavedContext;
13318   bool WasAlreadyBeingDeclared;
13319 
13320   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13321       : S(S), D(RD, CSM), SavedContext(S, RD) {
13322     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13323     if (WasAlreadyBeingDeclared)
13324       // This almost never happens, but if it does, ensure that our cache
13325       // doesn't contain a stale result.
13326       S.SpecialMemberCache.clear();
13327     else {
13328       // Register a note to be produced if we encounter an error while
13329       // declaring the special member.
13330       Sema::CodeSynthesisContext Ctx;
13331       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13332       // FIXME: We don't have a location to use here. Using the class's
13333       // location maintains the fiction that we declare all special members
13334       // with the class, but (1) it's not clear that lying about that helps our
13335       // users understand what's going on, and (2) there may be outer contexts
13336       // on the stack (some of which are relevant) and printing them exposes
13337       // our lies.
13338       Ctx.PointOfInstantiation = RD->getLocation();
13339       Ctx.Entity = RD;
13340       Ctx.SpecialMember = CSM;
13341       S.pushCodeSynthesisContext(Ctx);
13342     }
13343   }
13344   ~DeclaringSpecialMember() {
13345     if (!WasAlreadyBeingDeclared) {
13346       S.SpecialMembersBeingDeclared.erase(D);
13347       S.popCodeSynthesisContext();
13348     }
13349   }
13350 
13351   /// Are we already trying to declare this special member?
13352   bool isAlreadyBeingDeclared() const {
13353     return WasAlreadyBeingDeclared;
13354   }
13355 };
13356 }
13357 
13358 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13359   // Look up any existing declarations, but don't trigger declaration of all
13360   // implicit special members with this name.
13361   DeclarationName Name = FD->getDeclName();
13362   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13363                  ForExternalRedeclaration);
13364   for (auto *D : FD->getParent()->lookup(Name))
13365     if (auto *Acceptable = R.getAcceptableDecl(D))
13366       R.addDecl(Acceptable);
13367   R.resolveKind();
13368   R.suppressDiagnostics();
13369 
13370   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13371                            FD->isThisDeclarationADefinition());
13372 }
13373 
13374 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13375                                           QualType ResultTy,
13376                                           ArrayRef<QualType> Args) {
13377   // Build an exception specification pointing back at this constructor.
13378   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13379 
13380   LangAS AS = getDefaultCXXMethodAddrSpace();
13381   if (AS != LangAS::Default) {
13382     EPI.TypeQuals.addAddressSpace(AS);
13383   }
13384 
13385   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13386   SpecialMem->setType(QT);
13387 
13388   // During template instantiation of implicit special member functions we need
13389   // a reliable TypeSourceInfo for the function prototype in order to allow
13390   // functions to be substituted.
13391   if (inTemplateInstantiation() &&
13392       cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13393     TypeSourceInfo *TSI =
13394         Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13395     SpecialMem->setTypeSourceInfo(TSI);
13396   }
13397 }
13398 
13399 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13400                                                      CXXRecordDecl *ClassDecl) {
13401   // C++ [class.ctor]p5:
13402   //   A default constructor for a class X is a constructor of class X
13403   //   that can be called without an argument. If there is no
13404   //   user-declared constructor for class X, a default constructor is
13405   //   implicitly declared. An implicitly-declared default constructor
13406   //   is an inline public member of its class.
13407   assert(ClassDecl->needsImplicitDefaultConstructor() &&
13408          "Should not build implicit default constructor!");
13409 
13410   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13411   if (DSM.isAlreadyBeingDeclared())
13412     return nullptr;
13413 
13414   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13415                                                      CXXDefaultConstructor,
13416                                                      false);
13417 
13418   // Create the actual constructor declaration.
13419   CanQualType ClassType
13420     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13421   SourceLocation ClassLoc = ClassDecl->getLocation();
13422   DeclarationName Name
13423     = Context.DeclarationNames.getCXXConstructorName(ClassType);
13424   DeclarationNameInfo NameInfo(Name, ClassLoc);
13425   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13426       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13427       /*TInfo=*/nullptr, ExplicitSpecifier(),
13428       getCurFPFeatures().isFPConstrained(),
13429       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13430       Constexpr ? ConstexprSpecKind::Constexpr
13431                 : ConstexprSpecKind::Unspecified);
13432   DefaultCon->setAccess(AS_public);
13433   DefaultCon->setDefaulted();
13434 
13435   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13436 
13437   if (getLangOpts().CUDA)
13438     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13439                                             DefaultCon,
13440                                             /* ConstRHS */ false,
13441                                             /* Diagnose */ false);
13442 
13443   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13444   // constructors is easy to compute.
13445   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13446 
13447   // Note that we have declared this constructor.
13448   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13449 
13450   Scope *S = getScopeForContext(ClassDecl);
13451   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13452 
13453   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13454     SetDeclDeleted(DefaultCon, ClassLoc);
13455 
13456   if (S)
13457     PushOnScopeChains(DefaultCon, S, false);
13458   ClassDecl->addDecl(DefaultCon);
13459 
13460   return DefaultCon;
13461 }
13462 
13463 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13464                                             CXXConstructorDecl *Constructor) {
13465   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13466           !Constructor->doesThisDeclarationHaveABody() &&
13467           !Constructor->isDeleted()) &&
13468     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13469   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13470     return;
13471 
13472   CXXRecordDecl *ClassDecl = Constructor->getParent();
13473   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13474 
13475   SynthesizedFunctionScope Scope(*this, Constructor);
13476 
13477   // The exception specification is needed because we are defining the
13478   // function.
13479   ResolveExceptionSpec(CurrentLocation,
13480                        Constructor->getType()->castAs<FunctionProtoType>());
13481   MarkVTableUsed(CurrentLocation, ClassDecl);
13482 
13483   // Add a context note for diagnostics produced after this point.
13484   Scope.addContextNote(CurrentLocation);
13485 
13486   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13487     Constructor->setInvalidDecl();
13488     return;
13489   }
13490 
13491   SourceLocation Loc = Constructor->getEndLoc().isValid()
13492                            ? Constructor->getEndLoc()
13493                            : Constructor->getLocation();
13494   Constructor->setBody(new (Context) CompoundStmt(Loc));
13495   Constructor->markUsed(Context);
13496 
13497   if (ASTMutationListener *L = getASTMutationListener()) {
13498     L->CompletedImplicitDefinition(Constructor);
13499   }
13500 
13501   DiagnoseUninitializedFields(*this, Constructor);
13502 }
13503 
13504 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13505   // Perform any delayed checks on exception specifications.
13506   CheckDelayedMemberExceptionSpecs();
13507 }
13508 
13509 /// Find or create the fake constructor we synthesize to model constructing an
13510 /// object of a derived class via a constructor of a base class.
13511 CXXConstructorDecl *
13512 Sema::findInheritingConstructor(SourceLocation Loc,
13513                                 CXXConstructorDecl *BaseCtor,
13514                                 ConstructorUsingShadowDecl *Shadow) {
13515   CXXRecordDecl *Derived = Shadow->getParent();
13516   SourceLocation UsingLoc = Shadow->getLocation();
13517 
13518   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13519   // For now we use the name of the base class constructor as a member of the
13520   // derived class to indicate a (fake) inherited constructor name.
13521   DeclarationName Name = BaseCtor->getDeclName();
13522 
13523   // Check to see if we already have a fake constructor for this inherited
13524   // constructor call.
13525   for (NamedDecl *Ctor : Derived->lookup(Name))
13526     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13527                                ->getInheritedConstructor()
13528                                .getConstructor(),
13529                            BaseCtor))
13530       return cast<CXXConstructorDecl>(Ctor);
13531 
13532   DeclarationNameInfo NameInfo(Name, UsingLoc);
13533   TypeSourceInfo *TInfo =
13534       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13535   FunctionProtoTypeLoc ProtoLoc =
13536       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13537 
13538   // Check the inherited constructor is valid and find the list of base classes
13539   // from which it was inherited.
13540   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13541 
13542   bool Constexpr =
13543       BaseCtor->isConstexpr() &&
13544       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13545                                         false, BaseCtor, &ICI);
13546 
13547   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13548       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13549       BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13550       /*isInline=*/true,
13551       /*isImplicitlyDeclared=*/true,
13552       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13553       InheritedConstructor(Shadow, BaseCtor),
13554       BaseCtor->getTrailingRequiresClause());
13555   if (Shadow->isInvalidDecl())
13556     DerivedCtor->setInvalidDecl();
13557 
13558   // Build an unevaluated exception specification for this fake constructor.
13559   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13560   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13561   EPI.ExceptionSpec.Type = EST_Unevaluated;
13562   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13563   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13564                                                FPT->getParamTypes(), EPI));
13565 
13566   // Build the parameter declarations.
13567   SmallVector<ParmVarDecl *, 16> ParamDecls;
13568   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13569     TypeSourceInfo *TInfo =
13570         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13571     ParmVarDecl *PD = ParmVarDecl::Create(
13572         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13573         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13574     PD->setScopeInfo(0, I);
13575     PD->setImplicit();
13576     // Ensure attributes are propagated onto parameters (this matters for
13577     // format, pass_object_size, ...).
13578     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13579     ParamDecls.push_back(PD);
13580     ProtoLoc.setParam(I, PD);
13581   }
13582 
13583   // Set up the new constructor.
13584   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13585   DerivedCtor->setAccess(BaseCtor->getAccess());
13586   DerivedCtor->setParams(ParamDecls);
13587   Derived->addDecl(DerivedCtor);
13588 
13589   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13590     SetDeclDeleted(DerivedCtor, UsingLoc);
13591 
13592   return DerivedCtor;
13593 }
13594 
13595 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13596   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13597                                Ctor->getInheritedConstructor().getShadowDecl());
13598   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13599                             /*Diagnose*/true);
13600 }
13601 
13602 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13603                                        CXXConstructorDecl *Constructor) {
13604   CXXRecordDecl *ClassDecl = Constructor->getParent();
13605   assert(Constructor->getInheritedConstructor() &&
13606          !Constructor->doesThisDeclarationHaveABody() &&
13607          !Constructor->isDeleted());
13608   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13609     return;
13610 
13611   // Initializations are performed "as if by a defaulted default constructor",
13612   // so enter the appropriate scope.
13613   SynthesizedFunctionScope Scope(*this, Constructor);
13614 
13615   // The exception specification is needed because we are defining the
13616   // function.
13617   ResolveExceptionSpec(CurrentLocation,
13618                        Constructor->getType()->castAs<FunctionProtoType>());
13619   MarkVTableUsed(CurrentLocation, ClassDecl);
13620 
13621   // Add a context note for diagnostics produced after this point.
13622   Scope.addContextNote(CurrentLocation);
13623 
13624   ConstructorUsingShadowDecl *Shadow =
13625       Constructor->getInheritedConstructor().getShadowDecl();
13626   CXXConstructorDecl *InheritedCtor =
13627       Constructor->getInheritedConstructor().getConstructor();
13628 
13629   // [class.inhctor.init]p1:
13630   //   initialization proceeds as if a defaulted default constructor is used to
13631   //   initialize the D object and each base class subobject from which the
13632   //   constructor was inherited
13633 
13634   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13635   CXXRecordDecl *RD = Shadow->getParent();
13636   SourceLocation InitLoc = Shadow->getLocation();
13637 
13638   // Build explicit initializers for all base classes from which the
13639   // constructor was inherited.
13640   SmallVector<CXXCtorInitializer*, 8> Inits;
13641   for (bool VBase : {false, true}) {
13642     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13643       if (B.isVirtual() != VBase)
13644         continue;
13645 
13646       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13647       if (!BaseRD)
13648         continue;
13649 
13650       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13651       if (!BaseCtor.first)
13652         continue;
13653 
13654       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13655       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13656           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13657 
13658       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13659       Inits.push_back(new (Context) CXXCtorInitializer(
13660           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13661           SourceLocation()));
13662     }
13663   }
13664 
13665   // We now proceed as if for a defaulted default constructor, with the relevant
13666   // initializers replaced.
13667 
13668   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13669     Constructor->setInvalidDecl();
13670     return;
13671   }
13672 
13673   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13674   Constructor->markUsed(Context);
13675 
13676   if (ASTMutationListener *L = getASTMutationListener()) {
13677     L->CompletedImplicitDefinition(Constructor);
13678   }
13679 
13680   DiagnoseUninitializedFields(*this, Constructor);
13681 }
13682 
13683 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13684   // C++ [class.dtor]p2:
13685   //   If a class has no user-declared destructor, a destructor is
13686   //   declared implicitly. An implicitly-declared destructor is an
13687   //   inline public member of its class.
13688   assert(ClassDecl->needsImplicitDestructor());
13689 
13690   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13691   if (DSM.isAlreadyBeingDeclared())
13692     return nullptr;
13693 
13694   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13695                                                      CXXDestructor,
13696                                                      false);
13697 
13698   // Create the actual destructor declaration.
13699   CanQualType ClassType
13700     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13701   SourceLocation ClassLoc = ClassDecl->getLocation();
13702   DeclarationName Name
13703     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13704   DeclarationNameInfo NameInfo(Name, ClassLoc);
13705   CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
13706       Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13707       getCurFPFeatures().isFPConstrained(),
13708       /*isInline=*/true,
13709       /*isImplicitlyDeclared=*/true,
13710       Constexpr ? ConstexprSpecKind::Constexpr
13711                 : ConstexprSpecKind::Unspecified);
13712   Destructor->setAccess(AS_public);
13713   Destructor->setDefaulted();
13714 
13715   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13716 
13717   if (getLangOpts().CUDA)
13718     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13719                                             Destructor,
13720                                             /* ConstRHS */ false,
13721                                             /* Diagnose */ false);
13722 
13723   // We don't need to use SpecialMemberIsTrivial here; triviality for
13724   // destructors is easy to compute.
13725   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13726   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13727                                 ClassDecl->hasTrivialDestructorForCall());
13728 
13729   // Note that we have declared this destructor.
13730   ++getASTContext().NumImplicitDestructorsDeclared;
13731 
13732   Scope *S = getScopeForContext(ClassDecl);
13733   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13734 
13735   // We can't check whether an implicit destructor is deleted before we complete
13736   // the definition of the class, because its validity depends on the alignment
13737   // of the class. We'll check this from ActOnFields once the class is complete.
13738   if (ClassDecl->isCompleteDefinition() &&
13739       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13740     SetDeclDeleted(Destructor, ClassLoc);
13741 
13742   // Introduce this destructor into its scope.
13743   if (S)
13744     PushOnScopeChains(Destructor, S, false);
13745   ClassDecl->addDecl(Destructor);
13746 
13747   return Destructor;
13748 }
13749 
13750 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13751                                     CXXDestructorDecl *Destructor) {
13752   assert((Destructor->isDefaulted() &&
13753           !Destructor->doesThisDeclarationHaveABody() &&
13754           !Destructor->isDeleted()) &&
13755          "DefineImplicitDestructor - call it for implicit default dtor");
13756   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13757     return;
13758 
13759   CXXRecordDecl *ClassDecl = Destructor->getParent();
13760   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13761 
13762   SynthesizedFunctionScope Scope(*this, Destructor);
13763 
13764   // The exception specification is needed because we are defining the
13765   // function.
13766   ResolveExceptionSpec(CurrentLocation,
13767                        Destructor->getType()->castAs<FunctionProtoType>());
13768   MarkVTableUsed(CurrentLocation, ClassDecl);
13769 
13770   // Add a context note for diagnostics produced after this point.
13771   Scope.addContextNote(CurrentLocation);
13772 
13773   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13774                                          Destructor->getParent());
13775 
13776   if (CheckDestructor(Destructor)) {
13777     Destructor->setInvalidDecl();
13778     return;
13779   }
13780 
13781   SourceLocation Loc = Destructor->getEndLoc().isValid()
13782                            ? Destructor->getEndLoc()
13783                            : Destructor->getLocation();
13784   Destructor->setBody(new (Context) CompoundStmt(Loc));
13785   Destructor->markUsed(Context);
13786 
13787   if (ASTMutationListener *L = getASTMutationListener()) {
13788     L->CompletedImplicitDefinition(Destructor);
13789   }
13790 }
13791 
13792 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13793                                           CXXDestructorDecl *Destructor) {
13794   if (Destructor->isInvalidDecl())
13795     return;
13796 
13797   CXXRecordDecl *ClassDecl = Destructor->getParent();
13798   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13799          "implicit complete dtors unneeded outside MS ABI");
13800   assert(ClassDecl->getNumVBases() > 0 &&
13801          "complete dtor only exists for classes with vbases");
13802 
13803   SynthesizedFunctionScope Scope(*this, Destructor);
13804 
13805   // Add a context note for diagnostics produced after this point.
13806   Scope.addContextNote(CurrentLocation);
13807 
13808   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13809 }
13810 
13811 /// Perform any semantic analysis which needs to be delayed until all
13812 /// pending class member declarations have been parsed.
13813 void Sema::ActOnFinishCXXMemberDecls() {
13814   // If the context is an invalid C++ class, just suppress these checks.
13815   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13816     if (Record->isInvalidDecl()) {
13817       DelayedOverridingExceptionSpecChecks.clear();
13818       DelayedEquivalentExceptionSpecChecks.clear();
13819       return;
13820     }
13821     checkForMultipleExportedDefaultConstructors(*this, Record);
13822   }
13823 }
13824 
13825 void Sema::ActOnFinishCXXNonNestedClass() {
13826   referenceDLLExportedClassMethods();
13827 
13828   if (!DelayedDllExportMemberFunctions.empty()) {
13829     SmallVector<CXXMethodDecl*, 4> WorkList;
13830     std::swap(DelayedDllExportMemberFunctions, WorkList);
13831     for (CXXMethodDecl *M : WorkList) {
13832       DefineDefaultedFunction(*this, M, M->getLocation());
13833 
13834       // Pass the method to the consumer to get emitted. This is not necessary
13835       // for explicit instantiation definitions, as they will get emitted
13836       // anyway.
13837       if (M->getParent()->getTemplateSpecializationKind() !=
13838           TSK_ExplicitInstantiationDefinition)
13839         ActOnFinishInlineFunctionDef(M);
13840     }
13841   }
13842 }
13843 
13844 void Sema::referenceDLLExportedClassMethods() {
13845   if (!DelayedDllExportClasses.empty()) {
13846     // Calling ReferenceDllExportedMembers might cause the current function to
13847     // be called again, so use a local copy of DelayedDllExportClasses.
13848     SmallVector<CXXRecordDecl *, 4> WorkList;
13849     std::swap(DelayedDllExportClasses, WorkList);
13850     for (CXXRecordDecl *Class : WorkList)
13851       ReferenceDllExportedMembers(*this, Class);
13852   }
13853 }
13854 
13855 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13856   assert(getLangOpts().CPlusPlus11 &&
13857          "adjusting dtor exception specs was introduced in c++11");
13858 
13859   if (Destructor->isDependentContext())
13860     return;
13861 
13862   // C++11 [class.dtor]p3:
13863   //   A declaration of a destructor that does not have an exception-
13864   //   specification is implicitly considered to have the same exception-
13865   //   specification as an implicit declaration.
13866   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13867   if (DtorType->hasExceptionSpec())
13868     return;
13869 
13870   // Replace the destructor's type, building off the existing one. Fortunately,
13871   // the only thing of interest in the destructor type is its extended info.
13872   // The return and arguments are fixed.
13873   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13874   EPI.ExceptionSpec.Type = EST_Unevaluated;
13875   EPI.ExceptionSpec.SourceDecl = Destructor;
13876   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13877 
13878   // FIXME: If the destructor has a body that could throw, and the newly created
13879   // spec doesn't allow exceptions, we should emit a warning, because this
13880   // change in behavior can break conforming C++03 programs at runtime.
13881   // However, we don't have a body or an exception specification yet, so it
13882   // needs to be done somewhere else.
13883 }
13884 
13885 namespace {
13886 /// An abstract base class for all helper classes used in building the
13887 //  copy/move operators. These classes serve as factory functions and help us
13888 //  avoid using the same Expr* in the AST twice.
13889 class ExprBuilder {
13890   ExprBuilder(const ExprBuilder&) = delete;
13891   ExprBuilder &operator=(const ExprBuilder&) = delete;
13892 
13893 protected:
13894   static Expr *assertNotNull(Expr *E) {
13895     assert(E && "Expression construction must not fail.");
13896     return E;
13897   }
13898 
13899 public:
13900   ExprBuilder() {}
13901   virtual ~ExprBuilder() {}
13902 
13903   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13904 };
13905 
13906 class RefBuilder: public ExprBuilder {
13907   VarDecl *Var;
13908   QualType VarType;
13909 
13910 public:
13911   Expr *build(Sema &S, SourceLocation Loc) const override {
13912     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13913   }
13914 
13915   RefBuilder(VarDecl *Var, QualType VarType)
13916       : Var(Var), VarType(VarType) {}
13917 };
13918 
13919 class ThisBuilder: public ExprBuilder {
13920 public:
13921   Expr *build(Sema &S, SourceLocation Loc) const override {
13922     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13923   }
13924 };
13925 
13926 class CastBuilder: public ExprBuilder {
13927   const ExprBuilder &Builder;
13928   QualType Type;
13929   ExprValueKind Kind;
13930   const CXXCastPath &Path;
13931 
13932 public:
13933   Expr *build(Sema &S, SourceLocation Loc) const override {
13934     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13935                                              CK_UncheckedDerivedToBase, Kind,
13936                                              &Path).get());
13937   }
13938 
13939   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13940               const CXXCastPath &Path)
13941       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13942 };
13943 
13944 class DerefBuilder: public ExprBuilder {
13945   const ExprBuilder &Builder;
13946 
13947 public:
13948   Expr *build(Sema &S, SourceLocation Loc) const override {
13949     return assertNotNull(
13950         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13951   }
13952 
13953   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13954 };
13955 
13956 class MemberBuilder: public ExprBuilder {
13957   const ExprBuilder &Builder;
13958   QualType Type;
13959   CXXScopeSpec SS;
13960   bool IsArrow;
13961   LookupResult &MemberLookup;
13962 
13963 public:
13964   Expr *build(Sema &S, SourceLocation Loc) const override {
13965     return assertNotNull(S.BuildMemberReferenceExpr(
13966         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13967         nullptr, MemberLookup, nullptr, nullptr).get());
13968   }
13969 
13970   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13971                 LookupResult &MemberLookup)
13972       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13973         MemberLookup(MemberLookup) {}
13974 };
13975 
13976 class MoveCastBuilder: public ExprBuilder {
13977   const ExprBuilder &Builder;
13978 
13979 public:
13980   Expr *build(Sema &S, SourceLocation Loc) const override {
13981     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13982   }
13983 
13984   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13985 };
13986 
13987 class LvalueConvBuilder: public ExprBuilder {
13988   const ExprBuilder &Builder;
13989 
13990 public:
13991   Expr *build(Sema &S, SourceLocation Loc) const override {
13992     return assertNotNull(
13993         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13994   }
13995 
13996   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13997 };
13998 
13999 class SubscriptBuilder: public ExprBuilder {
14000   const ExprBuilder &Base;
14001   const ExprBuilder &Index;
14002 
14003 public:
14004   Expr *build(Sema &S, SourceLocation Loc) const override {
14005     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14006         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14007   }
14008 
14009   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14010       : Base(Base), Index(Index) {}
14011 };
14012 
14013 } // end anonymous namespace
14014 
14015 /// When generating a defaulted copy or move assignment operator, if a field
14016 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14017 /// do so. This optimization only applies for arrays of scalars, and for arrays
14018 /// of class type where the selected copy/move-assignment operator is trivial.
14019 static StmtResult
14020 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14021                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
14022   // Compute the size of the memory buffer to be copied.
14023   QualType SizeType = S.Context.getSizeType();
14024   llvm::APInt Size(S.Context.getTypeSize(SizeType),
14025                    S.Context.getTypeSizeInChars(T).getQuantity());
14026 
14027   // Take the address of the field references for "from" and "to". We
14028   // directly construct UnaryOperators here because semantic analysis
14029   // does not permit us to take the address of an xvalue.
14030   Expr *From = FromB.build(S, Loc);
14031   From = UnaryOperator::Create(
14032       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14033       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14034   Expr *To = ToB.build(S, Loc);
14035   To = UnaryOperator::Create(
14036       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14037       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14038 
14039   const Type *E = T->getBaseElementTypeUnsafe();
14040   bool NeedsCollectableMemCpy =
14041       E->isRecordType() &&
14042       E->castAs<RecordType>()->getDecl()->hasObjectMember();
14043 
14044   // Create a reference to the __builtin_objc_memmove_collectable function
14045   StringRef MemCpyName = NeedsCollectableMemCpy ?
14046     "__builtin_objc_memmove_collectable" :
14047     "__builtin_memcpy";
14048   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14049                  Sema::LookupOrdinaryName);
14050   S.LookupName(R, S.TUScope, true);
14051 
14052   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14053   if (!MemCpy)
14054     // Something went horribly wrong earlier, and we will have complained
14055     // about it.
14056     return StmtError();
14057 
14058   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14059                                             VK_PRValue, Loc, nullptr);
14060   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14061 
14062   Expr *CallArgs[] = {
14063     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14064   };
14065   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14066                                     Loc, CallArgs, Loc);
14067 
14068   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14069   return Call.getAs<Stmt>();
14070 }
14071 
14072 /// Builds a statement that copies/moves the given entity from \p From to
14073 /// \c To.
14074 ///
14075 /// This routine is used to copy/move the members of a class with an
14076 /// implicitly-declared copy/move assignment operator. When the entities being
14077 /// copied are arrays, this routine builds for loops to copy them.
14078 ///
14079 /// \param S The Sema object used for type-checking.
14080 ///
14081 /// \param Loc The location where the implicit copy/move is being generated.
14082 ///
14083 /// \param T The type of the expressions being copied/moved. Both expressions
14084 /// must have this type.
14085 ///
14086 /// \param To The expression we are copying/moving to.
14087 ///
14088 /// \param From The expression we are copying/moving from.
14089 ///
14090 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14091 /// Otherwise, it's a non-static member subobject.
14092 ///
14093 /// \param Copying Whether we're copying or moving.
14094 ///
14095 /// \param Depth Internal parameter recording the depth of the recursion.
14096 ///
14097 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14098 /// if a memcpy should be used instead.
14099 static StmtResult
14100 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14101                                  const ExprBuilder &To, const ExprBuilder &From,
14102                                  bool CopyingBaseSubobject, bool Copying,
14103                                  unsigned Depth = 0) {
14104   // C++11 [class.copy]p28:
14105   //   Each subobject is assigned in the manner appropriate to its type:
14106   //
14107   //     - if the subobject is of class type, as if by a call to operator= with
14108   //       the subobject as the object expression and the corresponding
14109   //       subobject of x as a single function argument (as if by explicit
14110   //       qualification; that is, ignoring any possible virtual overriding
14111   //       functions in more derived classes);
14112   //
14113   // C++03 [class.copy]p13:
14114   //     - if the subobject is of class type, the copy assignment operator for
14115   //       the class is used (as if by explicit qualification; that is,
14116   //       ignoring any possible virtual overriding functions in more derived
14117   //       classes);
14118   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14119     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14120 
14121     // Look for operator=.
14122     DeclarationName Name
14123       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14124     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14125     S.LookupQualifiedName(OpLookup, ClassDecl, false);
14126 
14127     // Prior to C++11, filter out any result that isn't a copy/move-assignment
14128     // operator.
14129     if (!S.getLangOpts().CPlusPlus11) {
14130       LookupResult::Filter F = OpLookup.makeFilter();
14131       while (F.hasNext()) {
14132         NamedDecl *D = F.next();
14133         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14134           if (Method->isCopyAssignmentOperator() ||
14135               (!Copying && Method->isMoveAssignmentOperator()))
14136             continue;
14137 
14138         F.erase();
14139       }
14140       F.done();
14141     }
14142 
14143     // Suppress the protected check (C++ [class.protected]) for each of the
14144     // assignment operators we found. This strange dance is required when
14145     // we're assigning via a base classes's copy-assignment operator. To
14146     // ensure that we're getting the right base class subobject (without
14147     // ambiguities), we need to cast "this" to that subobject type; to
14148     // ensure that we don't go through the virtual call mechanism, we need
14149     // to qualify the operator= name with the base class (see below). However,
14150     // this means that if the base class has a protected copy assignment
14151     // operator, the protected member access check will fail. So, we
14152     // rewrite "protected" access to "public" access in this case, since we
14153     // know by construction that we're calling from a derived class.
14154     if (CopyingBaseSubobject) {
14155       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14156            L != LEnd; ++L) {
14157         if (L.getAccess() == AS_protected)
14158           L.setAccess(AS_public);
14159       }
14160     }
14161 
14162     // Create the nested-name-specifier that will be used to qualify the
14163     // reference to operator=; this is required to suppress the virtual
14164     // call mechanism.
14165     CXXScopeSpec SS;
14166     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14167     SS.MakeTrivial(S.Context,
14168                    NestedNameSpecifier::Create(S.Context, nullptr, false,
14169                                                CanonicalT),
14170                    Loc);
14171 
14172     // Create the reference to operator=.
14173     ExprResult OpEqualRef
14174       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14175                                    SS, /*TemplateKWLoc=*/SourceLocation(),
14176                                    /*FirstQualifierInScope=*/nullptr,
14177                                    OpLookup,
14178                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
14179                                    /*SuppressQualifierCheck=*/true);
14180     if (OpEqualRef.isInvalid())
14181       return StmtError();
14182 
14183     // Build the call to the assignment operator.
14184 
14185     Expr *FromInst = From.build(S, Loc);
14186     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14187                                                   OpEqualRef.getAs<Expr>(),
14188                                                   Loc, FromInst, Loc);
14189     if (Call.isInvalid())
14190       return StmtError();
14191 
14192     // If we built a call to a trivial 'operator=' while copying an array,
14193     // bail out. We'll replace the whole shebang with a memcpy.
14194     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14195     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14196       return StmtResult((Stmt*)nullptr);
14197 
14198     // Convert to an expression-statement, and clean up any produced
14199     // temporaries.
14200     return S.ActOnExprStmt(Call);
14201   }
14202 
14203   //     - if the subobject is of scalar type, the built-in assignment
14204   //       operator is used.
14205   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14206   if (!ArrayTy) {
14207     ExprResult Assignment = S.CreateBuiltinBinOp(
14208         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14209     if (Assignment.isInvalid())
14210       return StmtError();
14211     return S.ActOnExprStmt(Assignment);
14212   }
14213 
14214   //     - if the subobject is an array, each element is assigned, in the
14215   //       manner appropriate to the element type;
14216 
14217   // Construct a loop over the array bounds, e.g.,
14218   //
14219   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14220   //
14221   // that will copy each of the array elements.
14222   QualType SizeType = S.Context.getSizeType();
14223 
14224   // Create the iteration variable.
14225   IdentifierInfo *IterationVarName = nullptr;
14226   {
14227     SmallString<8> Str;
14228     llvm::raw_svector_ostream OS(Str);
14229     OS << "__i" << Depth;
14230     IterationVarName = &S.Context.Idents.get(OS.str());
14231   }
14232   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14233                                           IterationVarName, SizeType,
14234                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14235                                           SC_None);
14236 
14237   // Initialize the iteration variable to zero.
14238   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14239   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14240 
14241   // Creates a reference to the iteration variable.
14242   RefBuilder IterationVarRef(IterationVar, SizeType);
14243   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14244 
14245   // Create the DeclStmt that holds the iteration variable.
14246   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14247 
14248   // Subscript the "from" and "to" expressions with the iteration variable.
14249   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14250   MoveCastBuilder FromIndexMove(FromIndexCopy);
14251   const ExprBuilder *FromIndex;
14252   if (Copying)
14253     FromIndex = &FromIndexCopy;
14254   else
14255     FromIndex = &FromIndexMove;
14256 
14257   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14258 
14259   // Build the copy/move for an individual element of the array.
14260   StmtResult Copy =
14261     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14262                                      ToIndex, *FromIndex, CopyingBaseSubobject,
14263                                      Copying, Depth + 1);
14264   // Bail out if copying fails or if we determined that we should use memcpy.
14265   if (Copy.isInvalid() || !Copy.get())
14266     return Copy;
14267 
14268   // Create the comparison against the array bound.
14269   llvm::APInt Upper
14270     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14271   Expr *Comparison = BinaryOperator::Create(
14272       S.Context, IterationVarRefRVal.build(S, Loc),
14273       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14274       S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14275       S.CurFPFeatureOverrides());
14276 
14277   // Create the pre-increment of the iteration variable. We can determine
14278   // whether the increment will overflow based on the value of the array
14279   // bound.
14280   Expr *Increment = UnaryOperator::Create(
14281       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14282       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14283 
14284   // Construct the loop that copies all elements of this array.
14285   return S.ActOnForStmt(
14286       Loc, Loc, InitStmt,
14287       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14288       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14289 }
14290 
14291 static StmtResult
14292 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14293                       const ExprBuilder &To, const ExprBuilder &From,
14294                       bool CopyingBaseSubobject, bool Copying) {
14295   // Maybe we should use a memcpy?
14296   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14297       T.isTriviallyCopyableType(S.Context))
14298     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14299 
14300   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14301                                                      CopyingBaseSubobject,
14302                                                      Copying, 0));
14303 
14304   // If we ended up picking a trivial assignment operator for an array of a
14305   // non-trivially-copyable class type, just emit a memcpy.
14306   if (!Result.isInvalid() && !Result.get())
14307     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14308 
14309   return Result;
14310 }
14311 
14312 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14313   // Note: The following rules are largely analoguous to the copy
14314   // constructor rules. Note that virtual bases are not taken into account
14315   // for determining the argument type of the operator. Note also that
14316   // operators taking an object instead of a reference are allowed.
14317   assert(ClassDecl->needsImplicitCopyAssignment());
14318 
14319   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14320   if (DSM.isAlreadyBeingDeclared())
14321     return nullptr;
14322 
14323   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14324   LangAS AS = getDefaultCXXMethodAddrSpace();
14325   if (AS != LangAS::Default)
14326     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14327   QualType RetType = Context.getLValueReferenceType(ArgType);
14328   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14329   if (Const)
14330     ArgType = ArgType.withConst();
14331 
14332   ArgType = Context.getLValueReferenceType(ArgType);
14333 
14334   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14335                                                      CXXCopyAssignment,
14336                                                      Const);
14337 
14338   //   An implicitly-declared copy assignment operator is an inline public
14339   //   member of its class.
14340   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14341   SourceLocation ClassLoc = ClassDecl->getLocation();
14342   DeclarationNameInfo NameInfo(Name, ClassLoc);
14343   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14344       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14345       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14346       getCurFPFeatures().isFPConstrained(),
14347       /*isInline=*/true,
14348       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14349       SourceLocation());
14350   CopyAssignment->setAccess(AS_public);
14351   CopyAssignment->setDefaulted();
14352   CopyAssignment->setImplicit();
14353 
14354   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14355 
14356   if (getLangOpts().CUDA)
14357     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14358                                             CopyAssignment,
14359                                             /* ConstRHS */ Const,
14360                                             /* Diagnose */ false);
14361 
14362   // Add the parameter to the operator.
14363   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14364                                                ClassLoc, ClassLoc,
14365                                                /*Id=*/nullptr, ArgType,
14366                                                /*TInfo=*/nullptr, SC_None,
14367                                                nullptr);
14368   CopyAssignment->setParams(FromParam);
14369 
14370   CopyAssignment->setTrivial(
14371     ClassDecl->needsOverloadResolutionForCopyAssignment()
14372       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14373       : ClassDecl->hasTrivialCopyAssignment());
14374 
14375   // Note that we have added this copy-assignment operator.
14376   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14377 
14378   Scope *S = getScopeForContext(ClassDecl);
14379   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14380 
14381   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14382     ClassDecl->setImplicitCopyAssignmentIsDeleted();
14383     SetDeclDeleted(CopyAssignment, ClassLoc);
14384   }
14385 
14386   if (S)
14387     PushOnScopeChains(CopyAssignment, S, false);
14388   ClassDecl->addDecl(CopyAssignment);
14389 
14390   return CopyAssignment;
14391 }
14392 
14393 /// Diagnose an implicit copy operation for a class which is odr-used, but
14394 /// which is deprecated because the class has a user-declared copy constructor,
14395 /// copy assignment operator, or destructor.
14396 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14397   assert(CopyOp->isImplicit());
14398 
14399   CXXRecordDecl *RD = CopyOp->getParent();
14400   CXXMethodDecl *UserDeclaredOperation = nullptr;
14401 
14402   // In Microsoft mode, assignment operations don't affect constructors and
14403   // vice versa.
14404   if (RD->hasUserDeclaredDestructor()) {
14405     UserDeclaredOperation = RD->getDestructor();
14406   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14407              RD->hasUserDeclaredCopyConstructor() &&
14408              !S.getLangOpts().MSVCCompat) {
14409     // Find any user-declared copy constructor.
14410     for (auto *I : RD->ctors()) {
14411       if (I->isCopyConstructor()) {
14412         UserDeclaredOperation = I;
14413         break;
14414       }
14415     }
14416     assert(UserDeclaredOperation);
14417   } else if (isa<CXXConstructorDecl>(CopyOp) &&
14418              RD->hasUserDeclaredCopyAssignment() &&
14419              !S.getLangOpts().MSVCCompat) {
14420     // Find any user-declared move assignment operator.
14421     for (auto *I : RD->methods()) {
14422       if (I->isCopyAssignmentOperator()) {
14423         UserDeclaredOperation = I;
14424         break;
14425       }
14426     }
14427     assert(UserDeclaredOperation);
14428   }
14429 
14430   if (UserDeclaredOperation) {
14431     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14432     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14433     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14434     unsigned DiagID =
14435         (UDOIsUserProvided && UDOIsDestructor)
14436             ? diag::warn_deprecated_copy_with_user_provided_dtor
14437         : (UDOIsUserProvided && !UDOIsDestructor)
14438             ? diag::warn_deprecated_copy_with_user_provided_copy
14439         : (!UDOIsUserProvided && UDOIsDestructor)
14440             ? diag::warn_deprecated_copy_with_dtor
14441             : diag::warn_deprecated_copy;
14442     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14443         << RD << IsCopyAssignment;
14444   }
14445 }
14446 
14447 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14448                                         CXXMethodDecl *CopyAssignOperator) {
14449   assert((CopyAssignOperator->isDefaulted() &&
14450           CopyAssignOperator->isOverloadedOperator() &&
14451           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14452           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14453           !CopyAssignOperator->isDeleted()) &&
14454          "DefineImplicitCopyAssignment called for wrong function");
14455   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14456     return;
14457 
14458   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14459   if (ClassDecl->isInvalidDecl()) {
14460     CopyAssignOperator->setInvalidDecl();
14461     return;
14462   }
14463 
14464   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14465 
14466   // The exception specification is needed because we are defining the
14467   // function.
14468   ResolveExceptionSpec(CurrentLocation,
14469                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14470 
14471   // Add a context note for diagnostics produced after this point.
14472   Scope.addContextNote(CurrentLocation);
14473 
14474   // C++11 [class.copy]p18:
14475   //   The [definition of an implicitly declared copy assignment operator] is
14476   //   deprecated if the class has a user-declared copy constructor or a
14477   //   user-declared destructor.
14478   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14479     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14480 
14481   // C++0x [class.copy]p30:
14482   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14483   //   for a non-union class X performs memberwise copy assignment of its
14484   //   subobjects. The direct base classes of X are assigned first, in the
14485   //   order of their declaration in the base-specifier-list, and then the
14486   //   immediate non-static data members of X are assigned, in the order in
14487   //   which they were declared in the class definition.
14488 
14489   // The statements that form the synthesized function body.
14490   SmallVector<Stmt*, 8> Statements;
14491 
14492   // The parameter for the "other" object, which we are copying from.
14493   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14494   Qualifiers OtherQuals = Other->getType().getQualifiers();
14495   QualType OtherRefType = Other->getType();
14496   if (const LValueReferenceType *OtherRef
14497                                 = OtherRefType->getAs<LValueReferenceType>()) {
14498     OtherRefType = OtherRef->getPointeeType();
14499     OtherQuals = OtherRefType.getQualifiers();
14500   }
14501 
14502   // Our location for everything implicitly-generated.
14503   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14504                            ? CopyAssignOperator->getEndLoc()
14505                            : CopyAssignOperator->getLocation();
14506 
14507   // Builds a DeclRefExpr for the "other" object.
14508   RefBuilder OtherRef(Other, OtherRefType);
14509 
14510   // Builds the "this" pointer.
14511   ThisBuilder This;
14512 
14513   // Assign base classes.
14514   bool Invalid = false;
14515   for (auto &Base : ClassDecl->bases()) {
14516     // Form the assignment:
14517     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14518     QualType BaseType = Base.getType().getUnqualifiedType();
14519     if (!BaseType->isRecordType()) {
14520       Invalid = true;
14521       continue;
14522     }
14523 
14524     CXXCastPath BasePath;
14525     BasePath.push_back(&Base);
14526 
14527     // Construct the "from" expression, which is an implicit cast to the
14528     // appropriately-qualified base type.
14529     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14530                      VK_LValue, BasePath);
14531 
14532     // Dereference "this".
14533     DerefBuilder DerefThis(This);
14534     CastBuilder To(DerefThis,
14535                    Context.getQualifiedType(
14536                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14537                    VK_LValue, BasePath);
14538 
14539     // Build the copy.
14540     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14541                                             To, From,
14542                                             /*CopyingBaseSubobject=*/true,
14543                                             /*Copying=*/true);
14544     if (Copy.isInvalid()) {
14545       CopyAssignOperator->setInvalidDecl();
14546       return;
14547     }
14548 
14549     // Success! Record the copy.
14550     Statements.push_back(Copy.getAs<Expr>());
14551   }
14552 
14553   // Assign non-static members.
14554   for (auto *Field : ClassDecl->fields()) {
14555     // FIXME: We should form some kind of AST representation for the implied
14556     // memcpy in a union copy operation.
14557     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14558       continue;
14559 
14560     if (Field->isInvalidDecl()) {
14561       Invalid = true;
14562       continue;
14563     }
14564 
14565     // Check for members of reference type; we can't copy those.
14566     if (Field->getType()->isReferenceType()) {
14567       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14568         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14569       Diag(Field->getLocation(), diag::note_declared_at);
14570       Invalid = true;
14571       continue;
14572     }
14573 
14574     // Check for members of const-qualified, non-class type.
14575     QualType BaseType = Context.getBaseElementType(Field->getType());
14576     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14577       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14578         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14579       Diag(Field->getLocation(), diag::note_declared_at);
14580       Invalid = true;
14581       continue;
14582     }
14583 
14584     // Suppress assigning zero-width bitfields.
14585     if (Field->isZeroLengthBitField(Context))
14586       continue;
14587 
14588     QualType FieldType = Field->getType().getNonReferenceType();
14589     if (FieldType->isIncompleteArrayType()) {
14590       assert(ClassDecl->hasFlexibleArrayMember() &&
14591              "Incomplete array type is not valid");
14592       continue;
14593     }
14594 
14595     // Build references to the field in the object we're copying from and to.
14596     CXXScopeSpec SS; // Intentionally empty
14597     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14598                               LookupMemberName);
14599     MemberLookup.addDecl(Field);
14600     MemberLookup.resolveKind();
14601 
14602     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14603 
14604     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14605 
14606     // Build the copy of this field.
14607     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14608                                             To, From,
14609                                             /*CopyingBaseSubobject=*/false,
14610                                             /*Copying=*/true);
14611     if (Copy.isInvalid()) {
14612       CopyAssignOperator->setInvalidDecl();
14613       return;
14614     }
14615 
14616     // Success! Record the copy.
14617     Statements.push_back(Copy.getAs<Stmt>());
14618   }
14619 
14620   if (!Invalid) {
14621     // Add a "return *this;"
14622     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14623 
14624     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14625     if (Return.isInvalid())
14626       Invalid = true;
14627     else
14628       Statements.push_back(Return.getAs<Stmt>());
14629   }
14630 
14631   if (Invalid) {
14632     CopyAssignOperator->setInvalidDecl();
14633     return;
14634   }
14635 
14636   StmtResult Body;
14637   {
14638     CompoundScopeRAII CompoundScope(*this);
14639     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14640                              /*isStmtExpr=*/false);
14641     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14642   }
14643   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14644   CopyAssignOperator->markUsed(Context);
14645 
14646   if (ASTMutationListener *L = getASTMutationListener()) {
14647     L->CompletedImplicitDefinition(CopyAssignOperator);
14648   }
14649 }
14650 
14651 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14652   assert(ClassDecl->needsImplicitMoveAssignment());
14653 
14654   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14655   if (DSM.isAlreadyBeingDeclared())
14656     return nullptr;
14657 
14658   // Note: The following rules are largely analoguous to the move
14659   // constructor rules.
14660 
14661   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14662   LangAS AS = getDefaultCXXMethodAddrSpace();
14663   if (AS != LangAS::Default)
14664     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14665   QualType RetType = Context.getLValueReferenceType(ArgType);
14666   ArgType = Context.getRValueReferenceType(ArgType);
14667 
14668   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14669                                                      CXXMoveAssignment,
14670                                                      false);
14671 
14672   //   An implicitly-declared move assignment operator is an inline public
14673   //   member of its class.
14674   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14675   SourceLocation ClassLoc = ClassDecl->getLocation();
14676   DeclarationNameInfo NameInfo(Name, ClassLoc);
14677   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14678       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14679       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14680       getCurFPFeatures().isFPConstrained(),
14681       /*isInline=*/true,
14682       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14683       SourceLocation());
14684   MoveAssignment->setAccess(AS_public);
14685   MoveAssignment->setDefaulted();
14686   MoveAssignment->setImplicit();
14687 
14688   setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14689 
14690   if (getLangOpts().CUDA)
14691     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14692                                             MoveAssignment,
14693                                             /* ConstRHS */ false,
14694                                             /* Diagnose */ false);
14695 
14696   // Add the parameter to the operator.
14697   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14698                                                ClassLoc, ClassLoc,
14699                                                /*Id=*/nullptr, ArgType,
14700                                                /*TInfo=*/nullptr, SC_None,
14701                                                nullptr);
14702   MoveAssignment->setParams(FromParam);
14703 
14704   MoveAssignment->setTrivial(
14705     ClassDecl->needsOverloadResolutionForMoveAssignment()
14706       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14707       : ClassDecl->hasTrivialMoveAssignment());
14708 
14709   // Note that we have added this copy-assignment operator.
14710   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14711 
14712   Scope *S = getScopeForContext(ClassDecl);
14713   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14714 
14715   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14716     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14717     SetDeclDeleted(MoveAssignment, ClassLoc);
14718   }
14719 
14720   if (S)
14721     PushOnScopeChains(MoveAssignment, S, false);
14722   ClassDecl->addDecl(MoveAssignment);
14723 
14724   return MoveAssignment;
14725 }
14726 
14727 /// Check if we're implicitly defining a move assignment operator for a class
14728 /// with virtual bases. Such a move assignment might move-assign the virtual
14729 /// base multiple times.
14730 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14731                                                SourceLocation CurrentLocation) {
14732   assert(!Class->isDependentContext() && "should not define dependent move");
14733 
14734   // Only a virtual base could get implicitly move-assigned multiple times.
14735   // Only a non-trivial move assignment can observe this. We only want to
14736   // diagnose if we implicitly define an assignment operator that assigns
14737   // two base classes, both of which move-assign the same virtual base.
14738   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14739       Class->getNumBases() < 2)
14740     return;
14741 
14742   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14743   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14744   VBaseMap VBases;
14745 
14746   for (auto &BI : Class->bases()) {
14747     Worklist.push_back(&BI);
14748     while (!Worklist.empty()) {
14749       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14750       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14751 
14752       // If the base has no non-trivial move assignment operators,
14753       // we don't care about moves from it.
14754       if (!Base->hasNonTrivialMoveAssignment())
14755         continue;
14756 
14757       // If there's nothing virtual here, skip it.
14758       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14759         continue;
14760 
14761       // If we're not actually going to call a move assignment for this base,
14762       // or the selected move assignment is trivial, skip it.
14763       Sema::SpecialMemberOverloadResult SMOR =
14764         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14765                               /*ConstArg*/false, /*VolatileArg*/false,
14766                               /*RValueThis*/true, /*ConstThis*/false,
14767                               /*VolatileThis*/false);
14768       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14769           !SMOR.getMethod()->isMoveAssignmentOperator())
14770         continue;
14771 
14772       if (BaseSpec->isVirtual()) {
14773         // We're going to move-assign this virtual base, and its move
14774         // assignment operator is not trivial. If this can happen for
14775         // multiple distinct direct bases of Class, diagnose it. (If it
14776         // only happens in one base, we'll diagnose it when synthesizing
14777         // that base class's move assignment operator.)
14778         CXXBaseSpecifier *&Existing =
14779             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14780                 .first->second;
14781         if (Existing && Existing != &BI) {
14782           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14783             << Class << Base;
14784           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14785               << (Base->getCanonicalDecl() ==
14786                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14787               << Base << Existing->getType() << Existing->getSourceRange();
14788           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14789               << (Base->getCanonicalDecl() ==
14790                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14791               << Base << BI.getType() << BaseSpec->getSourceRange();
14792 
14793           // Only diagnose each vbase once.
14794           Existing = nullptr;
14795         }
14796       } else {
14797         // Only walk over bases that have defaulted move assignment operators.
14798         // We assume that any user-provided move assignment operator handles
14799         // the multiple-moves-of-vbase case itself somehow.
14800         if (!SMOR.getMethod()->isDefaulted())
14801           continue;
14802 
14803         // We're going to move the base classes of Base. Add them to the list.
14804         llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
14805       }
14806     }
14807   }
14808 }
14809 
14810 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14811                                         CXXMethodDecl *MoveAssignOperator) {
14812   assert((MoveAssignOperator->isDefaulted() &&
14813           MoveAssignOperator->isOverloadedOperator() &&
14814           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14815           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14816           !MoveAssignOperator->isDeleted()) &&
14817          "DefineImplicitMoveAssignment called for wrong function");
14818   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14819     return;
14820 
14821   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14822   if (ClassDecl->isInvalidDecl()) {
14823     MoveAssignOperator->setInvalidDecl();
14824     return;
14825   }
14826 
14827   // C++0x [class.copy]p28:
14828   //   The implicitly-defined or move assignment operator for a non-union class
14829   //   X performs memberwise move assignment of its subobjects. The direct base
14830   //   classes of X are assigned first, in the order of their declaration in the
14831   //   base-specifier-list, and then the immediate non-static data members of X
14832   //   are assigned, in the order in which they were declared in the class
14833   //   definition.
14834 
14835   // Issue a warning if our implicit move assignment operator will move
14836   // from a virtual base more than once.
14837   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14838 
14839   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14840 
14841   // The exception specification is needed because we are defining the
14842   // function.
14843   ResolveExceptionSpec(CurrentLocation,
14844                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14845 
14846   // Add a context note for diagnostics produced after this point.
14847   Scope.addContextNote(CurrentLocation);
14848 
14849   // The statements that form the synthesized function body.
14850   SmallVector<Stmt*, 8> Statements;
14851 
14852   // The parameter for the "other" object, which we are move from.
14853   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14854   QualType OtherRefType =
14855       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14856 
14857   // Our location for everything implicitly-generated.
14858   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14859                            ? MoveAssignOperator->getEndLoc()
14860                            : MoveAssignOperator->getLocation();
14861 
14862   // Builds a reference to the "other" object.
14863   RefBuilder OtherRef(Other, OtherRefType);
14864   // Cast to rvalue.
14865   MoveCastBuilder MoveOther(OtherRef);
14866 
14867   // Builds the "this" pointer.
14868   ThisBuilder This;
14869 
14870   // Assign base classes.
14871   bool Invalid = false;
14872   for (auto &Base : ClassDecl->bases()) {
14873     // C++11 [class.copy]p28:
14874     //   It is unspecified whether subobjects representing virtual base classes
14875     //   are assigned more than once by the implicitly-defined copy assignment
14876     //   operator.
14877     // FIXME: Do not assign to a vbase that will be assigned by some other base
14878     // class. For a move-assignment, this can result in the vbase being moved
14879     // multiple times.
14880 
14881     // Form the assignment:
14882     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14883     QualType BaseType = Base.getType().getUnqualifiedType();
14884     if (!BaseType->isRecordType()) {
14885       Invalid = true;
14886       continue;
14887     }
14888 
14889     CXXCastPath BasePath;
14890     BasePath.push_back(&Base);
14891 
14892     // Construct the "from" expression, which is an implicit cast to the
14893     // appropriately-qualified base type.
14894     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14895 
14896     // Dereference "this".
14897     DerefBuilder DerefThis(This);
14898 
14899     // Implicitly cast "this" to the appropriately-qualified base type.
14900     CastBuilder To(DerefThis,
14901                    Context.getQualifiedType(
14902                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14903                    VK_LValue, BasePath);
14904 
14905     // Build the move.
14906     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14907                                             To, From,
14908                                             /*CopyingBaseSubobject=*/true,
14909                                             /*Copying=*/false);
14910     if (Move.isInvalid()) {
14911       MoveAssignOperator->setInvalidDecl();
14912       return;
14913     }
14914 
14915     // Success! Record the move.
14916     Statements.push_back(Move.getAs<Expr>());
14917   }
14918 
14919   // Assign non-static members.
14920   for (auto *Field : ClassDecl->fields()) {
14921     // FIXME: We should form some kind of AST representation for the implied
14922     // memcpy in a union copy operation.
14923     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14924       continue;
14925 
14926     if (Field->isInvalidDecl()) {
14927       Invalid = true;
14928       continue;
14929     }
14930 
14931     // Check for members of reference type; we can't move those.
14932     if (Field->getType()->isReferenceType()) {
14933       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14934         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14935       Diag(Field->getLocation(), diag::note_declared_at);
14936       Invalid = true;
14937       continue;
14938     }
14939 
14940     // Check for members of const-qualified, non-class type.
14941     QualType BaseType = Context.getBaseElementType(Field->getType());
14942     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14943       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14944         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14945       Diag(Field->getLocation(), diag::note_declared_at);
14946       Invalid = true;
14947       continue;
14948     }
14949 
14950     // Suppress assigning zero-width bitfields.
14951     if (Field->isZeroLengthBitField(Context))
14952       continue;
14953 
14954     QualType FieldType = Field->getType().getNonReferenceType();
14955     if (FieldType->isIncompleteArrayType()) {
14956       assert(ClassDecl->hasFlexibleArrayMember() &&
14957              "Incomplete array type is not valid");
14958       continue;
14959     }
14960 
14961     // Build references to the field in the object we're copying from and to.
14962     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14963                               LookupMemberName);
14964     MemberLookup.addDecl(Field);
14965     MemberLookup.resolveKind();
14966     MemberBuilder From(MoveOther, OtherRefType,
14967                        /*IsArrow=*/false, MemberLookup);
14968     MemberBuilder To(This, getCurrentThisType(),
14969                      /*IsArrow=*/true, MemberLookup);
14970 
14971     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14972         "Member reference with rvalue base must be rvalue except for reference "
14973         "members, which aren't allowed for move assignment.");
14974 
14975     // Build the move of this field.
14976     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14977                                             To, From,
14978                                             /*CopyingBaseSubobject=*/false,
14979                                             /*Copying=*/false);
14980     if (Move.isInvalid()) {
14981       MoveAssignOperator->setInvalidDecl();
14982       return;
14983     }
14984 
14985     // Success! Record the copy.
14986     Statements.push_back(Move.getAs<Stmt>());
14987   }
14988 
14989   if (!Invalid) {
14990     // Add a "return *this;"
14991     ExprResult ThisObj =
14992         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14993 
14994     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14995     if (Return.isInvalid())
14996       Invalid = true;
14997     else
14998       Statements.push_back(Return.getAs<Stmt>());
14999   }
15000 
15001   if (Invalid) {
15002     MoveAssignOperator->setInvalidDecl();
15003     return;
15004   }
15005 
15006   StmtResult Body;
15007   {
15008     CompoundScopeRAII CompoundScope(*this);
15009     Body = ActOnCompoundStmt(Loc, Loc, Statements,
15010                              /*isStmtExpr=*/false);
15011     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15012   }
15013   MoveAssignOperator->setBody(Body.getAs<Stmt>());
15014   MoveAssignOperator->markUsed(Context);
15015 
15016   if (ASTMutationListener *L = getASTMutationListener()) {
15017     L->CompletedImplicitDefinition(MoveAssignOperator);
15018   }
15019 }
15020 
15021 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15022                                                     CXXRecordDecl *ClassDecl) {
15023   // C++ [class.copy]p4:
15024   //   If the class definition does not explicitly declare a copy
15025   //   constructor, one is declared implicitly.
15026   assert(ClassDecl->needsImplicitCopyConstructor());
15027 
15028   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15029   if (DSM.isAlreadyBeingDeclared())
15030     return nullptr;
15031 
15032   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15033   QualType ArgType = ClassType;
15034   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15035   if (Const)
15036     ArgType = ArgType.withConst();
15037 
15038   LangAS AS = getDefaultCXXMethodAddrSpace();
15039   if (AS != LangAS::Default)
15040     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15041 
15042   ArgType = Context.getLValueReferenceType(ArgType);
15043 
15044   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15045                                                      CXXCopyConstructor,
15046                                                      Const);
15047 
15048   DeclarationName Name
15049     = Context.DeclarationNames.getCXXConstructorName(
15050                                            Context.getCanonicalType(ClassType));
15051   SourceLocation ClassLoc = ClassDecl->getLocation();
15052   DeclarationNameInfo NameInfo(Name, ClassLoc);
15053 
15054   //   An implicitly-declared copy constructor is an inline public
15055   //   member of its class.
15056   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15057       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15058       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15059       /*isInline=*/true,
15060       /*isImplicitlyDeclared=*/true,
15061       Constexpr ? ConstexprSpecKind::Constexpr
15062                 : ConstexprSpecKind::Unspecified);
15063   CopyConstructor->setAccess(AS_public);
15064   CopyConstructor->setDefaulted();
15065 
15066   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15067 
15068   if (getLangOpts().CUDA)
15069     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15070                                             CopyConstructor,
15071                                             /* ConstRHS */ Const,
15072                                             /* Diagnose */ false);
15073 
15074   // During template instantiation of special member functions we need a
15075   // reliable TypeSourceInfo for the parameter types in order to allow functions
15076   // to be substituted.
15077   TypeSourceInfo *TSI = nullptr;
15078   if (inTemplateInstantiation() && ClassDecl->isLambda())
15079     TSI = Context.getTrivialTypeSourceInfo(ArgType);
15080 
15081   // Add the parameter to the constructor.
15082   ParmVarDecl *FromParam =
15083       ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15084                           /*IdentifierInfo=*/nullptr, ArgType,
15085                           /*TInfo=*/TSI, SC_None, nullptr);
15086   CopyConstructor->setParams(FromParam);
15087 
15088   CopyConstructor->setTrivial(
15089       ClassDecl->needsOverloadResolutionForCopyConstructor()
15090           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15091           : ClassDecl->hasTrivialCopyConstructor());
15092 
15093   CopyConstructor->setTrivialForCall(
15094       ClassDecl->hasAttr<TrivialABIAttr>() ||
15095       (ClassDecl->needsOverloadResolutionForCopyConstructor()
15096            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15097              TAH_ConsiderTrivialABI)
15098            : ClassDecl->hasTrivialCopyConstructorForCall()));
15099 
15100   // Note that we have declared this constructor.
15101   ++getASTContext().NumImplicitCopyConstructorsDeclared;
15102 
15103   Scope *S = getScopeForContext(ClassDecl);
15104   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15105 
15106   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15107     ClassDecl->setImplicitCopyConstructorIsDeleted();
15108     SetDeclDeleted(CopyConstructor, ClassLoc);
15109   }
15110 
15111   if (S)
15112     PushOnScopeChains(CopyConstructor, S, false);
15113   ClassDecl->addDecl(CopyConstructor);
15114 
15115   return CopyConstructor;
15116 }
15117 
15118 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15119                                          CXXConstructorDecl *CopyConstructor) {
15120   assert((CopyConstructor->isDefaulted() &&
15121           CopyConstructor->isCopyConstructor() &&
15122           !CopyConstructor->doesThisDeclarationHaveABody() &&
15123           !CopyConstructor->isDeleted()) &&
15124          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15125   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15126     return;
15127 
15128   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15129   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15130 
15131   SynthesizedFunctionScope Scope(*this, CopyConstructor);
15132 
15133   // The exception specification is needed because we are defining the
15134   // function.
15135   ResolveExceptionSpec(CurrentLocation,
15136                        CopyConstructor->getType()->castAs<FunctionProtoType>());
15137   MarkVTableUsed(CurrentLocation, ClassDecl);
15138 
15139   // Add a context note for diagnostics produced after this point.
15140   Scope.addContextNote(CurrentLocation);
15141 
15142   // C++11 [class.copy]p7:
15143   //   The [definition of an implicitly declared copy constructor] is
15144   //   deprecated if the class has a user-declared copy assignment operator
15145   //   or a user-declared destructor.
15146   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15147     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15148 
15149   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15150     CopyConstructor->setInvalidDecl();
15151   }  else {
15152     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15153                              ? CopyConstructor->getEndLoc()
15154                              : CopyConstructor->getLocation();
15155     Sema::CompoundScopeRAII CompoundScope(*this);
15156     CopyConstructor->setBody(
15157         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
15158     CopyConstructor->markUsed(Context);
15159   }
15160 
15161   if (ASTMutationListener *L = getASTMutationListener()) {
15162     L->CompletedImplicitDefinition(CopyConstructor);
15163   }
15164 }
15165 
15166 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15167                                                     CXXRecordDecl *ClassDecl) {
15168   assert(ClassDecl->needsImplicitMoveConstructor());
15169 
15170   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15171   if (DSM.isAlreadyBeingDeclared())
15172     return nullptr;
15173 
15174   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15175 
15176   QualType ArgType = ClassType;
15177   LangAS AS = getDefaultCXXMethodAddrSpace();
15178   if (AS != LangAS::Default)
15179     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15180   ArgType = Context.getRValueReferenceType(ArgType);
15181 
15182   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15183                                                      CXXMoveConstructor,
15184                                                      false);
15185 
15186   DeclarationName Name
15187     = Context.DeclarationNames.getCXXConstructorName(
15188                                            Context.getCanonicalType(ClassType));
15189   SourceLocation ClassLoc = ClassDecl->getLocation();
15190   DeclarationNameInfo NameInfo(Name, ClassLoc);
15191 
15192   // C++11 [class.copy]p11:
15193   //   An implicitly-declared copy/move constructor is an inline public
15194   //   member of its class.
15195   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15196       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15197       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15198       /*isInline=*/true,
15199       /*isImplicitlyDeclared=*/true,
15200       Constexpr ? ConstexprSpecKind::Constexpr
15201                 : ConstexprSpecKind::Unspecified);
15202   MoveConstructor->setAccess(AS_public);
15203   MoveConstructor->setDefaulted();
15204 
15205   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15206 
15207   if (getLangOpts().CUDA)
15208     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15209                                             MoveConstructor,
15210                                             /* ConstRHS */ false,
15211                                             /* Diagnose */ false);
15212 
15213   // Add the parameter to the constructor.
15214   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15215                                                ClassLoc, ClassLoc,
15216                                                /*IdentifierInfo=*/nullptr,
15217                                                ArgType, /*TInfo=*/nullptr,
15218                                                SC_None, nullptr);
15219   MoveConstructor->setParams(FromParam);
15220 
15221   MoveConstructor->setTrivial(
15222       ClassDecl->needsOverloadResolutionForMoveConstructor()
15223           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15224           : ClassDecl->hasTrivialMoveConstructor());
15225 
15226   MoveConstructor->setTrivialForCall(
15227       ClassDecl->hasAttr<TrivialABIAttr>() ||
15228       (ClassDecl->needsOverloadResolutionForMoveConstructor()
15229            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15230                                     TAH_ConsiderTrivialABI)
15231            : ClassDecl->hasTrivialMoveConstructorForCall()));
15232 
15233   // Note that we have declared this constructor.
15234   ++getASTContext().NumImplicitMoveConstructorsDeclared;
15235 
15236   Scope *S = getScopeForContext(ClassDecl);
15237   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15238 
15239   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15240     ClassDecl->setImplicitMoveConstructorIsDeleted();
15241     SetDeclDeleted(MoveConstructor, ClassLoc);
15242   }
15243 
15244   if (S)
15245     PushOnScopeChains(MoveConstructor, S, false);
15246   ClassDecl->addDecl(MoveConstructor);
15247 
15248   return MoveConstructor;
15249 }
15250 
15251 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15252                                          CXXConstructorDecl *MoveConstructor) {
15253   assert((MoveConstructor->isDefaulted() &&
15254           MoveConstructor->isMoveConstructor() &&
15255           !MoveConstructor->doesThisDeclarationHaveABody() &&
15256           !MoveConstructor->isDeleted()) &&
15257          "DefineImplicitMoveConstructor - call it for implicit move ctor");
15258   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15259     return;
15260 
15261   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15262   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15263 
15264   SynthesizedFunctionScope Scope(*this, MoveConstructor);
15265 
15266   // The exception specification is needed because we are defining the
15267   // function.
15268   ResolveExceptionSpec(CurrentLocation,
15269                        MoveConstructor->getType()->castAs<FunctionProtoType>());
15270   MarkVTableUsed(CurrentLocation, ClassDecl);
15271 
15272   // Add a context note for diagnostics produced after this point.
15273   Scope.addContextNote(CurrentLocation);
15274 
15275   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15276     MoveConstructor->setInvalidDecl();
15277   } else {
15278     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15279                              ? MoveConstructor->getEndLoc()
15280                              : MoveConstructor->getLocation();
15281     Sema::CompoundScopeRAII CompoundScope(*this);
15282     MoveConstructor->setBody(ActOnCompoundStmt(
15283         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
15284     MoveConstructor->markUsed(Context);
15285   }
15286 
15287   if (ASTMutationListener *L = getASTMutationListener()) {
15288     L->CompletedImplicitDefinition(MoveConstructor);
15289   }
15290 }
15291 
15292 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15293   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15294 }
15295 
15296 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15297                             SourceLocation CurrentLocation,
15298                             CXXConversionDecl *Conv) {
15299   SynthesizedFunctionScope Scope(*this, Conv);
15300   assert(!Conv->getReturnType()->isUndeducedType());
15301 
15302   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15303   CallingConv CC =
15304       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15305 
15306   CXXRecordDecl *Lambda = Conv->getParent();
15307   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15308   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
15309 
15310   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15311     CallOp = InstantiateFunctionDeclaration(
15312         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15313     if (!CallOp)
15314       return;
15315 
15316     Invoker = InstantiateFunctionDeclaration(
15317         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15318     if (!Invoker)
15319       return;
15320   }
15321 
15322   if (CallOp->isInvalidDecl())
15323     return;
15324 
15325   // Mark the call operator referenced (and add to pending instantiations
15326   // if necessary).
15327   // For both the conversion and static-invoker template specializations
15328   // we construct their body's in this function, so no need to add them
15329   // to the PendingInstantiations.
15330   MarkFunctionReferenced(CurrentLocation, CallOp);
15331 
15332   // Fill in the __invoke function with a dummy implementation. IR generation
15333   // will fill in the actual details. Update its type in case it contained
15334   // an 'auto'.
15335   Invoker->markUsed(Context);
15336   Invoker->setReferenced();
15337   Invoker->setType(Conv->getReturnType()->getPointeeType());
15338   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15339 
15340   // Construct the body of the conversion function { return __invoke; }.
15341   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
15342                                        VK_LValue, Conv->getLocation());
15343   assert(FunctionRef && "Can't refer to __invoke function?");
15344   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15345   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
15346                                      Conv->getLocation()));
15347   Conv->markUsed(Context);
15348   Conv->setReferenced();
15349 
15350   if (ASTMutationListener *L = getASTMutationListener()) {
15351     L->CompletedImplicitDefinition(Conv);
15352     L->CompletedImplicitDefinition(Invoker);
15353   }
15354 }
15355 
15356 
15357 
15358 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15359        SourceLocation CurrentLocation,
15360        CXXConversionDecl *Conv)
15361 {
15362   assert(!Conv->getParent()->isGenericLambda());
15363 
15364   SynthesizedFunctionScope Scope(*this, Conv);
15365 
15366   // Copy-initialize the lambda object as needed to capture it.
15367   Expr *This = ActOnCXXThis(CurrentLocation).get();
15368   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15369 
15370   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15371                                                         Conv->getLocation(),
15372                                                         Conv, DerefThis);
15373 
15374   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15375   // behavior.  Note that only the general conversion function does this
15376   // (since it's unusable otherwise); in the case where we inline the
15377   // block literal, it has block literal lifetime semantics.
15378   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15379     BuildBlock = ImplicitCastExpr::Create(
15380         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15381         BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15382 
15383   if (BuildBlock.isInvalid()) {
15384     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15385     Conv->setInvalidDecl();
15386     return;
15387   }
15388 
15389   // Create the return statement that returns the block from the conversion
15390   // function.
15391   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15392   if (Return.isInvalid()) {
15393     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15394     Conv->setInvalidDecl();
15395     return;
15396   }
15397 
15398   // Set the body of the conversion function.
15399   Stmt *ReturnS = Return.get();
15400   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
15401                                      Conv->getLocation()));
15402   Conv->markUsed(Context);
15403 
15404   // We're done; notify the mutation listener, if any.
15405   if (ASTMutationListener *L = getASTMutationListener()) {
15406     L->CompletedImplicitDefinition(Conv);
15407   }
15408 }
15409 
15410 /// Determine whether the given list arguments contains exactly one
15411 /// "real" (non-default) argument.
15412 static bool hasOneRealArgument(MultiExprArg Args) {
15413   switch (Args.size()) {
15414   case 0:
15415     return false;
15416 
15417   default:
15418     if (!Args[1]->isDefaultArgument())
15419       return false;
15420 
15421     LLVM_FALLTHROUGH;
15422   case 1:
15423     return !Args[0]->isDefaultArgument();
15424   }
15425 
15426   return false;
15427 }
15428 
15429 ExprResult
15430 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15431                             NamedDecl *FoundDecl,
15432                             CXXConstructorDecl *Constructor,
15433                             MultiExprArg ExprArgs,
15434                             bool HadMultipleCandidates,
15435                             bool IsListInitialization,
15436                             bool IsStdInitListInitialization,
15437                             bool RequiresZeroInit,
15438                             unsigned ConstructKind,
15439                             SourceRange ParenRange) {
15440   bool Elidable = false;
15441 
15442   // C++0x [class.copy]p34:
15443   //   When certain criteria are met, an implementation is allowed to
15444   //   omit the copy/move construction of a class object, even if the
15445   //   copy/move constructor and/or destructor for the object have
15446   //   side effects. [...]
15447   //     - when a temporary class object that has not been bound to a
15448   //       reference (12.2) would be copied/moved to a class object
15449   //       with the same cv-unqualified type, the copy/move operation
15450   //       can be omitted by constructing the temporary object
15451   //       directly into the target of the omitted copy/move
15452   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15453       // FIXME: Converting constructors should also be accepted.
15454       // But to fix this, the logic that digs down into a CXXConstructExpr
15455       // to find the source object needs to handle it.
15456       // Right now it assumes the source object is passed directly as the
15457       // first argument.
15458       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15459     Expr *SubExpr = ExprArgs[0];
15460     // FIXME: Per above, this is also incorrect if we want to accept
15461     //        converting constructors, as isTemporaryObject will
15462     //        reject temporaries with different type from the
15463     //        CXXRecord itself.
15464     Elidable = SubExpr->isTemporaryObject(
15465         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15466   }
15467 
15468   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15469                                FoundDecl, Constructor,
15470                                Elidable, ExprArgs, HadMultipleCandidates,
15471                                IsListInitialization,
15472                                IsStdInitListInitialization, RequiresZeroInit,
15473                                ConstructKind, ParenRange);
15474 }
15475 
15476 ExprResult
15477 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15478                             NamedDecl *FoundDecl,
15479                             CXXConstructorDecl *Constructor,
15480                             bool Elidable,
15481                             MultiExprArg ExprArgs,
15482                             bool HadMultipleCandidates,
15483                             bool IsListInitialization,
15484                             bool IsStdInitListInitialization,
15485                             bool RequiresZeroInit,
15486                             unsigned ConstructKind,
15487                             SourceRange ParenRange) {
15488   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15489     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15490     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15491       return ExprError();
15492   }
15493 
15494   return BuildCXXConstructExpr(
15495       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15496       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15497       RequiresZeroInit, ConstructKind, ParenRange);
15498 }
15499 
15500 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15501 /// including handling of its default argument expressions.
15502 ExprResult
15503 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15504                             CXXConstructorDecl *Constructor,
15505                             bool Elidable,
15506                             MultiExprArg ExprArgs,
15507                             bool HadMultipleCandidates,
15508                             bool IsListInitialization,
15509                             bool IsStdInitListInitialization,
15510                             bool RequiresZeroInit,
15511                             unsigned ConstructKind,
15512                             SourceRange ParenRange) {
15513   assert(declaresSameEntity(
15514              Constructor->getParent(),
15515              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15516          "given constructor for wrong type");
15517   MarkFunctionReferenced(ConstructLoc, Constructor);
15518   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15519     return ExprError();
15520   if (getLangOpts().SYCLIsDevice &&
15521       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15522     return ExprError();
15523 
15524   return CheckForImmediateInvocation(
15525       CXXConstructExpr::Create(
15526           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15527           HadMultipleCandidates, IsListInitialization,
15528           IsStdInitListInitialization, RequiresZeroInit,
15529           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15530           ParenRange),
15531       Constructor);
15532 }
15533 
15534 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15535   assert(Field->hasInClassInitializer());
15536 
15537   // If we already have the in-class initializer nothing needs to be done.
15538   if (Field->getInClassInitializer())
15539     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15540 
15541   // If we might have already tried and failed to instantiate, don't try again.
15542   if (Field->isInvalidDecl())
15543     return ExprError();
15544 
15545   // Maybe we haven't instantiated the in-class initializer. Go check the
15546   // pattern FieldDecl to see if it has one.
15547   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15548 
15549   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15550     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15551     DeclContext::lookup_result Lookup =
15552         ClassPattern->lookup(Field->getDeclName());
15553 
15554     FieldDecl *Pattern = nullptr;
15555     for (auto L : Lookup) {
15556       if (isa<FieldDecl>(L)) {
15557         Pattern = cast<FieldDecl>(L);
15558         break;
15559       }
15560     }
15561     assert(Pattern && "We must have set the Pattern!");
15562 
15563     if (!Pattern->hasInClassInitializer() ||
15564         InstantiateInClassInitializer(Loc, Field, Pattern,
15565                                       getTemplateInstantiationArgs(Field))) {
15566       // Don't diagnose this again.
15567       Field->setInvalidDecl();
15568       return ExprError();
15569     }
15570     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15571   }
15572 
15573   // DR1351:
15574   //   If the brace-or-equal-initializer of a non-static data member
15575   //   invokes a defaulted default constructor of its class or of an
15576   //   enclosing class in a potentially evaluated subexpression, the
15577   //   program is ill-formed.
15578   //
15579   // This resolution is unworkable: the exception specification of the
15580   // default constructor can be needed in an unevaluated context, in
15581   // particular, in the operand of a noexcept-expression, and we can be
15582   // unable to compute an exception specification for an enclosed class.
15583   //
15584   // Any attempt to resolve the exception specification of a defaulted default
15585   // constructor before the initializer is lexically complete will ultimately
15586   // come here at which point we can diagnose it.
15587   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15588   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15589       << OutermostClass << Field;
15590   Diag(Field->getEndLoc(),
15591        diag::note_default_member_initializer_not_yet_parsed);
15592   // Recover by marking the field invalid, unless we're in a SFINAE context.
15593   if (!isSFINAEContext())
15594     Field->setInvalidDecl();
15595   return ExprError();
15596 }
15597 
15598 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15599   if (VD->isInvalidDecl()) return;
15600   // If initializing the variable failed, don't also diagnose problems with
15601   // the destructor, they're likely related.
15602   if (VD->getInit() && VD->getInit()->containsErrors())
15603     return;
15604 
15605   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15606   if (ClassDecl->isInvalidDecl()) return;
15607   if (ClassDecl->hasIrrelevantDestructor()) return;
15608   if (ClassDecl->isDependentContext()) return;
15609 
15610   if (VD->isNoDestroy(getASTContext()))
15611     return;
15612 
15613   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15614 
15615   // If this is an array, we'll require the destructor during initialization, so
15616   // we can skip over this. We still want to emit exit-time destructor warnings
15617   // though.
15618   if (!VD->getType()->isArrayType()) {
15619     MarkFunctionReferenced(VD->getLocation(), Destructor);
15620     CheckDestructorAccess(VD->getLocation(), Destructor,
15621                           PDiag(diag::err_access_dtor_var)
15622                               << VD->getDeclName() << VD->getType());
15623     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15624   }
15625 
15626   if (Destructor->isTrivial()) return;
15627 
15628   // If the destructor is constexpr, check whether the variable has constant
15629   // destruction now.
15630   if (Destructor->isConstexpr()) {
15631     bool HasConstantInit = false;
15632     if (VD->getInit() && !VD->getInit()->isValueDependent())
15633       HasConstantInit = VD->evaluateValue();
15634     SmallVector<PartialDiagnosticAt, 8> Notes;
15635     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15636         HasConstantInit) {
15637       Diag(VD->getLocation(),
15638            diag::err_constexpr_var_requires_const_destruction) << VD;
15639       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15640         Diag(Notes[I].first, Notes[I].second);
15641     }
15642   }
15643 
15644   if (!VD->hasGlobalStorage()) return;
15645 
15646   // Emit warning for non-trivial dtor in global scope (a real global,
15647   // class-static, function-static).
15648   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15649 
15650   // TODO: this should be re-enabled for static locals by !CXAAtExit
15651   if (!VD->isStaticLocal())
15652     Diag(VD->getLocation(), diag::warn_global_destructor);
15653 }
15654 
15655 /// Given a constructor and the set of arguments provided for the
15656 /// constructor, convert the arguments and add any required default arguments
15657 /// to form a proper call to this constructor.
15658 ///
15659 /// \returns true if an error occurred, false otherwise.
15660 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15661                                    QualType DeclInitType, MultiExprArg ArgsPtr,
15662                                    SourceLocation Loc,
15663                                    SmallVectorImpl<Expr *> &ConvertedArgs,
15664                                    bool AllowExplicit,
15665                                    bool IsListInitialization) {
15666   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15667   unsigned NumArgs = ArgsPtr.size();
15668   Expr **Args = ArgsPtr.data();
15669 
15670   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15671   unsigned NumParams = Proto->getNumParams();
15672 
15673   // If too few arguments are available, we'll fill in the rest with defaults.
15674   if (NumArgs < NumParams)
15675     ConvertedArgs.reserve(NumParams);
15676   else
15677     ConvertedArgs.reserve(NumArgs);
15678 
15679   VariadicCallType CallType =
15680     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15681   SmallVector<Expr *, 8> AllArgs;
15682   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15683                                         Proto, 0,
15684                                         llvm::makeArrayRef(Args, NumArgs),
15685                                         AllArgs,
15686                                         CallType, AllowExplicit,
15687                                         IsListInitialization);
15688   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15689 
15690   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15691 
15692   CheckConstructorCall(Constructor, DeclInitType,
15693                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15694                        Proto, Loc);
15695 
15696   return Invalid;
15697 }
15698 
15699 static inline bool
15700 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15701                                        const FunctionDecl *FnDecl) {
15702   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15703   if (isa<NamespaceDecl>(DC)) {
15704     return SemaRef.Diag(FnDecl->getLocation(),
15705                         diag::err_operator_new_delete_declared_in_namespace)
15706       << FnDecl->getDeclName();
15707   }
15708 
15709   if (isa<TranslationUnitDecl>(DC) &&
15710       FnDecl->getStorageClass() == SC_Static) {
15711     return SemaRef.Diag(FnDecl->getLocation(),
15712                         diag::err_operator_new_delete_declared_static)
15713       << FnDecl->getDeclName();
15714   }
15715 
15716   return false;
15717 }
15718 
15719 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15720                                              const PointerType *PtrTy) {
15721   auto &Ctx = SemaRef.Context;
15722   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15723   PtrQuals.removeAddressSpace();
15724   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15725       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15726 }
15727 
15728 static inline bool
15729 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15730                             CanQualType ExpectedResultType,
15731                             CanQualType ExpectedFirstParamType,
15732                             unsigned DependentParamTypeDiag,
15733                             unsigned InvalidParamTypeDiag) {
15734   QualType ResultType =
15735       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15736 
15737   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15738     // The operator is valid on any address space for OpenCL.
15739     // Drop address space from actual and expected result types.
15740     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15741       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15742 
15743     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15744       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15745   }
15746 
15747   // Check that the result type is what we expect.
15748   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15749     // Reject even if the type is dependent; an operator delete function is
15750     // required to have a non-dependent result type.
15751     return SemaRef.Diag(
15752                FnDecl->getLocation(),
15753                ResultType->isDependentType()
15754                    ? diag::err_operator_new_delete_dependent_result_type
15755                    : diag::err_operator_new_delete_invalid_result_type)
15756            << FnDecl->getDeclName() << ExpectedResultType;
15757   }
15758 
15759   // A function template must have at least 2 parameters.
15760   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15761     return SemaRef.Diag(FnDecl->getLocation(),
15762                       diag::err_operator_new_delete_template_too_few_parameters)
15763         << FnDecl->getDeclName();
15764 
15765   // The function decl must have at least 1 parameter.
15766   if (FnDecl->getNumParams() == 0)
15767     return SemaRef.Diag(FnDecl->getLocation(),
15768                         diag::err_operator_new_delete_too_few_parameters)
15769       << FnDecl->getDeclName();
15770 
15771   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15772   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15773     // The operator is valid on any address space for OpenCL.
15774     // Drop address space from actual and expected first parameter types.
15775     if (const auto *PtrTy =
15776             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15777       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15778 
15779     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15780       ExpectedFirstParamType =
15781           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15782   }
15783 
15784   // Check that the first parameter type is what we expect.
15785   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15786       ExpectedFirstParamType) {
15787     // The first parameter type is not allowed to be dependent. As a tentative
15788     // DR resolution, we allow a dependent parameter type if it is the right
15789     // type anyway, to allow destroying operator delete in class templates.
15790     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15791                                                    ? DependentParamTypeDiag
15792                                                    : InvalidParamTypeDiag)
15793            << FnDecl->getDeclName() << ExpectedFirstParamType;
15794   }
15795 
15796   return false;
15797 }
15798 
15799 static bool
15800 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15801   // C++ [basic.stc.dynamic.allocation]p1:
15802   //   A program is ill-formed if an allocation function is declared in a
15803   //   namespace scope other than global scope or declared static in global
15804   //   scope.
15805   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15806     return true;
15807 
15808   CanQualType SizeTy =
15809     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15810 
15811   // C++ [basic.stc.dynamic.allocation]p1:
15812   //  The return type shall be void*. The first parameter shall have type
15813   //  std::size_t.
15814   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15815                                   SizeTy,
15816                                   diag::err_operator_new_dependent_param_type,
15817                                   diag::err_operator_new_param_type))
15818     return true;
15819 
15820   // C++ [basic.stc.dynamic.allocation]p1:
15821   //  The first parameter shall not have an associated default argument.
15822   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15823     return SemaRef.Diag(FnDecl->getLocation(),
15824                         diag::err_operator_new_default_arg)
15825       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15826 
15827   return false;
15828 }
15829 
15830 static bool
15831 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15832   // C++ [basic.stc.dynamic.deallocation]p1:
15833   //   A program is ill-formed if deallocation functions are declared in a
15834   //   namespace scope other than global scope or declared static in global
15835   //   scope.
15836   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15837     return true;
15838 
15839   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15840 
15841   // C++ P0722:
15842   //   Within a class C, the first parameter of a destroying operator delete
15843   //   shall be of type C *. The first parameter of any other deallocation
15844   //   function shall be of type void *.
15845   CanQualType ExpectedFirstParamType =
15846       MD && MD->isDestroyingOperatorDelete()
15847           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15848                 SemaRef.Context.getRecordType(MD->getParent())))
15849           : SemaRef.Context.VoidPtrTy;
15850 
15851   // C++ [basic.stc.dynamic.deallocation]p2:
15852   //   Each deallocation function shall return void
15853   if (CheckOperatorNewDeleteTypes(
15854           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15855           diag::err_operator_delete_dependent_param_type,
15856           diag::err_operator_delete_param_type))
15857     return true;
15858 
15859   // C++ P0722:
15860   //   A destroying operator delete shall be a usual deallocation function.
15861   if (MD && !MD->getParent()->isDependentContext() &&
15862       MD->isDestroyingOperatorDelete() &&
15863       !SemaRef.isUsualDeallocationFunction(MD)) {
15864     SemaRef.Diag(MD->getLocation(),
15865                  diag::err_destroying_operator_delete_not_usual);
15866     return true;
15867   }
15868 
15869   return false;
15870 }
15871 
15872 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15873 /// of this overloaded operator is well-formed. If so, returns false;
15874 /// otherwise, emits appropriate diagnostics and returns true.
15875 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15876   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15877          "Expected an overloaded operator declaration");
15878 
15879   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15880 
15881   // C++ [over.oper]p5:
15882   //   The allocation and deallocation functions, operator new,
15883   //   operator new[], operator delete and operator delete[], are
15884   //   described completely in 3.7.3. The attributes and restrictions
15885   //   found in the rest of this subclause do not apply to them unless
15886   //   explicitly stated in 3.7.3.
15887   if (Op == OO_Delete || Op == OO_Array_Delete)
15888     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15889 
15890   if (Op == OO_New || Op == OO_Array_New)
15891     return CheckOperatorNewDeclaration(*this, FnDecl);
15892 
15893   // C++ [over.oper]p6:
15894   //   An operator function shall either be a non-static member
15895   //   function or be a non-member function and have at least one
15896   //   parameter whose type is a class, a reference to a class, an
15897   //   enumeration, or a reference to an enumeration.
15898   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15899     if (MethodDecl->isStatic())
15900       return Diag(FnDecl->getLocation(),
15901                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15902   } else {
15903     bool ClassOrEnumParam = false;
15904     for (auto Param : FnDecl->parameters()) {
15905       QualType ParamType = Param->getType().getNonReferenceType();
15906       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15907           ParamType->isEnumeralType()) {
15908         ClassOrEnumParam = true;
15909         break;
15910       }
15911     }
15912 
15913     if (!ClassOrEnumParam)
15914       return Diag(FnDecl->getLocation(),
15915                   diag::err_operator_overload_needs_class_or_enum)
15916         << FnDecl->getDeclName();
15917   }
15918 
15919   // C++ [over.oper]p8:
15920   //   An operator function cannot have default arguments (8.3.6),
15921   //   except where explicitly stated below.
15922   //
15923   // Only the function-call operator (C++ [over.call]p1) and the subscript
15924   // operator (CWG2507) allow default arguments.
15925   if (Op != OO_Call) {
15926     ParmVarDecl *FirstDefaultedParam = nullptr;
15927     for (auto Param : FnDecl->parameters()) {
15928       if (Param->hasDefaultArg()) {
15929         FirstDefaultedParam = Param;
15930         break;
15931       }
15932     }
15933     if (FirstDefaultedParam) {
15934       if (Op == OO_Subscript) {
15935         Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15936                                         ? diag::ext_subscript_overload
15937                                         : diag::error_subscript_overload)
15938             << FnDecl->getDeclName() << 1
15939             << FirstDefaultedParam->getDefaultArgRange();
15940       } else {
15941         return Diag(FirstDefaultedParam->getLocation(),
15942                     diag::err_operator_overload_default_arg)
15943                << FnDecl->getDeclName()
15944                << FirstDefaultedParam->getDefaultArgRange();
15945       }
15946     }
15947   }
15948 
15949   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15950     { false, false, false }
15951 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15952     , { Unary, Binary, MemberOnly }
15953 #include "clang/Basic/OperatorKinds.def"
15954   };
15955 
15956   bool CanBeUnaryOperator = OperatorUses[Op][0];
15957   bool CanBeBinaryOperator = OperatorUses[Op][1];
15958   bool MustBeMemberOperator = OperatorUses[Op][2];
15959 
15960   // C++ [over.oper]p8:
15961   //   [...] Operator functions cannot have more or fewer parameters
15962   //   than the number required for the corresponding operator, as
15963   //   described in the rest of this subclause.
15964   unsigned NumParams = FnDecl->getNumParams()
15965                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15966   if (Op != OO_Call && Op != OO_Subscript &&
15967       ((NumParams == 1 && !CanBeUnaryOperator) ||
15968        (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
15969        (NumParams > 2))) {
15970     // We have the wrong number of parameters.
15971     unsigned ErrorKind;
15972     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15973       ErrorKind = 2;  // 2 -> unary or binary.
15974     } else if (CanBeUnaryOperator) {
15975       ErrorKind = 0;  // 0 -> unary
15976     } else {
15977       assert(CanBeBinaryOperator &&
15978              "All non-call overloaded operators are unary or binary!");
15979       ErrorKind = 1;  // 1 -> binary
15980     }
15981     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15982       << FnDecl->getDeclName() << NumParams << ErrorKind;
15983   }
15984 
15985   if (Op == OO_Subscript && NumParams != 2) {
15986     Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15987                                     ? diag::ext_subscript_overload
15988                                     : diag::error_subscript_overload)
15989         << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
15990   }
15991 
15992   // Overloaded operators other than operator() and operator[] cannot be
15993   // variadic.
15994   if (Op != OO_Call &&
15995       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15996     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15997            << FnDecl->getDeclName();
15998   }
15999 
16000   // Some operators must be non-static member functions.
16001   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16002     return Diag(FnDecl->getLocation(),
16003                 diag::err_operator_overload_must_be_member)
16004       << FnDecl->getDeclName();
16005   }
16006 
16007   // C++ [over.inc]p1:
16008   //   The user-defined function called operator++ implements the
16009   //   prefix and postfix ++ operator. If this function is a member
16010   //   function with no parameters, or a non-member function with one
16011   //   parameter of class or enumeration type, it defines the prefix
16012   //   increment operator ++ for objects of that type. If the function
16013   //   is a member function with one parameter (which shall be of type
16014   //   int) or a non-member function with two parameters (the second
16015   //   of which shall be of type int), it defines the postfix
16016   //   increment operator ++ for objects of that type.
16017   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16018     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16019     QualType ParamType = LastParam->getType();
16020 
16021     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16022         !ParamType->isDependentType())
16023       return Diag(LastParam->getLocation(),
16024                   diag::err_operator_overload_post_incdec_must_be_int)
16025         << LastParam->getType() << (Op == OO_MinusMinus);
16026   }
16027 
16028   return false;
16029 }
16030 
16031 static bool
16032 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16033                                           FunctionTemplateDecl *TpDecl) {
16034   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16035 
16036   // Must have one or two template parameters.
16037   if (TemplateParams->size() == 1) {
16038     NonTypeTemplateParmDecl *PmDecl =
16039         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16040 
16041     // The template parameter must be a char parameter pack.
16042     if (PmDecl && PmDecl->isTemplateParameterPack() &&
16043         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16044       return false;
16045 
16046     // C++20 [over.literal]p5:
16047     //   A string literal operator template is a literal operator template
16048     //   whose template-parameter-list comprises a single non-type
16049     //   template-parameter of class type.
16050     //
16051     // As a DR resolution, we also allow placeholders for deduced class
16052     // template specializations.
16053     if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16054         !PmDecl->isTemplateParameterPack() &&
16055         (PmDecl->getType()->isRecordType() ||
16056          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16057       return false;
16058   } else if (TemplateParams->size() == 2) {
16059     TemplateTypeParmDecl *PmType =
16060         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16061     NonTypeTemplateParmDecl *PmArgs =
16062         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16063 
16064     // The second template parameter must be a parameter pack with the
16065     // first template parameter as its type.
16066     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16067         PmArgs->isTemplateParameterPack()) {
16068       const TemplateTypeParmType *TArgs =
16069           PmArgs->getType()->getAs<TemplateTypeParmType>();
16070       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16071           TArgs->getIndex() == PmType->getIndex()) {
16072         if (!SemaRef.inTemplateInstantiation())
16073           SemaRef.Diag(TpDecl->getLocation(),
16074                        diag::ext_string_literal_operator_template);
16075         return false;
16076       }
16077     }
16078   }
16079 
16080   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16081                diag::err_literal_operator_template)
16082       << TpDecl->getTemplateParameters()->getSourceRange();
16083   return true;
16084 }
16085 
16086 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16087 /// of this literal operator function is well-formed. If so, returns
16088 /// false; otherwise, emits appropriate diagnostics and returns true.
16089 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16090   if (isa<CXXMethodDecl>(FnDecl)) {
16091     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16092       << FnDecl->getDeclName();
16093     return true;
16094   }
16095 
16096   if (FnDecl->isExternC()) {
16097     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16098     if (const LinkageSpecDecl *LSD =
16099             FnDecl->getDeclContext()->getExternCContext())
16100       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16101     return true;
16102   }
16103 
16104   // This might be the definition of a literal operator template.
16105   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16106 
16107   // This might be a specialization of a literal operator template.
16108   if (!TpDecl)
16109     TpDecl = FnDecl->getPrimaryTemplate();
16110 
16111   // template <char...> type operator "" name() and
16112   // template <class T, T...> type operator "" name() are the only valid
16113   // template signatures, and the only valid signatures with no parameters.
16114   //
16115   // C++20 also allows template <SomeClass T> type operator "" name().
16116   if (TpDecl) {
16117     if (FnDecl->param_size() != 0) {
16118       Diag(FnDecl->getLocation(),
16119            diag::err_literal_operator_template_with_params);
16120       return true;
16121     }
16122 
16123     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16124       return true;
16125 
16126   } else if (FnDecl->param_size() == 1) {
16127     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16128 
16129     QualType ParamType = Param->getType().getUnqualifiedType();
16130 
16131     // Only unsigned long long int, long double, any character type, and const
16132     // char * are allowed as the only parameters.
16133     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16134         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16135         Context.hasSameType(ParamType, Context.CharTy) ||
16136         Context.hasSameType(ParamType, Context.WideCharTy) ||
16137         Context.hasSameType(ParamType, Context.Char8Ty) ||
16138         Context.hasSameType(ParamType, Context.Char16Ty) ||
16139         Context.hasSameType(ParamType, Context.Char32Ty)) {
16140     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16141       QualType InnerType = Ptr->getPointeeType();
16142 
16143       // Pointer parameter must be a const char *.
16144       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16145                                 Context.CharTy) &&
16146             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16147         Diag(Param->getSourceRange().getBegin(),
16148              diag::err_literal_operator_param)
16149             << ParamType << "'const char *'" << Param->getSourceRange();
16150         return true;
16151       }
16152 
16153     } else if (ParamType->isRealFloatingType()) {
16154       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16155           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16156       return true;
16157 
16158     } else if (ParamType->isIntegerType()) {
16159       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16160           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16161       return true;
16162 
16163     } else {
16164       Diag(Param->getSourceRange().getBegin(),
16165            diag::err_literal_operator_invalid_param)
16166           << ParamType << Param->getSourceRange();
16167       return true;
16168     }
16169 
16170   } else if (FnDecl->param_size() == 2) {
16171     FunctionDecl::param_iterator Param = FnDecl->param_begin();
16172 
16173     // First, verify that the first parameter is correct.
16174 
16175     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16176 
16177     // Two parameter function must have a pointer to const as a
16178     // first parameter; let's strip those qualifiers.
16179     const PointerType *PT = FirstParamType->getAs<PointerType>();
16180 
16181     if (!PT) {
16182       Diag((*Param)->getSourceRange().getBegin(),
16183            diag::err_literal_operator_param)
16184           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16185       return true;
16186     }
16187 
16188     QualType PointeeType = PT->getPointeeType();
16189     // First parameter must be const
16190     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16191       Diag((*Param)->getSourceRange().getBegin(),
16192            diag::err_literal_operator_param)
16193           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16194       return true;
16195     }
16196 
16197     QualType InnerType = PointeeType.getUnqualifiedType();
16198     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16199     // const char32_t* are allowed as the first parameter to a two-parameter
16200     // function
16201     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16202           Context.hasSameType(InnerType, Context.WideCharTy) ||
16203           Context.hasSameType(InnerType, Context.Char8Ty) ||
16204           Context.hasSameType(InnerType, Context.Char16Ty) ||
16205           Context.hasSameType(InnerType, Context.Char32Ty))) {
16206       Diag((*Param)->getSourceRange().getBegin(),
16207            diag::err_literal_operator_param)
16208           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16209       return true;
16210     }
16211 
16212     // Move on to the second and final parameter.
16213     ++Param;
16214 
16215     // The second parameter must be a std::size_t.
16216     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16217     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16218       Diag((*Param)->getSourceRange().getBegin(),
16219            diag::err_literal_operator_param)
16220           << SecondParamType << Context.getSizeType()
16221           << (*Param)->getSourceRange();
16222       return true;
16223     }
16224   } else {
16225     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16226     return true;
16227   }
16228 
16229   // Parameters are good.
16230 
16231   // A parameter-declaration-clause containing a default argument is not
16232   // equivalent to any of the permitted forms.
16233   for (auto Param : FnDecl->parameters()) {
16234     if (Param->hasDefaultArg()) {
16235       Diag(Param->getDefaultArgRange().getBegin(),
16236            diag::err_literal_operator_default_argument)
16237         << Param->getDefaultArgRange();
16238       break;
16239     }
16240   }
16241 
16242   StringRef LiteralName
16243     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16244   if (LiteralName[0] != '_' &&
16245       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16246     // C++11 [usrlit.suffix]p1:
16247     //   Literal suffix identifiers that do not start with an underscore
16248     //   are reserved for future standardization.
16249     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16250       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16251   }
16252 
16253   return false;
16254 }
16255 
16256 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16257 /// linkage specification, including the language and (if present)
16258 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16259 /// language string literal. LBraceLoc, if valid, provides the location of
16260 /// the '{' brace. Otherwise, this linkage specification does not
16261 /// have any braces.
16262 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16263                                            Expr *LangStr,
16264                                            SourceLocation LBraceLoc) {
16265   StringLiteral *Lit = cast<StringLiteral>(LangStr);
16266   if (!Lit->isAscii()) {
16267     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16268       << LangStr->getSourceRange();
16269     return nullptr;
16270   }
16271 
16272   StringRef Lang = Lit->getString();
16273   LinkageSpecDecl::LanguageIDs Language;
16274   if (Lang == "C")
16275     Language = LinkageSpecDecl::lang_c;
16276   else if (Lang == "C++")
16277     Language = LinkageSpecDecl::lang_cxx;
16278   else {
16279     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16280       << LangStr->getSourceRange();
16281     return nullptr;
16282   }
16283 
16284   // FIXME: Add all the various semantics of linkage specifications
16285 
16286   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16287                                                LangStr->getExprLoc(), Language,
16288                                                LBraceLoc.isValid());
16289 
16290   /// C++ [module.unit]p7.2.3
16291   /// - Otherwise, if the declaration
16292   ///   - ...
16293   ///   - ...
16294   ///   - appears within a linkage-specification,
16295   ///   it is attached to the global module.
16296   ///
16297   /// If the declaration is already in global module fragment, we don't
16298   /// need to attach it again.
16299   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16300     Module *GlobalModule =
16301         PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
16302     D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16303     D->setLocalOwningModule(GlobalModule);
16304   }
16305 
16306   CurContext->addDecl(D);
16307   PushDeclContext(S, D);
16308   return D;
16309 }
16310 
16311 /// ActOnFinishLinkageSpecification - Complete the definition of
16312 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16313 /// valid, it's the position of the closing '}' brace in a linkage
16314 /// specification that uses braces.
16315 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16316                                             Decl *LinkageSpec,
16317                                             SourceLocation RBraceLoc) {
16318   if (RBraceLoc.isValid()) {
16319     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16320     LSDecl->setRBraceLoc(RBraceLoc);
16321   }
16322 
16323   // If the current module doesn't has Parent, it implies that the
16324   // LinkageSpec isn't in the module created by itself. So we don't
16325   // need to pop it.
16326   if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16327       getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
16328     PopGlobalModuleFragment();
16329 
16330   PopDeclContext();
16331   return LinkageSpec;
16332 }
16333 
16334 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16335                                   const ParsedAttributesView &AttrList,
16336                                   SourceLocation SemiLoc) {
16337   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16338   // Attribute declarations appertain to empty declaration so we handle
16339   // them here.
16340   ProcessDeclAttributeList(S, ED, AttrList);
16341 
16342   CurContext->addDecl(ED);
16343   return ED;
16344 }
16345 
16346 /// Perform semantic analysis for the variable declaration that
16347 /// occurs within a C++ catch clause, returning the newly-created
16348 /// variable.
16349 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16350                                          TypeSourceInfo *TInfo,
16351                                          SourceLocation StartLoc,
16352                                          SourceLocation Loc,
16353                                          IdentifierInfo *Name) {
16354   bool Invalid = false;
16355   QualType ExDeclType = TInfo->getType();
16356 
16357   // Arrays and functions decay.
16358   if (ExDeclType->isArrayType())
16359     ExDeclType = Context.getArrayDecayedType(ExDeclType);
16360   else if (ExDeclType->isFunctionType())
16361     ExDeclType = Context.getPointerType(ExDeclType);
16362 
16363   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16364   // The exception-declaration shall not denote a pointer or reference to an
16365   // incomplete type, other than [cv] void*.
16366   // N2844 forbids rvalue references.
16367   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16368     Diag(Loc, diag::err_catch_rvalue_ref);
16369     Invalid = true;
16370   }
16371 
16372   if (ExDeclType->isVariablyModifiedType()) {
16373     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16374     Invalid = true;
16375   }
16376 
16377   QualType BaseType = ExDeclType;
16378   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16379   unsigned DK = diag::err_catch_incomplete;
16380   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16381     BaseType = Ptr->getPointeeType();
16382     Mode = 1;
16383     DK = diag::err_catch_incomplete_ptr;
16384   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16385     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16386     BaseType = Ref->getPointeeType();
16387     Mode = 2;
16388     DK = diag::err_catch_incomplete_ref;
16389   }
16390   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16391       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16392     Invalid = true;
16393 
16394   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16395     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16396     Invalid = true;
16397   }
16398 
16399   if (!Invalid && !ExDeclType->isDependentType() &&
16400       RequireNonAbstractType(Loc, ExDeclType,
16401                              diag::err_abstract_type_in_decl,
16402                              AbstractVariableType))
16403     Invalid = true;
16404 
16405   // Only the non-fragile NeXT runtime currently supports C++ catches
16406   // of ObjC types, and no runtime supports catching ObjC types by value.
16407   if (!Invalid && getLangOpts().ObjC) {
16408     QualType T = ExDeclType;
16409     if (const ReferenceType *RT = T->getAs<ReferenceType>())
16410       T = RT->getPointeeType();
16411 
16412     if (T->isObjCObjectType()) {
16413       Diag(Loc, diag::err_objc_object_catch);
16414       Invalid = true;
16415     } else if (T->isObjCObjectPointerType()) {
16416       // FIXME: should this be a test for macosx-fragile specifically?
16417       if (getLangOpts().ObjCRuntime.isFragile())
16418         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16419     }
16420   }
16421 
16422   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16423                                     ExDeclType, TInfo, SC_None);
16424   ExDecl->setExceptionVariable(true);
16425 
16426   // In ARC, infer 'retaining' for variables of retainable type.
16427   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16428     Invalid = true;
16429 
16430   if (!Invalid && !ExDeclType->isDependentType()) {
16431     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16432       // Insulate this from anything else we might currently be parsing.
16433       EnterExpressionEvaluationContext scope(
16434           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16435 
16436       // C++ [except.handle]p16:
16437       //   The object declared in an exception-declaration or, if the
16438       //   exception-declaration does not specify a name, a temporary (12.2) is
16439       //   copy-initialized (8.5) from the exception object. [...]
16440       //   The object is destroyed when the handler exits, after the destruction
16441       //   of any automatic objects initialized within the handler.
16442       //
16443       // We just pretend to initialize the object with itself, then make sure
16444       // it can be destroyed later.
16445       QualType initType = Context.getExceptionObjectType(ExDeclType);
16446 
16447       InitializedEntity entity =
16448         InitializedEntity::InitializeVariable(ExDecl);
16449       InitializationKind initKind =
16450         InitializationKind::CreateCopy(Loc, SourceLocation());
16451 
16452       Expr *opaqueValue =
16453         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16454       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16455       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16456       if (result.isInvalid())
16457         Invalid = true;
16458       else {
16459         // If the constructor used was non-trivial, set this as the
16460         // "initializer".
16461         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16462         if (!construct->getConstructor()->isTrivial()) {
16463           Expr *init = MaybeCreateExprWithCleanups(construct);
16464           ExDecl->setInit(init);
16465         }
16466 
16467         // And make sure it's destructable.
16468         FinalizeVarWithDestructor(ExDecl, recordType);
16469       }
16470     }
16471   }
16472 
16473   if (Invalid)
16474     ExDecl->setInvalidDecl();
16475 
16476   return ExDecl;
16477 }
16478 
16479 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16480 /// handler.
16481 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16482   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16483   bool Invalid = D.isInvalidType();
16484 
16485   // Check for unexpanded parameter packs.
16486   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16487                                       UPPC_ExceptionType)) {
16488     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16489                                              D.getIdentifierLoc());
16490     Invalid = true;
16491   }
16492 
16493   IdentifierInfo *II = D.getIdentifier();
16494   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16495                                              LookupOrdinaryName,
16496                                              ForVisibleRedeclaration)) {
16497     // The scope should be freshly made just for us. There is just no way
16498     // it contains any previous declaration, except for function parameters in
16499     // a function-try-block's catch statement.
16500     assert(!S->isDeclScope(PrevDecl));
16501     if (isDeclInScope(PrevDecl, CurContext, S)) {
16502       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16503         << D.getIdentifier();
16504       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16505       Invalid = true;
16506     } else if (PrevDecl->isTemplateParameter())
16507       // Maybe we will complain about the shadowed template parameter.
16508       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16509   }
16510 
16511   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16512     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16513       << D.getCXXScopeSpec().getRange();
16514     Invalid = true;
16515   }
16516 
16517   VarDecl *ExDecl = BuildExceptionDeclaration(
16518       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16519   if (Invalid)
16520     ExDecl->setInvalidDecl();
16521 
16522   // Add the exception declaration into this scope.
16523   if (II)
16524     PushOnScopeChains(ExDecl, S);
16525   else
16526     CurContext->addDecl(ExDecl);
16527 
16528   ProcessDeclAttributes(S, ExDecl, D);
16529   return ExDecl;
16530 }
16531 
16532 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16533                                          Expr *AssertExpr,
16534                                          Expr *AssertMessageExpr,
16535                                          SourceLocation RParenLoc) {
16536   StringLiteral *AssertMessage =
16537       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16538 
16539   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16540     return nullptr;
16541 
16542   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16543                                       AssertMessage, RParenLoc, false);
16544 }
16545 
16546 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16547                                          Expr *AssertExpr,
16548                                          StringLiteral *AssertMessage,
16549                                          SourceLocation RParenLoc,
16550                                          bool Failed) {
16551   assert(AssertExpr != nullptr && "Expected non-null condition");
16552   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16553       !Failed) {
16554     // In a static_assert-declaration, the constant-expression shall be a
16555     // constant expression that can be contextually converted to bool.
16556     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16557     if (Converted.isInvalid())
16558       Failed = true;
16559 
16560     ExprResult FullAssertExpr =
16561         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16562                             /*DiscardedValue*/ false,
16563                             /*IsConstexpr*/ true);
16564     if (FullAssertExpr.isInvalid())
16565       Failed = true;
16566     else
16567       AssertExpr = FullAssertExpr.get();
16568 
16569     llvm::APSInt Cond;
16570     if (!Failed && VerifyIntegerConstantExpression(
16571                        AssertExpr, &Cond,
16572                        diag::err_static_assert_expression_is_not_constant)
16573                        .isInvalid())
16574       Failed = true;
16575 
16576     if (!Failed && !Cond) {
16577       SmallString<256> MsgBuffer;
16578       llvm::raw_svector_ostream Msg(MsgBuffer);
16579       if (AssertMessage)
16580         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16581 
16582       Expr *InnerCond = nullptr;
16583       std::string InnerCondDescription;
16584       std::tie(InnerCond, InnerCondDescription) =
16585         findFailedBooleanCondition(Converted.get());
16586       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16587         // Drill down into concept specialization expressions to see why they
16588         // weren't satisfied.
16589         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16590           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16591         ConstraintSatisfaction Satisfaction;
16592         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16593           DiagnoseUnsatisfiedConstraint(Satisfaction);
16594       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16595                            && !isa<IntegerLiteral>(InnerCond)) {
16596         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16597           << InnerCondDescription << !AssertMessage
16598           << Msg.str() << InnerCond->getSourceRange();
16599       } else {
16600         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16601           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16602       }
16603       Failed = true;
16604     }
16605   } else {
16606     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16607                                                     /*DiscardedValue*/false,
16608                                                     /*IsConstexpr*/true);
16609     if (FullAssertExpr.isInvalid())
16610       Failed = true;
16611     else
16612       AssertExpr = FullAssertExpr.get();
16613   }
16614 
16615   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16616                                         AssertExpr, AssertMessage, RParenLoc,
16617                                         Failed);
16618 
16619   CurContext->addDecl(Decl);
16620   return Decl;
16621 }
16622 
16623 /// Perform semantic analysis of the given friend type declaration.
16624 ///
16625 /// \returns A friend declaration that.
16626 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16627                                       SourceLocation FriendLoc,
16628                                       TypeSourceInfo *TSInfo) {
16629   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16630 
16631   QualType T = TSInfo->getType();
16632   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16633 
16634   // C++03 [class.friend]p2:
16635   //   An elaborated-type-specifier shall be used in a friend declaration
16636   //   for a class.*
16637   //
16638   //   * The class-key of the elaborated-type-specifier is required.
16639   if (!CodeSynthesisContexts.empty()) {
16640     // Do not complain about the form of friend template types during any kind
16641     // of code synthesis. For template instantiation, we will have complained
16642     // when the template was defined.
16643   } else {
16644     if (!T->isElaboratedTypeSpecifier()) {
16645       // If we evaluated the type to a record type, suggest putting
16646       // a tag in front.
16647       if (const RecordType *RT = T->getAs<RecordType>()) {
16648         RecordDecl *RD = RT->getDecl();
16649 
16650         SmallString<16> InsertionText(" ");
16651         InsertionText += RD->getKindName();
16652 
16653         Diag(TypeRange.getBegin(),
16654              getLangOpts().CPlusPlus11 ?
16655                diag::warn_cxx98_compat_unelaborated_friend_type :
16656                diag::ext_unelaborated_friend_type)
16657           << (unsigned) RD->getTagKind()
16658           << T
16659           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16660                                         InsertionText);
16661       } else {
16662         Diag(FriendLoc,
16663              getLangOpts().CPlusPlus11 ?
16664                diag::warn_cxx98_compat_nonclass_type_friend :
16665                diag::ext_nonclass_type_friend)
16666           << T
16667           << TypeRange;
16668       }
16669     } else if (T->getAs<EnumType>()) {
16670       Diag(FriendLoc,
16671            getLangOpts().CPlusPlus11 ?
16672              diag::warn_cxx98_compat_enum_friend :
16673              diag::ext_enum_friend)
16674         << T
16675         << TypeRange;
16676     }
16677 
16678     // C++11 [class.friend]p3:
16679     //   A friend declaration that does not declare a function shall have one
16680     //   of the following forms:
16681     //     friend elaborated-type-specifier ;
16682     //     friend simple-type-specifier ;
16683     //     friend typename-specifier ;
16684     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16685       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16686   }
16687 
16688   //   If the type specifier in a friend declaration designates a (possibly
16689   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16690   //   the friend declaration is ignored.
16691   return FriendDecl::Create(Context, CurContext,
16692                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16693                             FriendLoc);
16694 }
16695 
16696 /// Handle a friend tag declaration where the scope specifier was
16697 /// templated.
16698 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16699                                     unsigned TagSpec, SourceLocation TagLoc,
16700                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16701                                     SourceLocation NameLoc,
16702                                     const ParsedAttributesView &Attr,
16703                                     MultiTemplateParamsArg TempParamLists) {
16704   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16705 
16706   bool IsMemberSpecialization = false;
16707   bool Invalid = false;
16708 
16709   if (TemplateParameterList *TemplateParams =
16710           MatchTemplateParametersToScopeSpecifier(
16711               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16712               IsMemberSpecialization, Invalid)) {
16713     if (TemplateParams->size() > 0) {
16714       // This is a declaration of a class template.
16715       if (Invalid)
16716         return nullptr;
16717 
16718       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16719                                 NameLoc, Attr, TemplateParams, AS_public,
16720                                 /*ModulePrivateLoc=*/SourceLocation(),
16721                                 FriendLoc, TempParamLists.size() - 1,
16722                                 TempParamLists.data()).get();
16723     } else {
16724       // The "template<>" header is extraneous.
16725       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16726         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16727       IsMemberSpecialization = true;
16728     }
16729   }
16730 
16731   if (Invalid) return nullptr;
16732 
16733   bool isAllExplicitSpecializations = true;
16734   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16735     if (TempParamLists[I]->size()) {
16736       isAllExplicitSpecializations = false;
16737       break;
16738     }
16739   }
16740 
16741   // FIXME: don't ignore attributes.
16742 
16743   // If it's explicit specializations all the way down, just forget
16744   // about the template header and build an appropriate non-templated
16745   // friend.  TODO: for source fidelity, remember the headers.
16746   if (isAllExplicitSpecializations) {
16747     if (SS.isEmpty()) {
16748       bool Owned = false;
16749       bool IsDependent = false;
16750       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16751                       Attr, AS_public,
16752                       /*ModulePrivateLoc=*/SourceLocation(),
16753                       MultiTemplateParamsArg(), Owned, IsDependent,
16754                       /*ScopedEnumKWLoc=*/SourceLocation(),
16755                       /*ScopedEnumUsesClassTag=*/false,
16756                       /*UnderlyingType=*/TypeResult(),
16757                       /*IsTypeSpecifier=*/false,
16758                       /*IsTemplateParamOrArg=*/false);
16759     }
16760 
16761     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16762     ElaboratedTypeKeyword Keyword
16763       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16764     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16765                                    *Name, NameLoc);
16766     if (T.isNull())
16767       return nullptr;
16768 
16769     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16770     if (isa<DependentNameType>(T)) {
16771       DependentNameTypeLoc TL =
16772           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16773       TL.setElaboratedKeywordLoc(TagLoc);
16774       TL.setQualifierLoc(QualifierLoc);
16775       TL.setNameLoc(NameLoc);
16776     } else {
16777       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16778       TL.setElaboratedKeywordLoc(TagLoc);
16779       TL.setQualifierLoc(QualifierLoc);
16780       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16781     }
16782 
16783     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16784                                             TSI, FriendLoc, TempParamLists);
16785     Friend->setAccess(AS_public);
16786     CurContext->addDecl(Friend);
16787     return Friend;
16788   }
16789 
16790   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16791 
16792 
16793 
16794   // Handle the case of a templated-scope friend class.  e.g.
16795   //   template <class T> class A<T>::B;
16796   // FIXME: we don't support these right now.
16797   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16798     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16799   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16800   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16801   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16802   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16803   TL.setElaboratedKeywordLoc(TagLoc);
16804   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16805   TL.setNameLoc(NameLoc);
16806 
16807   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16808                                           TSI, FriendLoc, TempParamLists);
16809   Friend->setAccess(AS_public);
16810   Friend->setUnsupportedFriend(true);
16811   CurContext->addDecl(Friend);
16812   return Friend;
16813 }
16814 
16815 /// Handle a friend type declaration.  This works in tandem with
16816 /// ActOnTag.
16817 ///
16818 /// Notes on friend class templates:
16819 ///
16820 /// We generally treat friend class declarations as if they were
16821 /// declaring a class.  So, for example, the elaborated type specifier
16822 /// in a friend declaration is required to obey the restrictions of a
16823 /// class-head (i.e. no typedefs in the scope chain), template
16824 /// parameters are required to match up with simple template-ids, &c.
16825 /// However, unlike when declaring a template specialization, it's
16826 /// okay to refer to a template specialization without an empty
16827 /// template parameter declaration, e.g.
16828 ///   friend class A<T>::B<unsigned>;
16829 /// We permit this as a special case; if there are any template
16830 /// parameters present at all, require proper matching, i.e.
16831 ///   template <> template \<class T> friend class A<int>::B;
16832 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16833                                 MultiTemplateParamsArg TempParams) {
16834   SourceLocation Loc = DS.getBeginLoc();
16835 
16836   assert(DS.isFriendSpecified());
16837   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16838 
16839   // C++ [class.friend]p3:
16840   // A friend declaration that does not declare a function shall have one of
16841   // the following forms:
16842   //     friend elaborated-type-specifier ;
16843   //     friend simple-type-specifier ;
16844   //     friend typename-specifier ;
16845   //
16846   // Any declaration with a type qualifier does not have that form. (It's
16847   // legal to specify a qualified type as a friend, you just can't write the
16848   // keywords.)
16849   if (DS.getTypeQualifiers()) {
16850     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16851       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16852     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16853       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16854     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16855       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16856     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16857       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16858     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16859       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16860   }
16861 
16862   // Try to convert the decl specifier to a type.  This works for
16863   // friend templates because ActOnTag never produces a ClassTemplateDecl
16864   // for a TUK_Friend.
16865   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16866   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16867   QualType T = TSI->getType();
16868   if (TheDeclarator.isInvalidType())
16869     return nullptr;
16870 
16871   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16872     return nullptr;
16873 
16874   // This is definitely an error in C++98.  It's probably meant to
16875   // be forbidden in C++0x, too, but the specification is just
16876   // poorly written.
16877   //
16878   // The problem is with declarations like the following:
16879   //   template <T> friend A<T>::foo;
16880   // where deciding whether a class C is a friend or not now hinges
16881   // on whether there exists an instantiation of A that causes
16882   // 'foo' to equal C.  There are restrictions on class-heads
16883   // (which we declare (by fiat) elaborated friend declarations to
16884   // be) that makes this tractable.
16885   //
16886   // FIXME: handle "template <> friend class A<T>;", which
16887   // is possibly well-formed?  Who even knows?
16888   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16889     Diag(Loc, diag::err_tagless_friend_type_template)
16890       << DS.getSourceRange();
16891     return nullptr;
16892   }
16893 
16894   // C++98 [class.friend]p1: A friend of a class is a function
16895   //   or class that is not a member of the class . . .
16896   // This is fixed in DR77, which just barely didn't make the C++03
16897   // deadline.  It's also a very silly restriction that seriously
16898   // affects inner classes and which nobody else seems to implement;
16899   // thus we never diagnose it, not even in -pedantic.
16900   //
16901   // But note that we could warn about it: it's always useless to
16902   // friend one of your own members (it's not, however, worthless to
16903   // friend a member of an arbitrary specialization of your template).
16904 
16905   Decl *D;
16906   if (!TempParams.empty())
16907     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16908                                    TempParams,
16909                                    TSI,
16910                                    DS.getFriendSpecLoc());
16911   else
16912     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16913 
16914   if (!D)
16915     return nullptr;
16916 
16917   D->setAccess(AS_public);
16918   CurContext->addDecl(D);
16919 
16920   return D;
16921 }
16922 
16923 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16924                                         MultiTemplateParamsArg TemplateParams) {
16925   const DeclSpec &DS = D.getDeclSpec();
16926 
16927   assert(DS.isFriendSpecified());
16928   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16929 
16930   SourceLocation Loc = D.getIdentifierLoc();
16931   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16932 
16933   // C++ [class.friend]p1
16934   //   A friend of a class is a function or class....
16935   // Note that this sees through typedefs, which is intended.
16936   // It *doesn't* see through dependent types, which is correct
16937   // according to [temp.arg.type]p3:
16938   //   If a declaration acquires a function type through a
16939   //   type dependent on a template-parameter and this causes
16940   //   a declaration that does not use the syntactic form of a
16941   //   function declarator to have a function type, the program
16942   //   is ill-formed.
16943   if (!TInfo->getType()->isFunctionType()) {
16944     Diag(Loc, diag::err_unexpected_friend);
16945 
16946     // It might be worthwhile to try to recover by creating an
16947     // appropriate declaration.
16948     return nullptr;
16949   }
16950 
16951   // C++ [namespace.memdef]p3
16952   //  - If a friend declaration in a non-local class first declares a
16953   //    class or function, the friend class or function is a member
16954   //    of the innermost enclosing namespace.
16955   //  - The name of the friend is not found by simple name lookup
16956   //    until a matching declaration is provided in that namespace
16957   //    scope (either before or after the class declaration granting
16958   //    friendship).
16959   //  - If a friend function is called, its name may be found by the
16960   //    name lookup that considers functions from namespaces and
16961   //    classes associated with the types of the function arguments.
16962   //  - When looking for a prior declaration of a class or a function
16963   //    declared as a friend, scopes outside the innermost enclosing
16964   //    namespace scope are not considered.
16965 
16966   CXXScopeSpec &SS = D.getCXXScopeSpec();
16967   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16968   assert(NameInfo.getName());
16969 
16970   // Check for unexpanded parameter packs.
16971   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16972       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16973       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16974     return nullptr;
16975 
16976   // The context we found the declaration in, or in which we should
16977   // create the declaration.
16978   DeclContext *DC;
16979   Scope *DCScope = S;
16980   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16981                         ForExternalRedeclaration);
16982 
16983   // There are five cases here.
16984   //   - There's no scope specifier and we're in a local class. Only look
16985   //     for functions declared in the immediately-enclosing block scope.
16986   // We recover from invalid scope qualifiers as if they just weren't there.
16987   FunctionDecl *FunctionContainingLocalClass = nullptr;
16988   if ((SS.isInvalid() || !SS.isSet()) &&
16989       (FunctionContainingLocalClass =
16990            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16991     // C++11 [class.friend]p11:
16992     //   If a friend declaration appears in a local class and the name
16993     //   specified is an unqualified name, a prior declaration is
16994     //   looked up without considering scopes that are outside the
16995     //   innermost enclosing non-class scope. For a friend function
16996     //   declaration, if there is no prior declaration, the program is
16997     //   ill-formed.
16998 
16999     // Find the innermost enclosing non-class scope. This is the block
17000     // scope containing the local class definition (or for a nested class,
17001     // the outer local class).
17002     DCScope = S->getFnParent();
17003 
17004     // Look up the function name in the scope.
17005     Previous.clear(LookupLocalFriendName);
17006     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17007 
17008     if (!Previous.empty()) {
17009       // All possible previous declarations must have the same context:
17010       // either they were declared at block scope or they are members of
17011       // one of the enclosing local classes.
17012       DC = Previous.getRepresentativeDecl()->getDeclContext();
17013     } else {
17014       // This is ill-formed, but provide the context that we would have
17015       // declared the function in, if we were permitted to, for error recovery.
17016       DC = FunctionContainingLocalClass;
17017     }
17018     adjustContextForLocalExternDecl(DC);
17019 
17020     // C++ [class.friend]p6:
17021     //   A function can be defined in a friend declaration of a class if and
17022     //   only if the class is a non-local class (9.8), the function name is
17023     //   unqualified, and the function has namespace scope.
17024     if (D.isFunctionDefinition()) {
17025       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17026     }
17027 
17028   //   - There's no scope specifier, in which case we just go to the
17029   //     appropriate scope and look for a function or function template
17030   //     there as appropriate.
17031   } else if (SS.isInvalid() || !SS.isSet()) {
17032     // C++11 [namespace.memdef]p3:
17033     //   If the name in a friend declaration is neither qualified nor
17034     //   a template-id and the declaration is a function or an
17035     //   elaborated-type-specifier, the lookup to determine whether
17036     //   the entity has been previously declared shall not consider
17037     //   any scopes outside the innermost enclosing namespace.
17038     bool isTemplateId =
17039         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17040 
17041     // Find the appropriate context according to the above.
17042     DC = CurContext;
17043 
17044     // Skip class contexts.  If someone can cite chapter and verse
17045     // for this behavior, that would be nice --- it's what GCC and
17046     // EDG do, and it seems like a reasonable intent, but the spec
17047     // really only says that checks for unqualified existing
17048     // declarations should stop at the nearest enclosing namespace,
17049     // not that they should only consider the nearest enclosing
17050     // namespace.
17051     while (DC->isRecord())
17052       DC = DC->getParent();
17053 
17054     DeclContext *LookupDC = DC->getNonTransparentContext();
17055     while (true) {
17056       LookupQualifiedName(Previous, LookupDC);
17057 
17058       if (!Previous.empty()) {
17059         DC = LookupDC;
17060         break;
17061       }
17062 
17063       if (isTemplateId) {
17064         if (isa<TranslationUnitDecl>(LookupDC)) break;
17065       } else {
17066         if (LookupDC->isFileContext()) break;
17067       }
17068       LookupDC = LookupDC->getParent();
17069     }
17070 
17071     DCScope = getScopeForDeclContext(S, DC);
17072 
17073   //   - There's a non-dependent scope specifier, in which case we
17074   //     compute it and do a previous lookup there for a function
17075   //     or function template.
17076   } else if (!SS.getScopeRep()->isDependent()) {
17077     DC = computeDeclContext(SS);
17078     if (!DC) return nullptr;
17079 
17080     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17081 
17082     LookupQualifiedName(Previous, DC);
17083 
17084     // C++ [class.friend]p1: A friend of a class is a function or
17085     //   class that is not a member of the class . . .
17086     if (DC->Equals(CurContext))
17087       Diag(DS.getFriendSpecLoc(),
17088            getLangOpts().CPlusPlus11 ?
17089              diag::warn_cxx98_compat_friend_is_member :
17090              diag::err_friend_is_member);
17091 
17092     if (D.isFunctionDefinition()) {
17093       // C++ [class.friend]p6:
17094       //   A function can be defined in a friend declaration of a class if and
17095       //   only if the class is a non-local class (9.8), the function name is
17096       //   unqualified, and the function has namespace scope.
17097       //
17098       // FIXME: We should only do this if the scope specifier names the
17099       // innermost enclosing namespace; otherwise the fixit changes the
17100       // meaning of the code.
17101       SemaDiagnosticBuilder DB
17102         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17103 
17104       DB << SS.getScopeRep();
17105       if (DC->isFileContext())
17106         DB << FixItHint::CreateRemoval(SS.getRange());
17107       SS.clear();
17108     }
17109 
17110   //   - There's a scope specifier that does not match any template
17111   //     parameter lists, in which case we use some arbitrary context,
17112   //     create a method or method template, and wait for instantiation.
17113   //   - There's a scope specifier that does match some template
17114   //     parameter lists, which we don't handle right now.
17115   } else {
17116     if (D.isFunctionDefinition()) {
17117       // C++ [class.friend]p6:
17118       //   A function can be defined in a friend declaration of a class if and
17119       //   only if the class is a non-local class (9.8), the function name is
17120       //   unqualified, and the function has namespace scope.
17121       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17122         << SS.getScopeRep();
17123     }
17124 
17125     DC = CurContext;
17126     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17127   }
17128 
17129   if (!DC->isRecord()) {
17130     int DiagArg = -1;
17131     switch (D.getName().getKind()) {
17132     case UnqualifiedIdKind::IK_ConstructorTemplateId:
17133     case UnqualifiedIdKind::IK_ConstructorName:
17134       DiagArg = 0;
17135       break;
17136     case UnqualifiedIdKind::IK_DestructorName:
17137       DiagArg = 1;
17138       break;
17139     case UnqualifiedIdKind::IK_ConversionFunctionId:
17140       DiagArg = 2;
17141       break;
17142     case UnqualifiedIdKind::IK_DeductionGuideName:
17143       DiagArg = 3;
17144       break;
17145     case UnqualifiedIdKind::IK_Identifier:
17146     case UnqualifiedIdKind::IK_ImplicitSelfParam:
17147     case UnqualifiedIdKind::IK_LiteralOperatorId:
17148     case UnqualifiedIdKind::IK_OperatorFunctionId:
17149     case UnqualifiedIdKind::IK_TemplateId:
17150       break;
17151     }
17152     // This implies that it has to be an operator or function.
17153     if (DiagArg >= 0) {
17154       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17155       return nullptr;
17156     }
17157   }
17158 
17159   // FIXME: This is an egregious hack to cope with cases where the scope stack
17160   // does not contain the declaration context, i.e., in an out-of-line
17161   // definition of a class.
17162   Scope FakeDCScope(S, Scope::DeclScope, Diags);
17163   if (!DCScope) {
17164     FakeDCScope.setEntity(DC);
17165     DCScope = &FakeDCScope;
17166   }
17167 
17168   bool AddToScope = true;
17169   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17170                                           TemplateParams, AddToScope);
17171   if (!ND) return nullptr;
17172 
17173   assert(ND->getLexicalDeclContext() == CurContext);
17174 
17175   // If we performed typo correction, we might have added a scope specifier
17176   // and changed the decl context.
17177   DC = ND->getDeclContext();
17178 
17179   // Add the function declaration to the appropriate lookup tables,
17180   // adjusting the redeclarations list as necessary.  We don't
17181   // want to do this yet if the friending class is dependent.
17182   //
17183   // Also update the scope-based lookup if the target context's
17184   // lookup context is in lexical scope.
17185   if (!CurContext->isDependentContext()) {
17186     DC = DC->getRedeclContext();
17187     DC->makeDeclVisibleInContext(ND);
17188     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17189       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17190   }
17191 
17192   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17193                                        D.getIdentifierLoc(), ND,
17194                                        DS.getFriendSpecLoc());
17195   FrD->setAccess(AS_public);
17196   CurContext->addDecl(FrD);
17197 
17198   if (ND->isInvalidDecl()) {
17199     FrD->setInvalidDecl();
17200   } else {
17201     if (DC->isRecord()) CheckFriendAccess(ND);
17202 
17203     FunctionDecl *FD;
17204     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17205       FD = FTD->getTemplatedDecl();
17206     else
17207       FD = cast<FunctionDecl>(ND);
17208 
17209     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17210     // default argument expression, that declaration shall be a definition
17211     // and shall be the only declaration of the function or function
17212     // template in the translation unit.
17213     if (functionDeclHasDefaultArgument(FD)) {
17214       // We can't look at FD->getPreviousDecl() because it may not have been set
17215       // if we're in a dependent context. If the function is known to be a
17216       // redeclaration, we will have narrowed Previous down to the right decl.
17217       if (D.isRedeclaration()) {
17218         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17219         Diag(Previous.getRepresentativeDecl()->getLocation(),
17220              diag::note_previous_declaration);
17221       } else if (!D.isFunctionDefinition())
17222         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17223     }
17224 
17225     // Mark templated-scope function declarations as unsupported.
17226     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17227       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17228         << SS.getScopeRep() << SS.getRange()
17229         << cast<CXXRecordDecl>(CurContext);
17230       FrD->setUnsupportedFriend(true);
17231     }
17232   }
17233 
17234   warnOnReservedIdentifier(ND);
17235 
17236   return ND;
17237 }
17238 
17239 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17240   AdjustDeclIfTemplate(Dcl);
17241 
17242   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17243   if (!Fn) {
17244     Diag(DelLoc, diag::err_deleted_non_function);
17245     return;
17246   }
17247 
17248   // Deleted function does not have a body.
17249   Fn->setWillHaveBody(false);
17250 
17251   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17252     // Don't consider the implicit declaration we generate for explicit
17253     // specializations. FIXME: Do not generate these implicit declarations.
17254     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17255          Prev->getPreviousDecl()) &&
17256         !Prev->isDefined()) {
17257       Diag(DelLoc, diag::err_deleted_decl_not_first);
17258       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17259            Prev->isImplicit() ? diag::note_previous_implicit_declaration
17260                               : diag::note_previous_declaration);
17261       // We can't recover from this; the declaration might have already
17262       // been used.
17263       Fn->setInvalidDecl();
17264       return;
17265     }
17266 
17267     // To maintain the invariant that functions are only deleted on their first
17268     // declaration, mark the implicitly-instantiated declaration of the
17269     // explicitly-specialized function as deleted instead of marking the
17270     // instantiated redeclaration.
17271     Fn = Fn->getCanonicalDecl();
17272   }
17273 
17274   // dllimport/dllexport cannot be deleted.
17275   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17276     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17277     Fn->setInvalidDecl();
17278   }
17279 
17280   // C++11 [basic.start.main]p3:
17281   //   A program that defines main as deleted [...] is ill-formed.
17282   if (Fn->isMain())
17283     Diag(DelLoc, diag::err_deleted_main);
17284 
17285   // C++11 [dcl.fct.def.delete]p4:
17286   //  A deleted function is implicitly inline.
17287   Fn->setImplicitlyInline();
17288   Fn->setDeletedAsWritten();
17289 }
17290 
17291 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17292   if (!Dcl || Dcl->isInvalidDecl())
17293     return;
17294 
17295   auto *FD = dyn_cast<FunctionDecl>(Dcl);
17296   if (!FD) {
17297     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17298       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17299         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17300         return;
17301       }
17302     }
17303 
17304     Diag(DefaultLoc, diag::err_default_special_members)
17305         << getLangOpts().CPlusPlus20;
17306     return;
17307   }
17308 
17309   // Reject if this can't possibly be a defaultable function.
17310   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17311   if (!DefKind &&
17312       // A dependent function that doesn't locally look defaultable can
17313       // still instantiate to a defaultable function if it's a constructor
17314       // or assignment operator.
17315       (!FD->isDependentContext() ||
17316        (!isa<CXXConstructorDecl>(FD) &&
17317         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17318     Diag(DefaultLoc, diag::err_default_special_members)
17319         << getLangOpts().CPlusPlus20;
17320     return;
17321   }
17322 
17323   // Issue compatibility warning. We already warned if the operator is
17324   // 'operator<=>' when parsing the '<=>' token.
17325   if (DefKind.isComparison() &&
17326       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17327     Diag(DefaultLoc, getLangOpts().CPlusPlus20
17328                          ? diag::warn_cxx17_compat_defaulted_comparison
17329                          : diag::ext_defaulted_comparison);
17330   }
17331 
17332   FD->setDefaulted();
17333   FD->setExplicitlyDefaulted();
17334 
17335   // Defer checking functions that are defaulted in a dependent context.
17336   if (FD->isDependentContext())
17337     return;
17338 
17339   // Unset that we will have a body for this function. We might not,
17340   // if it turns out to be trivial, and we don't need this marking now
17341   // that we've marked it as defaulted.
17342   FD->setWillHaveBody(false);
17343 
17344   if (DefKind.isComparison()) {
17345     // If this comparison's defaulting occurs within the definition of its
17346     // lexical class context, we have to do the checking when complete.
17347     if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17348       if (!RD->isCompleteDefinition())
17349         return;
17350   }
17351 
17352   // If this member fn was defaulted on its first declaration, we will have
17353   // already performed the checking in CheckCompletedCXXClass. Such a
17354   // declaration doesn't trigger an implicit definition.
17355   if (isa<CXXMethodDecl>(FD)) {
17356     const FunctionDecl *Primary = FD;
17357     if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17358       // Ask the template instantiation pattern that actually had the
17359       // '= default' on it.
17360       Primary = Pattern;
17361     if (Primary->getCanonicalDecl()->isDefaulted())
17362       return;
17363   }
17364 
17365   if (DefKind.isComparison()) {
17366     if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17367       FD->setInvalidDecl();
17368     else
17369       DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17370   } else {
17371     auto *MD = cast<CXXMethodDecl>(FD);
17372 
17373     if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
17374       MD->setInvalidDecl();
17375     else
17376       DefineDefaultedFunction(*this, MD, DefaultLoc);
17377   }
17378 }
17379 
17380 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17381   for (Stmt *SubStmt : S->children()) {
17382     if (!SubStmt)
17383       continue;
17384     if (isa<ReturnStmt>(SubStmt))
17385       Self.Diag(SubStmt->getBeginLoc(),
17386                 diag::err_return_in_constructor_handler);
17387     if (!isa<Expr>(SubStmt))
17388       SearchForReturnInStmt(Self, SubStmt);
17389   }
17390 }
17391 
17392 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17393   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17394     CXXCatchStmt *Handler = TryBlock->getHandler(I);
17395     SearchForReturnInStmt(*this, Handler);
17396   }
17397 }
17398 
17399 void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
17400                                FnBodyKind BodyKind) {
17401   switch (BodyKind) {
17402   case FnBodyKind::Delete:
17403     SetDeclDeleted(D, Loc);
17404     break;
17405   case FnBodyKind::Default:
17406     SetDeclDefaulted(D, Loc);
17407     break;
17408   case FnBodyKind::Other:
17409     llvm_unreachable(
17410         "Parsed function body should be '= delete;' or '= default;'");
17411   }
17412 }
17413 
17414 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17415                                              const CXXMethodDecl *Old) {
17416   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17417   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17418 
17419   if (OldFT->hasExtParameterInfos()) {
17420     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17421       // A parameter of the overriding method should be annotated with noescape
17422       // if the corresponding parameter of the overridden method is annotated.
17423       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17424           !NewFT->getExtParameterInfo(I).isNoEscape()) {
17425         Diag(New->getParamDecl(I)->getLocation(),
17426              diag::warn_overriding_method_missing_noescape);
17427         Diag(Old->getParamDecl(I)->getLocation(),
17428              diag::note_overridden_marked_noescape);
17429       }
17430   }
17431 
17432   // Virtual overrides must have the same code_seg.
17433   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17434   const auto *NewCSA = New->getAttr<CodeSegAttr>();
17435   if ((NewCSA || OldCSA) &&
17436       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17437     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17438     Diag(Old->getLocation(), diag::note_previous_declaration);
17439     return true;
17440   }
17441 
17442   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17443 
17444   // If the calling conventions match, everything is fine
17445   if (NewCC == OldCC)
17446     return false;
17447 
17448   // If the calling conventions mismatch because the new function is static,
17449   // suppress the calling convention mismatch error; the error about static
17450   // function override (err_static_overrides_virtual from
17451   // Sema::CheckFunctionDeclaration) is more clear.
17452   if (New->getStorageClass() == SC_Static)
17453     return false;
17454 
17455   Diag(New->getLocation(),
17456        diag::err_conflicting_overriding_cc_attributes)
17457     << New->getDeclName() << New->getType() << Old->getType();
17458   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17459   return true;
17460 }
17461 
17462 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17463                                              const CXXMethodDecl *Old) {
17464   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17465   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17466 
17467   if (Context.hasSameType(NewTy, OldTy) ||
17468       NewTy->isDependentType() || OldTy->isDependentType())
17469     return false;
17470 
17471   // Check if the return types are covariant
17472   QualType NewClassTy, OldClassTy;
17473 
17474   /// Both types must be pointers or references to classes.
17475   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17476     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17477       NewClassTy = NewPT->getPointeeType();
17478       OldClassTy = OldPT->getPointeeType();
17479     }
17480   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17481     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17482       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17483         NewClassTy = NewRT->getPointeeType();
17484         OldClassTy = OldRT->getPointeeType();
17485       }
17486     }
17487   }
17488 
17489   // The return types aren't either both pointers or references to a class type.
17490   if (NewClassTy.isNull()) {
17491     Diag(New->getLocation(),
17492          diag::err_different_return_type_for_overriding_virtual_function)
17493         << New->getDeclName() << NewTy << OldTy
17494         << New->getReturnTypeSourceRange();
17495     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17496         << Old->getReturnTypeSourceRange();
17497 
17498     return true;
17499   }
17500 
17501   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17502     // C++14 [class.virtual]p8:
17503     //   If the class type in the covariant return type of D::f differs from
17504     //   that of B::f, the class type in the return type of D::f shall be
17505     //   complete at the point of declaration of D::f or shall be the class
17506     //   type D.
17507     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17508       if (!RT->isBeingDefined() &&
17509           RequireCompleteType(New->getLocation(), NewClassTy,
17510                               diag::err_covariant_return_incomplete,
17511                               New->getDeclName()))
17512         return true;
17513     }
17514 
17515     // Check if the new class derives from the old class.
17516     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17517       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17518           << New->getDeclName() << NewTy << OldTy
17519           << New->getReturnTypeSourceRange();
17520       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17521           << Old->getReturnTypeSourceRange();
17522       return true;
17523     }
17524 
17525     // Check if we the conversion from derived to base is valid.
17526     if (CheckDerivedToBaseConversion(
17527             NewClassTy, OldClassTy,
17528             diag::err_covariant_return_inaccessible_base,
17529             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17530             New->getLocation(), New->getReturnTypeSourceRange(),
17531             New->getDeclName(), nullptr)) {
17532       // FIXME: this note won't trigger for delayed access control
17533       // diagnostics, and it's impossible to get an undelayed error
17534       // here from access control during the original parse because
17535       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17536       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17537           << Old->getReturnTypeSourceRange();
17538       return true;
17539     }
17540   }
17541 
17542   // The qualifiers of the return types must be the same.
17543   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17544     Diag(New->getLocation(),
17545          diag::err_covariant_return_type_different_qualifications)
17546         << New->getDeclName() << NewTy << OldTy
17547         << New->getReturnTypeSourceRange();
17548     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17549         << Old->getReturnTypeSourceRange();
17550     return true;
17551   }
17552 
17553 
17554   // The new class type must have the same or less qualifiers as the old type.
17555   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17556     Diag(New->getLocation(),
17557          diag::err_covariant_return_type_class_type_more_qualified)
17558         << New->getDeclName() << NewTy << OldTy
17559         << New->getReturnTypeSourceRange();
17560     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17561         << Old->getReturnTypeSourceRange();
17562     return true;
17563   }
17564 
17565   return false;
17566 }
17567 
17568 /// Mark the given method pure.
17569 ///
17570 /// \param Method the method to be marked pure.
17571 ///
17572 /// \param InitRange the source range that covers the "0" initializer.
17573 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17574   SourceLocation EndLoc = InitRange.getEnd();
17575   if (EndLoc.isValid())
17576     Method->setRangeEnd(EndLoc);
17577 
17578   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17579     Method->setPure();
17580     return false;
17581   }
17582 
17583   if (!Method->isInvalidDecl())
17584     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17585       << Method->getDeclName() << InitRange;
17586   return true;
17587 }
17588 
17589 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17590   if (D->getFriendObjectKind())
17591     Diag(D->getLocation(), diag::err_pure_friend);
17592   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17593     CheckPureMethod(M, ZeroLoc);
17594   else
17595     Diag(D->getLocation(), diag::err_illegal_initializer);
17596 }
17597 
17598 /// Determine whether the given declaration is a global variable or
17599 /// static data member.
17600 static bool isNonlocalVariable(const Decl *D) {
17601   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17602     return Var->hasGlobalStorage();
17603 
17604   return false;
17605 }
17606 
17607 /// Invoked when we are about to parse an initializer for the declaration
17608 /// 'Dcl'.
17609 ///
17610 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17611 /// static data member of class X, names should be looked up in the scope of
17612 /// class X. If the declaration had a scope specifier, a scope will have
17613 /// been created and passed in for this purpose. Otherwise, S will be null.
17614 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17615   // If there is no declaration, there was an error parsing it.
17616   if (!D || D->isInvalidDecl())
17617     return;
17618 
17619   // We will always have a nested name specifier here, but this declaration
17620   // might not be out of line if the specifier names the current namespace:
17621   //   extern int n;
17622   //   int ::n = 0;
17623   if (S && D->isOutOfLine())
17624     EnterDeclaratorContext(S, D->getDeclContext());
17625 
17626   // If we are parsing the initializer for a static data member, push a
17627   // new expression evaluation context that is associated with this static
17628   // data member.
17629   if (isNonlocalVariable(D))
17630     PushExpressionEvaluationContext(
17631         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17632 }
17633 
17634 /// Invoked after we are finished parsing an initializer for the declaration D.
17635 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17636   // If there is no declaration, there was an error parsing it.
17637   if (!D || D->isInvalidDecl())
17638     return;
17639 
17640   if (isNonlocalVariable(D))
17641     PopExpressionEvaluationContext();
17642 
17643   if (S && D->isOutOfLine())
17644     ExitDeclaratorContext(S);
17645 }
17646 
17647 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17648 /// C++ if/switch/while/for statement.
17649 /// e.g: "if (int x = f()) {...}"
17650 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17651   // C++ 6.4p2:
17652   // The declarator shall not specify a function or an array.
17653   // The type-specifier-seq shall not contain typedef and shall not declare a
17654   // new class or enumeration.
17655   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17656          "Parser allowed 'typedef' as storage class of condition decl.");
17657 
17658   Decl *Dcl = ActOnDeclarator(S, D);
17659   if (!Dcl)
17660     return true;
17661 
17662   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17663     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17664       << D.getSourceRange();
17665     return true;
17666   }
17667 
17668   return Dcl;
17669 }
17670 
17671 void Sema::LoadExternalVTableUses() {
17672   if (!ExternalSource)
17673     return;
17674 
17675   SmallVector<ExternalVTableUse, 4> VTables;
17676   ExternalSource->ReadUsedVTables(VTables);
17677   SmallVector<VTableUse, 4> NewUses;
17678   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17679     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17680       = VTablesUsed.find(VTables[I].Record);
17681     // Even if a definition wasn't required before, it may be required now.
17682     if (Pos != VTablesUsed.end()) {
17683       if (!Pos->second && VTables[I].DefinitionRequired)
17684         Pos->second = true;
17685       continue;
17686     }
17687 
17688     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17689     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17690   }
17691 
17692   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17693 }
17694 
17695 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17696                           bool DefinitionRequired) {
17697   // Ignore any vtable uses in unevaluated operands or for classes that do
17698   // not have a vtable.
17699   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17700       CurContext->isDependentContext() || isUnevaluatedContext())
17701     return;
17702   // Do not mark as used if compiling for the device outside of the target
17703   // region.
17704   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17705       !isInOpenMPDeclareTargetContext() &&
17706       !isInOpenMPTargetExecutionDirective()) {
17707     if (!DefinitionRequired)
17708       MarkVirtualMembersReferenced(Loc, Class);
17709     return;
17710   }
17711 
17712   // Try to insert this class into the map.
17713   LoadExternalVTableUses();
17714   Class = Class->getCanonicalDecl();
17715   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17716     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17717   if (!Pos.second) {
17718     // If we already had an entry, check to see if we are promoting this vtable
17719     // to require a definition. If so, we need to reappend to the VTableUses
17720     // list, since we may have already processed the first entry.
17721     if (DefinitionRequired && !Pos.first->second) {
17722       Pos.first->second = true;
17723     } else {
17724       // Otherwise, we can early exit.
17725       return;
17726     }
17727   } else {
17728     // The Microsoft ABI requires that we perform the destructor body
17729     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17730     // the deleting destructor is emitted with the vtable, not with the
17731     // destructor definition as in the Itanium ABI.
17732     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17733       CXXDestructorDecl *DD = Class->getDestructor();
17734       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17735         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17736           // If this is an out-of-line declaration, marking it referenced will
17737           // not do anything. Manually call CheckDestructor to look up operator
17738           // delete().
17739           ContextRAII SavedContext(*this, DD);
17740           CheckDestructor(DD);
17741         } else {
17742           MarkFunctionReferenced(Loc, Class->getDestructor());
17743         }
17744       }
17745     }
17746   }
17747 
17748   // Local classes need to have their virtual members marked
17749   // immediately. For all other classes, we mark their virtual members
17750   // at the end of the translation unit.
17751   if (Class->isLocalClass())
17752     MarkVirtualMembersReferenced(Loc, Class);
17753   else
17754     VTableUses.push_back(std::make_pair(Class, Loc));
17755 }
17756 
17757 bool Sema::DefineUsedVTables() {
17758   LoadExternalVTableUses();
17759   if (VTableUses.empty())
17760     return false;
17761 
17762   // Note: The VTableUses vector could grow as a result of marking
17763   // the members of a class as "used", so we check the size each
17764   // time through the loop and prefer indices (which are stable) to
17765   // iterators (which are not).
17766   bool DefinedAnything = false;
17767   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17768     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17769     if (!Class)
17770       continue;
17771     TemplateSpecializationKind ClassTSK =
17772         Class->getTemplateSpecializationKind();
17773 
17774     SourceLocation Loc = VTableUses[I].second;
17775 
17776     bool DefineVTable = true;
17777 
17778     // If this class has a key function, but that key function is
17779     // defined in another translation unit, we don't need to emit the
17780     // vtable even though we're using it.
17781     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17782     if (KeyFunction && !KeyFunction->hasBody()) {
17783       // The key function is in another translation unit.
17784       DefineVTable = false;
17785       TemplateSpecializationKind TSK =
17786           KeyFunction->getTemplateSpecializationKind();
17787       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17788              TSK != TSK_ImplicitInstantiation &&
17789              "Instantiations don't have key functions");
17790       (void)TSK;
17791     } else if (!KeyFunction) {
17792       // If we have a class with no key function that is the subject
17793       // of an explicit instantiation declaration, suppress the
17794       // vtable; it will live with the explicit instantiation
17795       // definition.
17796       bool IsExplicitInstantiationDeclaration =
17797           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17798       for (auto R : Class->redecls()) {
17799         TemplateSpecializationKind TSK
17800           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17801         if (TSK == TSK_ExplicitInstantiationDeclaration)
17802           IsExplicitInstantiationDeclaration = true;
17803         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17804           IsExplicitInstantiationDeclaration = false;
17805           break;
17806         }
17807       }
17808 
17809       if (IsExplicitInstantiationDeclaration)
17810         DefineVTable = false;
17811     }
17812 
17813     // The exception specifications for all virtual members may be needed even
17814     // if we are not providing an authoritative form of the vtable in this TU.
17815     // We may choose to emit it available_externally anyway.
17816     if (!DefineVTable) {
17817       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17818       continue;
17819     }
17820 
17821     // Mark all of the virtual members of this class as referenced, so
17822     // that we can build a vtable. Then, tell the AST consumer that a
17823     // vtable for this class is required.
17824     DefinedAnything = true;
17825     MarkVirtualMembersReferenced(Loc, Class);
17826     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17827     if (VTablesUsed[Canonical])
17828       Consumer.HandleVTable(Class);
17829 
17830     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17831     // no key function or the key function is inlined. Don't warn in C++ ABIs
17832     // that lack key functions, since the user won't be able to make one.
17833     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17834         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
17835         ClassTSK != TSK_ExplicitInstantiationDefinition) {
17836       const FunctionDecl *KeyFunctionDef = nullptr;
17837       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17838                            KeyFunctionDef->isInlined()))
17839         Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
17840     }
17841   }
17842   VTableUses.clear();
17843 
17844   return DefinedAnything;
17845 }
17846 
17847 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17848                                                  const CXXRecordDecl *RD) {
17849   for (const auto *I : RD->methods())
17850     if (I->isVirtual() && !I->isPure())
17851       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17852 }
17853 
17854 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17855                                         const CXXRecordDecl *RD,
17856                                         bool ConstexprOnly) {
17857   // Mark all functions which will appear in RD's vtable as used.
17858   CXXFinalOverriderMap FinalOverriders;
17859   RD->getFinalOverriders(FinalOverriders);
17860   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17861                                             E = FinalOverriders.end();
17862        I != E; ++I) {
17863     for (OverridingMethods::const_iterator OI = I->second.begin(),
17864                                            OE = I->second.end();
17865          OI != OE; ++OI) {
17866       assert(OI->second.size() > 0 && "no final overrider");
17867       CXXMethodDecl *Overrider = OI->second.front().Method;
17868 
17869       // C++ [basic.def.odr]p2:
17870       //   [...] A virtual member function is used if it is not pure. [...]
17871       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17872         MarkFunctionReferenced(Loc, Overrider);
17873     }
17874   }
17875 
17876   // Only classes that have virtual bases need a VTT.
17877   if (RD->getNumVBases() == 0)
17878     return;
17879 
17880   for (const auto &I : RD->bases()) {
17881     const auto *Base =
17882         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17883     if (Base->getNumVBases() == 0)
17884       continue;
17885     MarkVirtualMembersReferenced(Loc, Base);
17886   }
17887 }
17888 
17889 /// SetIvarInitializers - This routine builds initialization ASTs for the
17890 /// Objective-C implementation whose ivars need be initialized.
17891 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17892   if (!getLangOpts().CPlusPlus)
17893     return;
17894   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17895     SmallVector<ObjCIvarDecl*, 8> ivars;
17896     CollectIvarsToConstructOrDestruct(OID, ivars);
17897     if (ivars.empty())
17898       return;
17899     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17900     for (unsigned i = 0; i < ivars.size(); i++) {
17901       FieldDecl *Field = ivars[i];
17902       if (Field->isInvalidDecl())
17903         continue;
17904 
17905       CXXCtorInitializer *Member;
17906       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17907       InitializationKind InitKind =
17908         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17909 
17910       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17911       ExprResult MemberInit =
17912         InitSeq.Perform(*this, InitEntity, InitKind, None);
17913       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17914       // Note, MemberInit could actually come back empty if no initialization
17915       // is required (e.g., because it would call a trivial default constructor)
17916       if (!MemberInit.get() || MemberInit.isInvalid())
17917         continue;
17918 
17919       Member =
17920         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17921                                          SourceLocation(),
17922                                          MemberInit.getAs<Expr>(),
17923                                          SourceLocation());
17924       AllToInit.push_back(Member);
17925 
17926       // Be sure that the destructor is accessible and is marked as referenced.
17927       if (const RecordType *RecordTy =
17928               Context.getBaseElementType(Field->getType())
17929                   ->getAs<RecordType>()) {
17930         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17931         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17932           MarkFunctionReferenced(Field->getLocation(), Destructor);
17933           CheckDestructorAccess(Field->getLocation(), Destructor,
17934                             PDiag(diag::err_access_dtor_ivar)
17935                               << Context.getBaseElementType(Field->getType()));
17936         }
17937       }
17938     }
17939     ObjCImplementation->setIvarInitializers(Context,
17940                                             AllToInit.data(), AllToInit.size());
17941   }
17942 }
17943 
17944 static
17945 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17946                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17947                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17948                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17949                            Sema &S) {
17950   if (Ctor->isInvalidDecl())
17951     return;
17952 
17953   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17954 
17955   // Target may not be determinable yet, for instance if this is a dependent
17956   // call in an uninstantiated template.
17957   if (Target) {
17958     const FunctionDecl *FNTarget = nullptr;
17959     (void)Target->hasBody(FNTarget);
17960     Target = const_cast<CXXConstructorDecl*>(
17961       cast_or_null<CXXConstructorDecl>(FNTarget));
17962   }
17963 
17964   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17965                      // Avoid dereferencing a null pointer here.
17966                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17967 
17968   if (!Current.insert(Canonical).second)
17969     return;
17970 
17971   // We know that beyond here, we aren't chaining into a cycle.
17972   if (!Target || !Target->isDelegatingConstructor() ||
17973       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17974     Valid.insert(Current.begin(), Current.end());
17975     Current.clear();
17976   // We've hit a cycle.
17977   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17978              Current.count(TCanonical)) {
17979     // If we haven't diagnosed this cycle yet, do so now.
17980     if (!Invalid.count(TCanonical)) {
17981       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17982              diag::warn_delegating_ctor_cycle)
17983         << Ctor;
17984 
17985       // Don't add a note for a function delegating directly to itself.
17986       if (TCanonical != Canonical)
17987         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17988 
17989       CXXConstructorDecl *C = Target;
17990       while (C->getCanonicalDecl() != Canonical) {
17991         const FunctionDecl *FNTarget = nullptr;
17992         (void)C->getTargetConstructor()->hasBody(FNTarget);
17993         assert(FNTarget && "Ctor cycle through bodiless function");
17994 
17995         C = const_cast<CXXConstructorDecl*>(
17996           cast<CXXConstructorDecl>(FNTarget));
17997         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17998       }
17999     }
18000 
18001     Invalid.insert(Current.begin(), Current.end());
18002     Current.clear();
18003   } else {
18004     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18005   }
18006 }
18007 
18008 
18009 void Sema::CheckDelegatingCtorCycles() {
18010   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18011 
18012   for (DelegatingCtorDeclsType::iterator
18013          I = DelegatingCtorDecls.begin(ExternalSource),
18014          E = DelegatingCtorDecls.end();
18015        I != E; ++I)
18016     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18017 
18018   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18019     (*CI)->setInvalidDecl();
18020 }
18021 
18022 namespace {
18023   /// AST visitor that finds references to the 'this' expression.
18024   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18025     Sema &S;
18026 
18027   public:
18028     explicit FindCXXThisExpr(Sema &S) : S(S) { }
18029 
18030     bool VisitCXXThisExpr(CXXThisExpr *E) {
18031       S.Diag(E->getLocation(), diag::err_this_static_member_func)
18032         << E->isImplicit();
18033       return false;
18034     }
18035   };
18036 }
18037 
18038 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18039   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18040   if (!TSInfo)
18041     return false;
18042 
18043   TypeLoc TL = TSInfo->getTypeLoc();
18044   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18045   if (!ProtoTL)
18046     return false;
18047 
18048   // C++11 [expr.prim.general]p3:
18049   //   [The expression this] shall not appear before the optional
18050   //   cv-qualifier-seq and it shall not appear within the declaration of a
18051   //   static member function (although its type and value category are defined
18052   //   within a static member function as they are within a non-static member
18053   //   function). [ Note: this is because declaration matching does not occur
18054   //  until the complete declarator is known. - end note ]
18055   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18056   FindCXXThisExpr Finder(*this);
18057 
18058   // If the return type came after the cv-qualifier-seq, check it now.
18059   if (Proto->hasTrailingReturn() &&
18060       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18061     return true;
18062 
18063   // Check the exception specification.
18064   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18065     return true;
18066 
18067   // Check the trailing requires clause
18068   if (Expr *E = Method->getTrailingRequiresClause())
18069     if (!Finder.TraverseStmt(E))
18070       return true;
18071 
18072   return checkThisInStaticMemberFunctionAttributes(Method);
18073 }
18074 
18075 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18076   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18077   if (!TSInfo)
18078     return false;
18079 
18080   TypeLoc TL = TSInfo->getTypeLoc();
18081   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18082   if (!ProtoTL)
18083     return false;
18084 
18085   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18086   FindCXXThisExpr Finder(*this);
18087 
18088   switch (Proto->getExceptionSpecType()) {
18089   case EST_Unparsed:
18090   case EST_Uninstantiated:
18091   case EST_Unevaluated:
18092   case EST_BasicNoexcept:
18093   case EST_NoThrow:
18094   case EST_DynamicNone:
18095   case EST_MSAny:
18096   case EST_None:
18097     break;
18098 
18099   case EST_DependentNoexcept:
18100   case EST_NoexceptFalse:
18101   case EST_NoexceptTrue:
18102     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18103       return true;
18104     LLVM_FALLTHROUGH;
18105 
18106   case EST_Dynamic:
18107     for (const auto &E : Proto->exceptions()) {
18108       if (!Finder.TraverseType(E))
18109         return true;
18110     }
18111     break;
18112   }
18113 
18114   return false;
18115 }
18116 
18117 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
18118   FindCXXThisExpr Finder(*this);
18119 
18120   // Check attributes.
18121   for (const auto *A : Method->attrs()) {
18122     // FIXME: This should be emitted by tblgen.
18123     Expr *Arg = nullptr;
18124     ArrayRef<Expr *> Args;
18125     if (const auto *G = dyn_cast<GuardedByAttr>(A))
18126       Arg = G->getArg();
18127     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18128       Arg = G->getArg();
18129     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18130       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
18131     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18132       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
18133     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18134       Arg = ETLF->getSuccessValue();
18135       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
18136     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18137       Arg = STLF->getSuccessValue();
18138       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
18139     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18140       Arg = LR->getArg();
18141     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18142       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
18143     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18144       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18145     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18146       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18147     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18148       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18149     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18150       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18151 
18152     if (Arg && !Finder.TraverseStmt(Arg))
18153       return true;
18154 
18155     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18156       if (!Finder.TraverseStmt(Args[I]))
18157         return true;
18158     }
18159   }
18160 
18161   return false;
18162 }
18163 
18164 void Sema::checkExceptionSpecification(
18165     bool IsTopLevel, ExceptionSpecificationType EST,
18166     ArrayRef<ParsedType> DynamicExceptions,
18167     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18168     SmallVectorImpl<QualType> &Exceptions,
18169     FunctionProtoType::ExceptionSpecInfo &ESI) {
18170   Exceptions.clear();
18171   ESI.Type = EST;
18172   if (EST == EST_Dynamic) {
18173     Exceptions.reserve(DynamicExceptions.size());
18174     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18175       // FIXME: Preserve type source info.
18176       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18177 
18178       if (IsTopLevel) {
18179         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
18180         collectUnexpandedParameterPacks(ET, Unexpanded);
18181         if (!Unexpanded.empty()) {
18182           DiagnoseUnexpandedParameterPacks(
18183               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18184               Unexpanded);
18185           continue;
18186         }
18187       }
18188 
18189       // Check that the type is valid for an exception spec, and
18190       // drop it if not.
18191       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18192         Exceptions.push_back(ET);
18193     }
18194     ESI.Exceptions = Exceptions;
18195     return;
18196   }
18197 
18198   if (isComputedNoexcept(EST)) {
18199     assert((NoexceptExpr->isTypeDependent() ||
18200             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18201             Context.BoolTy) &&
18202            "Parser should have made sure that the expression is boolean");
18203     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18204       ESI.Type = EST_BasicNoexcept;
18205       return;
18206     }
18207 
18208     ESI.NoexceptExpr = NoexceptExpr;
18209     return;
18210   }
18211 }
18212 
18213 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
18214              ExceptionSpecificationType EST,
18215              SourceRange SpecificationRange,
18216              ArrayRef<ParsedType> DynamicExceptions,
18217              ArrayRef<SourceRange> DynamicExceptionRanges,
18218              Expr *NoexceptExpr) {
18219   if (!MethodD)
18220     return;
18221 
18222   // Dig out the method we're referring to.
18223   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18224     MethodD = FunTmpl->getTemplatedDecl();
18225 
18226   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18227   if (!Method)
18228     return;
18229 
18230   // Check the exception specification.
18231   llvm::SmallVector<QualType, 4> Exceptions;
18232   FunctionProtoType::ExceptionSpecInfo ESI;
18233   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18234                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
18235                               ESI);
18236 
18237   // Update the exception specification on the function type.
18238   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18239 
18240   if (Method->isStatic())
18241     checkThisInStaticMemberFunctionExceptionSpec(Method);
18242 
18243   if (Method->isVirtual()) {
18244     // Check overrides, which we previously had to delay.
18245     for (const CXXMethodDecl *O : Method->overridden_methods())
18246       CheckOverridingFunctionExceptionSpec(Method, O);
18247   }
18248 }
18249 
18250 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18251 ///
18252 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18253                                        SourceLocation DeclStart, Declarator &D,
18254                                        Expr *BitWidth,
18255                                        InClassInitStyle InitStyle,
18256                                        AccessSpecifier AS,
18257                                        const ParsedAttr &MSPropertyAttr) {
18258   IdentifierInfo *II = D.getIdentifier();
18259   if (!II) {
18260     Diag(DeclStart, diag::err_anonymous_property);
18261     return nullptr;
18262   }
18263   SourceLocation Loc = D.getIdentifierLoc();
18264 
18265   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18266   QualType T = TInfo->getType();
18267   if (getLangOpts().CPlusPlus) {
18268     CheckExtraCXXDefaultArguments(D);
18269 
18270     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18271                                         UPPC_DataMemberType)) {
18272       D.setInvalidType();
18273       T = Context.IntTy;
18274       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18275     }
18276   }
18277 
18278   DiagnoseFunctionSpecifiers(D.getDeclSpec());
18279 
18280   if (D.getDeclSpec().isInlineSpecified())
18281     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18282         << getLangOpts().CPlusPlus17;
18283   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18284     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18285          diag::err_invalid_thread)
18286       << DeclSpec::getSpecifierName(TSCS);
18287 
18288   // Check to see if this name was declared as a member previously
18289   NamedDecl *PrevDecl = nullptr;
18290   LookupResult Previous(*this, II, Loc, LookupMemberName,
18291                         ForVisibleRedeclaration);
18292   LookupName(Previous, S);
18293   switch (Previous.getResultKind()) {
18294   case LookupResult::Found:
18295   case LookupResult::FoundUnresolvedValue:
18296     PrevDecl = Previous.getAsSingle<NamedDecl>();
18297     break;
18298 
18299   case LookupResult::FoundOverloaded:
18300     PrevDecl = Previous.getRepresentativeDecl();
18301     break;
18302 
18303   case LookupResult::NotFound:
18304   case LookupResult::NotFoundInCurrentInstantiation:
18305   case LookupResult::Ambiguous:
18306     break;
18307   }
18308 
18309   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18310     // Maybe we will complain about the shadowed template parameter.
18311     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18312     // Just pretend that we didn't see the previous declaration.
18313     PrevDecl = nullptr;
18314   }
18315 
18316   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18317     PrevDecl = nullptr;
18318 
18319   SourceLocation TSSL = D.getBeginLoc();
18320   MSPropertyDecl *NewPD =
18321       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18322                              MSPropertyAttr.getPropertyDataGetter(),
18323                              MSPropertyAttr.getPropertyDataSetter());
18324   ProcessDeclAttributes(TUScope, NewPD, D);
18325   NewPD->setAccess(AS);
18326 
18327   if (NewPD->isInvalidDecl())
18328     Record->setInvalidDecl();
18329 
18330   if (D.getDeclSpec().isModulePrivateSpecified())
18331     NewPD->setModulePrivate();
18332 
18333   if (NewPD->isInvalidDecl() && PrevDecl) {
18334     // Don't introduce NewFD into scope; there's already something
18335     // with the same name in the same scope.
18336   } else if (II) {
18337     PushOnScopeChains(NewPD, S);
18338   } else
18339     Record->addDecl(NewPD);
18340 
18341   return NewPD;
18342 }
18343 
18344 void Sema::ActOnStartFunctionDeclarationDeclarator(
18345     Declarator &Declarator, unsigned TemplateParameterDepth) {
18346   auto &Info = InventedParameterInfos.emplace_back();
18347   TemplateParameterList *ExplicitParams = nullptr;
18348   ArrayRef<TemplateParameterList *> ExplicitLists =
18349       Declarator.getTemplateParameterLists();
18350   if (!ExplicitLists.empty()) {
18351     bool IsMemberSpecialization, IsInvalid;
18352     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18353         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18354         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18355         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18356         /*SuppressDiagnostic=*/true);
18357   }
18358   if (ExplicitParams) {
18359     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18360     llvm::append_range(Info.TemplateParams, *ExplicitParams);
18361     Info.NumExplicitTemplateParams = ExplicitParams->size();
18362   } else {
18363     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18364     Info.NumExplicitTemplateParams = 0;
18365   }
18366 }
18367 
18368 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18369   auto &FSI = InventedParameterInfos.back();
18370   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18371     if (FSI.NumExplicitTemplateParams != 0) {
18372       TemplateParameterList *ExplicitParams =
18373           Declarator.getTemplateParameterLists().back();
18374       Declarator.setInventedTemplateParameterList(
18375           TemplateParameterList::Create(
18376               Context, ExplicitParams->getTemplateLoc(),
18377               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18378               ExplicitParams->getRAngleLoc(),
18379               ExplicitParams->getRequiresClause()));
18380     } else {
18381       Declarator.setInventedTemplateParameterList(
18382           TemplateParameterList::Create(
18383               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18384               SourceLocation(), /*RequiresClause=*/nullptr));
18385     }
18386   }
18387   InventedParameterInfos.pop_back();
18388 }
18389