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 = getElaboratedType(ETK_None, SS, Context.getTypeDeclType(TyD));
4366       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4367       TInfo = Context.CreateTypeSourceInfo(BaseType);
4368       ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4369       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4370       TL.setElaboratedKeywordLoc(SourceLocation());
4371       TL.setQualifierLoc(SS.getWithLocInContext(Context));
4372     }
4373   }
4374 
4375   if (!TInfo)
4376     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4377 
4378   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4379 }
4380 
4381 MemInitResult
4382 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4383                              SourceLocation IdLoc) {
4384   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4385   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4386   assert((DirectMember || IndirectMember) &&
4387          "Member must be a FieldDecl or IndirectFieldDecl");
4388 
4389   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4390     return true;
4391 
4392   if (Member->isInvalidDecl())
4393     return true;
4394 
4395   MultiExprArg Args;
4396   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4397     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4398   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4399     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4400   } else {
4401     // Template instantiation doesn't reconstruct ParenListExprs for us.
4402     Args = Init;
4403   }
4404 
4405   SourceRange InitRange = Init->getSourceRange();
4406 
4407   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4408     // Can't check initialization for a member of dependent type or when
4409     // any of the arguments are type-dependent expressions.
4410     DiscardCleanupsInEvaluationContext();
4411   } else {
4412     bool InitList = false;
4413     if (isa<InitListExpr>(Init)) {
4414       InitList = true;
4415       Args = Init;
4416     }
4417 
4418     // Initialize the member.
4419     InitializedEntity MemberEntity =
4420       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4421                    : InitializedEntity::InitializeMember(IndirectMember,
4422                                                          nullptr);
4423     InitializationKind Kind =
4424         InitList ? InitializationKind::CreateDirectList(
4425                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4426                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4427                                                     InitRange.getEnd());
4428 
4429     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4430     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4431                                             nullptr);
4432     if (!MemberInit.isInvalid()) {
4433       // C++11 [class.base.init]p7:
4434       //   The initialization of each base and member constitutes a
4435       //   full-expression.
4436       MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4437                                        /*DiscardedValue*/ false);
4438     }
4439 
4440     if (MemberInit.isInvalid()) {
4441       // Args were sensible expressions but we couldn't initialize the member
4442       // from them. Preserve them in a RecoveryExpr instead.
4443       Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4444                                 Member->getType())
4445                  .get();
4446       if (!Init)
4447         return true;
4448     } else {
4449       Init = MemberInit.get();
4450     }
4451   }
4452 
4453   if (DirectMember) {
4454     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4455                                             InitRange.getBegin(), Init,
4456                                             InitRange.getEnd());
4457   } else {
4458     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4459                                             InitRange.getBegin(), Init,
4460                                             InitRange.getEnd());
4461   }
4462 }
4463 
4464 MemInitResult
4465 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4466                                  CXXRecordDecl *ClassDecl) {
4467   SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4468   if (!LangOpts.CPlusPlus11)
4469     return Diag(NameLoc, diag::err_delegating_ctor)
4470            << TInfo->getTypeLoc().getSourceRange();
4471   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4472 
4473   bool InitList = true;
4474   MultiExprArg Args = Init;
4475   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4476     InitList = false;
4477     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4478   }
4479 
4480   SourceRange InitRange = Init->getSourceRange();
4481   // Initialize the object.
4482   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4483                                      QualType(ClassDecl->getTypeForDecl(), 0));
4484   InitializationKind Kind =
4485       InitList ? InitializationKind::CreateDirectList(
4486                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4487                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4488                                                   InitRange.getEnd());
4489   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4490   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4491                                               Args, nullptr);
4492   if (!DelegationInit.isInvalid()) {
4493     assert((DelegationInit.get()->containsErrors() ||
4494             cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4495            "Delegating constructor with no target?");
4496 
4497     // C++11 [class.base.init]p7:
4498     //   The initialization of each base and member constitutes a
4499     //   full-expression.
4500     DelegationInit = ActOnFinishFullExpr(
4501         DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4502   }
4503 
4504   if (DelegationInit.isInvalid()) {
4505     DelegationInit =
4506         CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4507                            QualType(ClassDecl->getTypeForDecl(), 0));
4508     if (DelegationInit.isInvalid())
4509       return true;
4510   } else {
4511     // If we are in a dependent context, template instantiation will
4512     // perform this type-checking again. Just save the arguments that we
4513     // received in a ParenListExpr.
4514     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4515     // of the information that we have about the base
4516     // initializer. However, deconstructing the ASTs is a dicey process,
4517     // and this approach is far more likely to get the corner cases right.
4518     if (CurContext->isDependentContext())
4519       DelegationInit = Init;
4520   }
4521 
4522   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4523                                           DelegationInit.getAs<Expr>(),
4524                                           InitRange.getEnd());
4525 }
4526 
4527 MemInitResult
4528 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4529                            Expr *Init, CXXRecordDecl *ClassDecl,
4530                            SourceLocation EllipsisLoc) {
4531   SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4532 
4533   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4534     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4535            << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4536 
4537   // C++ [class.base.init]p2:
4538   //   [...] Unless the mem-initializer-id names a nonstatic data
4539   //   member of the constructor's class or a direct or virtual base
4540   //   of that class, the mem-initializer is ill-formed. A
4541   //   mem-initializer-list can initialize a base class using any
4542   //   name that denotes that base class type.
4543 
4544   // We can store the initializers in "as-written" form and delay analysis until
4545   // instantiation if the constructor is dependent. But not for dependent
4546   // (broken) code in a non-template! SetCtorInitializers does not expect this.
4547   bool Dependent = CurContext->isDependentContext() &&
4548                    (BaseType->isDependentType() || Init->isTypeDependent());
4549 
4550   SourceRange InitRange = Init->getSourceRange();
4551   if (EllipsisLoc.isValid()) {
4552     // This is a pack expansion.
4553     if (!BaseType->containsUnexpandedParameterPack())  {
4554       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4555         << SourceRange(BaseLoc, InitRange.getEnd());
4556 
4557       EllipsisLoc = SourceLocation();
4558     }
4559   } else {
4560     // Check for any unexpanded parameter packs.
4561     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4562       return true;
4563 
4564     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4565       return true;
4566   }
4567 
4568   // Check for direct and virtual base classes.
4569   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4570   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4571   if (!Dependent) {
4572     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4573                                        BaseType))
4574       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4575 
4576     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4577                         VirtualBaseSpec);
4578 
4579     // C++ [base.class.init]p2:
4580     // Unless the mem-initializer-id names a nonstatic data member of the
4581     // constructor's class or a direct or virtual base of that class, the
4582     // mem-initializer is ill-formed.
4583     if (!DirectBaseSpec && !VirtualBaseSpec) {
4584       // If the class has any dependent bases, then it's possible that
4585       // one of those types will resolve to the same type as
4586       // BaseType. Therefore, just treat this as a dependent base
4587       // class initialization.  FIXME: Should we try to check the
4588       // initialization anyway? It seems odd.
4589       if (ClassDecl->hasAnyDependentBases())
4590         Dependent = true;
4591       else
4592         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4593                << BaseType << Context.getTypeDeclType(ClassDecl)
4594                << BaseTInfo->getTypeLoc().getSourceRange();
4595     }
4596   }
4597 
4598   if (Dependent) {
4599     DiscardCleanupsInEvaluationContext();
4600 
4601     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4602                                             /*IsVirtual=*/false,
4603                                             InitRange.getBegin(), Init,
4604                                             InitRange.getEnd(), EllipsisLoc);
4605   }
4606 
4607   // C++ [base.class.init]p2:
4608   //   If a mem-initializer-id is ambiguous because it designates both
4609   //   a direct non-virtual base class and an inherited virtual base
4610   //   class, the mem-initializer is ill-formed.
4611   if (DirectBaseSpec && VirtualBaseSpec)
4612     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4613       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4614 
4615   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4616   if (!BaseSpec)
4617     BaseSpec = VirtualBaseSpec;
4618 
4619   // Initialize the base.
4620   bool InitList = true;
4621   MultiExprArg Args = Init;
4622   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4623     InitList = false;
4624     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4625   }
4626 
4627   InitializedEntity BaseEntity =
4628     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4629   InitializationKind Kind =
4630       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4631                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4632                                                   InitRange.getEnd());
4633   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4634   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4635   if (!BaseInit.isInvalid()) {
4636     // C++11 [class.base.init]p7:
4637     //   The initialization of each base and member constitutes a
4638     //   full-expression.
4639     BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4640                                    /*DiscardedValue*/ false);
4641   }
4642 
4643   if (BaseInit.isInvalid()) {
4644     BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4645                                   Args, BaseType);
4646     if (BaseInit.isInvalid())
4647       return true;
4648   } else {
4649     // If we are in a dependent context, template instantiation will
4650     // perform this type-checking again. Just save the arguments that we
4651     // received in a ParenListExpr.
4652     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4653     // of the information that we have about the base
4654     // initializer. However, deconstructing the ASTs is a dicey process,
4655     // and this approach is far more likely to get the corner cases right.
4656     if (CurContext->isDependentContext())
4657       BaseInit = Init;
4658   }
4659 
4660   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4661                                           BaseSpec->isVirtual(),
4662                                           InitRange.getBegin(),
4663                                           BaseInit.getAs<Expr>(),
4664                                           InitRange.getEnd(), EllipsisLoc);
4665 }
4666 
4667 // Create a static_cast\<T&&>(expr).
4668 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4669   if (T.isNull()) T = E->getType();
4670   QualType TargetType = SemaRef.BuildReferenceType(
4671       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4672   SourceLocation ExprLoc = E->getBeginLoc();
4673   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4674       TargetType, ExprLoc);
4675 
4676   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4677                                    SourceRange(ExprLoc, ExprLoc),
4678                                    E->getSourceRange()).get();
4679 }
4680 
4681 /// ImplicitInitializerKind - How an implicit base or member initializer should
4682 /// initialize its base or member.
4683 enum ImplicitInitializerKind {
4684   IIK_Default,
4685   IIK_Copy,
4686   IIK_Move,
4687   IIK_Inherit
4688 };
4689 
4690 static bool
4691 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4692                              ImplicitInitializerKind ImplicitInitKind,
4693                              CXXBaseSpecifier *BaseSpec,
4694                              bool IsInheritedVirtualBase,
4695                              CXXCtorInitializer *&CXXBaseInit) {
4696   InitializedEntity InitEntity
4697     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4698                                         IsInheritedVirtualBase);
4699 
4700   ExprResult BaseInit;
4701 
4702   switch (ImplicitInitKind) {
4703   case IIK_Inherit:
4704   case IIK_Default: {
4705     InitializationKind InitKind
4706       = InitializationKind::CreateDefault(Constructor->getLocation());
4707     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4708     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4709     break;
4710   }
4711 
4712   case IIK_Move:
4713   case IIK_Copy: {
4714     bool Moving = ImplicitInitKind == IIK_Move;
4715     ParmVarDecl *Param = Constructor->getParamDecl(0);
4716     QualType ParamType = Param->getType().getNonReferenceType();
4717 
4718     Expr *CopyCtorArg =
4719       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4720                           SourceLocation(), Param, false,
4721                           Constructor->getLocation(), ParamType,
4722                           VK_LValue, nullptr);
4723 
4724     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4725 
4726     // Cast to the base class to avoid ambiguities.
4727     QualType ArgTy =
4728       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4729                                        ParamType.getQualifiers());
4730 
4731     if (Moving) {
4732       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4733     }
4734 
4735     CXXCastPath BasePath;
4736     BasePath.push_back(BaseSpec);
4737     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4738                                             CK_UncheckedDerivedToBase,
4739                                             Moving ? VK_XValue : VK_LValue,
4740                                             &BasePath).get();
4741 
4742     InitializationKind InitKind
4743       = InitializationKind::CreateDirect(Constructor->getLocation(),
4744                                          SourceLocation(), SourceLocation());
4745     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4746     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4747     break;
4748   }
4749   }
4750 
4751   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4752   if (BaseInit.isInvalid())
4753     return true;
4754 
4755   CXXBaseInit =
4756     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4757                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4758                                                         SourceLocation()),
4759                                              BaseSpec->isVirtual(),
4760                                              SourceLocation(),
4761                                              BaseInit.getAs<Expr>(),
4762                                              SourceLocation(),
4763                                              SourceLocation());
4764 
4765   return false;
4766 }
4767 
4768 static bool RefersToRValueRef(Expr *MemRef) {
4769   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4770   return Referenced->getType()->isRValueReferenceType();
4771 }
4772 
4773 static bool
4774 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4775                                ImplicitInitializerKind ImplicitInitKind,
4776                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4777                                CXXCtorInitializer *&CXXMemberInit) {
4778   if (Field->isInvalidDecl())
4779     return true;
4780 
4781   SourceLocation Loc = Constructor->getLocation();
4782 
4783   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4784     bool Moving = ImplicitInitKind == IIK_Move;
4785     ParmVarDecl *Param = Constructor->getParamDecl(0);
4786     QualType ParamType = Param->getType().getNonReferenceType();
4787 
4788     // Suppress copying zero-width bitfields.
4789     if (Field->isZeroLengthBitField(SemaRef.Context))
4790       return false;
4791 
4792     Expr *MemberExprBase =
4793       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4794                           SourceLocation(), Param, false,
4795                           Loc, ParamType, VK_LValue, nullptr);
4796 
4797     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4798 
4799     if (Moving) {
4800       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4801     }
4802 
4803     // Build a reference to this field within the parameter.
4804     CXXScopeSpec SS;
4805     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4806                               Sema::LookupMemberName);
4807     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4808                                   : cast<ValueDecl>(Field), AS_public);
4809     MemberLookup.resolveKind();
4810     ExprResult CtorArg
4811       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4812                                          ParamType, Loc,
4813                                          /*IsArrow=*/false,
4814                                          SS,
4815                                          /*TemplateKWLoc=*/SourceLocation(),
4816                                          /*FirstQualifierInScope=*/nullptr,
4817                                          MemberLookup,
4818                                          /*TemplateArgs=*/nullptr,
4819                                          /*S*/nullptr);
4820     if (CtorArg.isInvalid())
4821       return true;
4822 
4823     // C++11 [class.copy]p15:
4824     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4825     //     with static_cast<T&&>(x.m);
4826     if (RefersToRValueRef(CtorArg.get())) {
4827       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4828     }
4829 
4830     InitializedEntity Entity =
4831         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4832                                                        /*Implicit*/ true)
4833                  : InitializedEntity::InitializeMember(Field, nullptr,
4834                                                        /*Implicit*/ true);
4835 
4836     // Direct-initialize to use the copy constructor.
4837     InitializationKind InitKind =
4838       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4839 
4840     Expr *CtorArgE = CtorArg.getAs<Expr>();
4841     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4842     ExprResult MemberInit =
4843         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4844     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4845     if (MemberInit.isInvalid())
4846       return true;
4847 
4848     if (Indirect)
4849       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4850           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4851     else
4852       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4853           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4854     return false;
4855   }
4856 
4857   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4858          "Unhandled implicit init kind!");
4859 
4860   QualType FieldBaseElementType =
4861     SemaRef.Context.getBaseElementType(Field->getType());
4862 
4863   if (FieldBaseElementType->isRecordType()) {
4864     InitializedEntity InitEntity =
4865         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4866                                                        /*Implicit*/ true)
4867                  : InitializedEntity::InitializeMember(Field, nullptr,
4868                                                        /*Implicit*/ true);
4869     InitializationKind InitKind =
4870       InitializationKind::CreateDefault(Loc);
4871 
4872     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4873     ExprResult MemberInit =
4874       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4875 
4876     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4877     if (MemberInit.isInvalid())
4878       return true;
4879 
4880     if (Indirect)
4881       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4882                                                                Indirect, Loc,
4883                                                                Loc,
4884                                                                MemberInit.get(),
4885                                                                Loc);
4886     else
4887       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4888                                                                Field, Loc, Loc,
4889                                                                MemberInit.get(),
4890                                                                Loc);
4891     return false;
4892   }
4893 
4894   if (!Field->getParent()->isUnion()) {
4895     if (FieldBaseElementType->isReferenceType()) {
4896       SemaRef.Diag(Constructor->getLocation(),
4897                    diag::err_uninitialized_member_in_ctor)
4898       << (int)Constructor->isImplicit()
4899       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4900       << 0 << Field->getDeclName();
4901       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4902       return true;
4903     }
4904 
4905     if (FieldBaseElementType.isConstQualified()) {
4906       SemaRef.Diag(Constructor->getLocation(),
4907                    diag::err_uninitialized_member_in_ctor)
4908       << (int)Constructor->isImplicit()
4909       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4910       << 1 << Field->getDeclName();
4911       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4912       return true;
4913     }
4914   }
4915 
4916   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4917     // ARC and Weak:
4918     //   Default-initialize Objective-C pointers to NULL.
4919     CXXMemberInit
4920       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4921                                                  Loc, Loc,
4922                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4923                                                  Loc);
4924     return false;
4925   }
4926 
4927   // Nothing to initialize.
4928   CXXMemberInit = nullptr;
4929   return false;
4930 }
4931 
4932 namespace {
4933 struct BaseAndFieldInfo {
4934   Sema &S;
4935   CXXConstructorDecl *Ctor;
4936   bool AnyErrorsInInits;
4937   ImplicitInitializerKind IIK;
4938   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4939   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4940   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4941 
4942   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4943     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4944     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4945     if (Ctor->getInheritedConstructor())
4946       IIK = IIK_Inherit;
4947     else if (Generated && Ctor->isCopyConstructor())
4948       IIK = IIK_Copy;
4949     else if (Generated && Ctor->isMoveConstructor())
4950       IIK = IIK_Move;
4951     else
4952       IIK = IIK_Default;
4953   }
4954 
4955   bool isImplicitCopyOrMove() const {
4956     switch (IIK) {
4957     case IIK_Copy:
4958     case IIK_Move:
4959       return true;
4960 
4961     case IIK_Default:
4962     case IIK_Inherit:
4963       return false;
4964     }
4965 
4966     llvm_unreachable("Invalid ImplicitInitializerKind!");
4967   }
4968 
4969   bool addFieldInitializer(CXXCtorInitializer *Init) {
4970     AllToInit.push_back(Init);
4971 
4972     // Check whether this initializer makes the field "used".
4973     if (Init->getInit()->HasSideEffects(S.Context))
4974       S.UnusedPrivateFields.remove(Init->getAnyMember());
4975 
4976     return false;
4977   }
4978 
4979   bool isInactiveUnionMember(FieldDecl *Field) {
4980     RecordDecl *Record = Field->getParent();
4981     if (!Record->isUnion())
4982       return false;
4983 
4984     if (FieldDecl *Active =
4985             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4986       return Active != Field->getCanonicalDecl();
4987 
4988     // In an implicit copy or move constructor, ignore any in-class initializer.
4989     if (isImplicitCopyOrMove())
4990       return true;
4991 
4992     // If there's no explicit initialization, the field is active only if it
4993     // has an in-class initializer...
4994     if (Field->hasInClassInitializer())
4995       return false;
4996     // ... or it's an anonymous struct or union whose class has an in-class
4997     // initializer.
4998     if (!Field->isAnonymousStructOrUnion())
4999       return true;
5000     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5001     return !FieldRD->hasInClassInitializer();
5002   }
5003 
5004   /// Determine whether the given field is, or is within, a union member
5005   /// that is inactive (because there was an initializer given for a different
5006   /// member of the union, or because the union was not initialized at all).
5007   bool isWithinInactiveUnionMember(FieldDecl *Field,
5008                                    IndirectFieldDecl *Indirect) {
5009     if (!Indirect)
5010       return isInactiveUnionMember(Field);
5011 
5012     for (auto *C : Indirect->chain()) {
5013       FieldDecl *Field = dyn_cast<FieldDecl>(C);
5014       if (Field && isInactiveUnionMember(Field))
5015         return true;
5016     }
5017     return false;
5018   }
5019 };
5020 }
5021 
5022 /// Determine whether the given type is an incomplete or zero-lenfgth
5023 /// array type.
5024 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5025   if (T->isIncompleteArrayType())
5026     return true;
5027 
5028   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5029     if (!ArrayT->getSize())
5030       return true;
5031 
5032     T = ArrayT->getElementType();
5033   }
5034 
5035   return false;
5036 }
5037 
5038 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5039                                     FieldDecl *Field,
5040                                     IndirectFieldDecl *Indirect = nullptr) {
5041   if (Field->isInvalidDecl())
5042     return false;
5043 
5044   // Overwhelmingly common case: we have a direct initializer for this field.
5045   if (CXXCtorInitializer *Init =
5046           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
5047     return Info.addFieldInitializer(Init);
5048 
5049   // C++11 [class.base.init]p8:
5050   //   if the entity is a non-static data member that has a
5051   //   brace-or-equal-initializer and either
5052   //   -- the constructor's class is a union and no other variant member of that
5053   //      union is designated by a mem-initializer-id or
5054   //   -- the constructor's class is not a union, and, if the entity is a member
5055   //      of an anonymous union, no other member of that union is designated by
5056   //      a mem-initializer-id,
5057   //   the entity is initialized as specified in [dcl.init].
5058   //
5059   // We also apply the same rules to handle anonymous structs within anonymous
5060   // unions.
5061   if (Info.isWithinInactiveUnionMember(Field, Indirect))
5062     return false;
5063 
5064   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5065     ExprResult DIE =
5066         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5067     if (DIE.isInvalid())
5068       return true;
5069 
5070     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5071     SemaRef.checkInitializerLifetime(Entity, DIE.get());
5072 
5073     CXXCtorInitializer *Init;
5074     if (Indirect)
5075       Init = new (SemaRef.Context)
5076           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5077                              SourceLocation(), DIE.get(), SourceLocation());
5078     else
5079       Init = new (SemaRef.Context)
5080           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5081                              SourceLocation(), DIE.get(), SourceLocation());
5082     return Info.addFieldInitializer(Init);
5083   }
5084 
5085   // Don't initialize incomplete or zero-length arrays.
5086   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5087     return false;
5088 
5089   // Don't try to build an implicit initializer if there were semantic
5090   // errors in any of the initializers (and therefore we might be
5091   // missing some that the user actually wrote).
5092   if (Info.AnyErrorsInInits)
5093     return false;
5094 
5095   CXXCtorInitializer *Init = nullptr;
5096   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5097                                      Indirect, Init))
5098     return true;
5099 
5100   if (!Init)
5101     return false;
5102 
5103   return Info.addFieldInitializer(Init);
5104 }
5105 
5106 bool
5107 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5108                                CXXCtorInitializer *Initializer) {
5109   assert(Initializer->isDelegatingInitializer());
5110   Constructor->setNumCtorInitializers(1);
5111   CXXCtorInitializer **initializer =
5112     new (Context) CXXCtorInitializer*[1];
5113   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5114   Constructor->setCtorInitializers(initializer);
5115 
5116   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5117     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5118     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5119   }
5120 
5121   DelegatingCtorDecls.push_back(Constructor);
5122 
5123   DiagnoseUninitializedFields(*this, Constructor);
5124 
5125   return false;
5126 }
5127 
5128 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5129                                ArrayRef<CXXCtorInitializer *> Initializers) {
5130   if (Constructor->isDependentContext()) {
5131     // Just store the initializers as written, they will be checked during
5132     // instantiation.
5133     if (!Initializers.empty()) {
5134       Constructor->setNumCtorInitializers(Initializers.size());
5135       CXXCtorInitializer **baseOrMemberInitializers =
5136         new (Context) CXXCtorInitializer*[Initializers.size()];
5137       memcpy(baseOrMemberInitializers, Initializers.data(),
5138              Initializers.size() * sizeof(CXXCtorInitializer*));
5139       Constructor->setCtorInitializers(baseOrMemberInitializers);
5140     }
5141 
5142     // Let template instantiation know whether we had errors.
5143     if (AnyErrors)
5144       Constructor->setInvalidDecl();
5145 
5146     return false;
5147   }
5148 
5149   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5150 
5151   // We need to build the initializer AST according to order of construction
5152   // and not what user specified in the Initializers list.
5153   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5154   if (!ClassDecl)
5155     return true;
5156 
5157   bool HadError = false;
5158 
5159   for (unsigned i = 0; i < Initializers.size(); i++) {
5160     CXXCtorInitializer *Member = Initializers[i];
5161 
5162     if (Member->isBaseInitializer())
5163       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5164     else {
5165       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5166 
5167       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5168         for (auto *C : F->chain()) {
5169           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5170           if (FD && FD->getParent()->isUnion())
5171             Info.ActiveUnionMember.insert(std::make_pair(
5172                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5173         }
5174       } else if (FieldDecl *FD = Member->getMember()) {
5175         if (FD->getParent()->isUnion())
5176           Info.ActiveUnionMember.insert(std::make_pair(
5177               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5178       }
5179     }
5180   }
5181 
5182   // Keep track of the direct virtual bases.
5183   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5184   for (auto &I : ClassDecl->bases()) {
5185     if (I.isVirtual())
5186       DirectVBases.insert(&I);
5187   }
5188 
5189   // Push virtual bases before others.
5190   for (auto &VBase : ClassDecl->vbases()) {
5191     if (CXXCtorInitializer *Value
5192         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5193       // [class.base.init]p7, per DR257:
5194       //   A mem-initializer where the mem-initializer-id names a virtual base
5195       //   class is ignored during execution of a constructor of any class that
5196       //   is not the most derived class.
5197       if (ClassDecl->isAbstract()) {
5198         // FIXME: Provide a fixit to remove the base specifier. This requires
5199         // tracking the location of the associated comma for a base specifier.
5200         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5201           << VBase.getType() << ClassDecl;
5202         DiagnoseAbstractType(ClassDecl);
5203       }
5204 
5205       Info.AllToInit.push_back(Value);
5206     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5207       // [class.base.init]p8, per DR257:
5208       //   If a given [...] base class is not named by a mem-initializer-id
5209       //   [...] and the entity is not a virtual base class of an abstract
5210       //   class, then [...] the entity is default-initialized.
5211       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5212       CXXCtorInitializer *CXXBaseInit;
5213       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5214                                        &VBase, IsInheritedVirtualBase,
5215                                        CXXBaseInit)) {
5216         HadError = true;
5217         continue;
5218       }
5219 
5220       Info.AllToInit.push_back(CXXBaseInit);
5221     }
5222   }
5223 
5224   // Non-virtual bases.
5225   for (auto &Base : ClassDecl->bases()) {
5226     // Virtuals are in the virtual base list and already constructed.
5227     if (Base.isVirtual())
5228       continue;
5229 
5230     if (CXXCtorInitializer *Value
5231           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5232       Info.AllToInit.push_back(Value);
5233     } else if (!AnyErrors) {
5234       CXXCtorInitializer *CXXBaseInit;
5235       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5236                                        &Base, /*IsInheritedVirtualBase=*/false,
5237                                        CXXBaseInit)) {
5238         HadError = true;
5239         continue;
5240       }
5241 
5242       Info.AllToInit.push_back(CXXBaseInit);
5243     }
5244   }
5245 
5246   // Fields.
5247   for (auto *Mem : ClassDecl->decls()) {
5248     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5249       // C++ [class.bit]p2:
5250       //   A declaration for a bit-field that omits the identifier declares an
5251       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5252       //   initialized.
5253       if (F->isUnnamedBitfield())
5254         continue;
5255 
5256       // If we're not generating the implicit copy/move constructor, then we'll
5257       // handle anonymous struct/union fields based on their individual
5258       // indirect fields.
5259       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5260         continue;
5261 
5262       if (CollectFieldInitializer(*this, Info, F))
5263         HadError = true;
5264       continue;
5265     }
5266 
5267     // Beyond this point, we only consider default initialization.
5268     if (Info.isImplicitCopyOrMove())
5269       continue;
5270 
5271     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5272       if (F->getType()->isIncompleteArrayType()) {
5273         assert(ClassDecl->hasFlexibleArrayMember() &&
5274                "Incomplete array type is not valid");
5275         continue;
5276       }
5277 
5278       // Initialize each field of an anonymous struct individually.
5279       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5280         HadError = true;
5281 
5282       continue;
5283     }
5284   }
5285 
5286   unsigned NumInitializers = Info.AllToInit.size();
5287   if (NumInitializers > 0) {
5288     Constructor->setNumCtorInitializers(NumInitializers);
5289     CXXCtorInitializer **baseOrMemberInitializers =
5290       new (Context) CXXCtorInitializer*[NumInitializers];
5291     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5292            NumInitializers * sizeof(CXXCtorInitializer*));
5293     Constructor->setCtorInitializers(baseOrMemberInitializers);
5294 
5295     // Constructors implicitly reference the base and member
5296     // destructors.
5297     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5298                                            Constructor->getParent());
5299   }
5300 
5301   return HadError;
5302 }
5303 
5304 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5305   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5306     const RecordDecl *RD = RT->getDecl();
5307     if (RD->isAnonymousStructOrUnion()) {
5308       for (auto *Field : RD->fields())
5309         PopulateKeysForFields(Field, IdealInits);
5310       return;
5311     }
5312   }
5313   IdealInits.push_back(Field->getCanonicalDecl());
5314 }
5315 
5316 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5317   return Context.getCanonicalType(BaseType).getTypePtr();
5318 }
5319 
5320 static const void *GetKeyForMember(ASTContext &Context,
5321                                    CXXCtorInitializer *Member) {
5322   if (!Member->isAnyMemberInitializer())
5323     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5324 
5325   return Member->getAnyMember()->getCanonicalDecl();
5326 }
5327 
5328 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5329                                  const CXXCtorInitializer *Previous,
5330                                  const CXXCtorInitializer *Current) {
5331   if (Previous->isAnyMemberInitializer())
5332     Diag << 0 << Previous->getAnyMember();
5333   else
5334     Diag << 1 << Previous->getTypeSourceInfo()->getType();
5335 
5336   if (Current->isAnyMemberInitializer())
5337     Diag << 0 << Current->getAnyMember();
5338   else
5339     Diag << 1 << Current->getTypeSourceInfo()->getType();
5340 }
5341 
5342 static void DiagnoseBaseOrMemInitializerOrder(
5343     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5344     ArrayRef<CXXCtorInitializer *> Inits) {
5345   if (Constructor->getDeclContext()->isDependentContext())
5346     return;
5347 
5348   // Don't check initializers order unless the warning is enabled at the
5349   // location of at least one initializer.
5350   bool ShouldCheckOrder = false;
5351   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5352     CXXCtorInitializer *Init = Inits[InitIndex];
5353     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5354                                  Init->getSourceLocation())) {
5355       ShouldCheckOrder = true;
5356       break;
5357     }
5358   }
5359   if (!ShouldCheckOrder)
5360     return;
5361 
5362   // Build the list of bases and members in the order that they'll
5363   // actually be initialized.  The explicit initializers should be in
5364   // this same order but may be missing things.
5365   SmallVector<const void*, 32> IdealInitKeys;
5366 
5367   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5368 
5369   // 1. Virtual bases.
5370   for (const auto &VBase : ClassDecl->vbases())
5371     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5372 
5373   // 2. Non-virtual bases.
5374   for (const auto &Base : ClassDecl->bases()) {
5375     if (Base.isVirtual())
5376       continue;
5377     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5378   }
5379 
5380   // 3. Direct fields.
5381   for (auto *Field : ClassDecl->fields()) {
5382     if (Field->isUnnamedBitfield())
5383       continue;
5384 
5385     PopulateKeysForFields(Field, IdealInitKeys);
5386   }
5387 
5388   unsigned NumIdealInits = IdealInitKeys.size();
5389   unsigned IdealIndex = 0;
5390 
5391   // Track initializers that are in an incorrect order for either a warning or
5392   // note if multiple ones occur.
5393   SmallVector<unsigned> WarnIndexes;
5394   // Correlates the index of an initializer in the init-list to the index of
5395   // the field/base in the class.
5396   SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5397 
5398   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5399     const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5400 
5401     // Scan forward to try to find this initializer in the idealized
5402     // initializers list.
5403     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5404       if (InitKey == IdealInitKeys[IdealIndex])
5405         break;
5406 
5407     // If we didn't find this initializer, it must be because we
5408     // scanned past it on a previous iteration.  That can only
5409     // happen if we're out of order;  emit a warning.
5410     if (IdealIndex == NumIdealInits && InitIndex) {
5411       WarnIndexes.push_back(InitIndex);
5412 
5413       // Move back to the initializer's location in the ideal list.
5414       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5415         if (InitKey == IdealInitKeys[IdealIndex])
5416           break;
5417 
5418       assert(IdealIndex < NumIdealInits &&
5419              "initializer not found in initializer list");
5420     }
5421     CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5422   }
5423 
5424   if (WarnIndexes.empty())
5425     return;
5426 
5427   // Sort based on the ideal order, first in the pair.
5428   llvm::sort(CorrelatedInitOrder, llvm::less_first());
5429 
5430   // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5431   // emit the diagnostic before we can try adding notes.
5432   {
5433     Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5434         Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5435         WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5436                                 : diag::warn_some_initializers_out_of_order);
5437 
5438     for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5439       if (CorrelatedInitOrder[I].second == I)
5440         continue;
5441       // Ideally we would be using InsertFromRange here, but clang doesn't
5442       // appear to handle InsertFromRange correctly when the source range is
5443       // modified by another fix-it.
5444       D << FixItHint::CreateReplacement(
5445           Inits[I]->getSourceRange(),
5446           Lexer::getSourceText(
5447               CharSourceRange::getTokenRange(
5448                   Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5449               SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5450     }
5451 
5452     // If there is only 1 item out of order, the warning expects the name and
5453     // type of each being added to it.
5454     if (WarnIndexes.size() == 1) {
5455       AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5456                            Inits[WarnIndexes.front()]);
5457       return;
5458     }
5459   }
5460   // More than 1 item to warn, create notes letting the user know which ones
5461   // are bad.
5462   for (unsigned WarnIndex : WarnIndexes) {
5463     const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5464     auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5465                           diag::note_initializer_out_of_order);
5466     AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5467     D << PrevInit->getSourceRange();
5468   }
5469 }
5470 
5471 namespace {
5472 bool CheckRedundantInit(Sema &S,
5473                         CXXCtorInitializer *Init,
5474                         CXXCtorInitializer *&PrevInit) {
5475   if (!PrevInit) {
5476     PrevInit = Init;
5477     return false;
5478   }
5479 
5480   if (FieldDecl *Field = Init->getAnyMember())
5481     S.Diag(Init->getSourceLocation(),
5482            diag::err_multiple_mem_initialization)
5483       << Field->getDeclName()
5484       << Init->getSourceRange();
5485   else {
5486     const Type *BaseClass = Init->getBaseClass();
5487     assert(BaseClass && "neither field nor base");
5488     S.Diag(Init->getSourceLocation(),
5489            diag::err_multiple_base_initialization)
5490       << QualType(BaseClass, 0)
5491       << Init->getSourceRange();
5492   }
5493   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5494     << 0 << PrevInit->getSourceRange();
5495 
5496   return true;
5497 }
5498 
5499 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5500 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5501 
5502 bool CheckRedundantUnionInit(Sema &S,
5503                              CXXCtorInitializer *Init,
5504                              RedundantUnionMap &Unions) {
5505   FieldDecl *Field = Init->getAnyMember();
5506   RecordDecl *Parent = Field->getParent();
5507   NamedDecl *Child = Field;
5508 
5509   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5510     if (Parent->isUnion()) {
5511       UnionEntry &En = Unions[Parent];
5512       if (En.first && En.first != Child) {
5513         S.Diag(Init->getSourceLocation(),
5514                diag::err_multiple_mem_union_initialization)
5515           << Field->getDeclName()
5516           << Init->getSourceRange();
5517         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5518           << 0 << En.second->getSourceRange();
5519         return true;
5520       }
5521       if (!En.first) {
5522         En.first = Child;
5523         En.second = Init;
5524       }
5525       if (!Parent->isAnonymousStructOrUnion())
5526         return false;
5527     }
5528 
5529     Child = Parent;
5530     Parent = cast<RecordDecl>(Parent->getDeclContext());
5531   }
5532 
5533   return false;
5534 }
5535 } // namespace
5536 
5537 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5538 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5539                                 SourceLocation ColonLoc,
5540                                 ArrayRef<CXXCtorInitializer*> MemInits,
5541                                 bool AnyErrors) {
5542   if (!ConstructorDecl)
5543     return;
5544 
5545   AdjustDeclIfTemplate(ConstructorDecl);
5546 
5547   CXXConstructorDecl *Constructor
5548     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5549 
5550   if (!Constructor) {
5551     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5552     return;
5553   }
5554 
5555   // Mapping for the duplicate initializers check.
5556   // For member initializers, this is keyed with a FieldDecl*.
5557   // For base initializers, this is keyed with a Type*.
5558   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5559 
5560   // Mapping for the inconsistent anonymous-union initializers check.
5561   RedundantUnionMap MemberUnions;
5562 
5563   bool HadError = false;
5564   for (unsigned i = 0; i < MemInits.size(); i++) {
5565     CXXCtorInitializer *Init = MemInits[i];
5566 
5567     // Set the source order index.
5568     Init->setSourceOrder(i);
5569 
5570     if (Init->isAnyMemberInitializer()) {
5571       const void *Key = GetKeyForMember(Context, Init);
5572       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5573           CheckRedundantUnionInit(*this, Init, MemberUnions))
5574         HadError = true;
5575     } else if (Init->isBaseInitializer()) {
5576       const void *Key = GetKeyForMember(Context, Init);
5577       if (CheckRedundantInit(*this, Init, Members[Key]))
5578         HadError = true;
5579     } else {
5580       assert(Init->isDelegatingInitializer());
5581       // This must be the only initializer
5582       if (MemInits.size() != 1) {
5583         Diag(Init->getSourceLocation(),
5584              diag::err_delegating_initializer_alone)
5585           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5586         // We will treat this as being the only initializer.
5587       }
5588       SetDelegatingInitializer(Constructor, MemInits[i]);
5589       // Return immediately as the initializer is set.
5590       return;
5591     }
5592   }
5593 
5594   if (HadError)
5595     return;
5596 
5597   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5598 
5599   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5600 
5601   DiagnoseUninitializedFields(*this, Constructor);
5602 }
5603 
5604 void
5605 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5606                                              CXXRecordDecl *ClassDecl) {
5607   // Ignore dependent contexts. Also ignore unions, since their members never
5608   // have destructors implicitly called.
5609   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5610     return;
5611 
5612   // FIXME: all the access-control diagnostics are positioned on the
5613   // field/base declaration.  That's probably good; that said, the
5614   // user might reasonably want to know why the destructor is being
5615   // emitted, and we currently don't say.
5616 
5617   // Non-static data members.
5618   for (auto *Field : ClassDecl->fields()) {
5619     if (Field->isInvalidDecl())
5620       continue;
5621 
5622     // Don't destroy incomplete or zero-length arrays.
5623     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5624       continue;
5625 
5626     QualType FieldType = Context.getBaseElementType(Field->getType());
5627 
5628     const RecordType* RT = FieldType->getAs<RecordType>();
5629     if (!RT)
5630       continue;
5631 
5632     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5633     if (FieldClassDecl->isInvalidDecl())
5634       continue;
5635     if (FieldClassDecl->hasIrrelevantDestructor())
5636       continue;
5637     // The destructor for an implicit anonymous union member is never invoked.
5638     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5639       continue;
5640 
5641     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5642     assert(Dtor && "No dtor found for FieldClassDecl!");
5643     CheckDestructorAccess(Field->getLocation(), Dtor,
5644                           PDiag(diag::err_access_dtor_field)
5645                             << Field->getDeclName()
5646                             << FieldType);
5647 
5648     MarkFunctionReferenced(Location, Dtor);
5649     DiagnoseUseOfDecl(Dtor, Location);
5650   }
5651 
5652   // We only potentially invoke the destructors of potentially constructed
5653   // subobjects.
5654   bool VisitVirtualBases = !ClassDecl->isAbstract();
5655 
5656   // If the destructor exists and has already been marked used in the MS ABI,
5657   // then virtual base destructors have already been checked and marked used.
5658   // Skip checking them again to avoid duplicate diagnostics.
5659   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5660     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5661     if (Dtor && Dtor->isUsed())
5662       VisitVirtualBases = false;
5663   }
5664 
5665   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5666 
5667   // Bases.
5668   for (const auto &Base : ClassDecl->bases()) {
5669     const RecordType *RT = Base.getType()->getAs<RecordType>();
5670     if (!RT)
5671       continue;
5672 
5673     // Remember direct virtual bases.
5674     if (Base.isVirtual()) {
5675       if (!VisitVirtualBases)
5676         continue;
5677       DirectVirtualBases.insert(RT);
5678     }
5679 
5680     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5681     // If our base class is invalid, we probably can't get its dtor anyway.
5682     if (BaseClassDecl->isInvalidDecl())
5683       continue;
5684     if (BaseClassDecl->hasIrrelevantDestructor())
5685       continue;
5686 
5687     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5688     assert(Dtor && "No dtor found for BaseClassDecl!");
5689 
5690     // FIXME: caret should be on the start of the class name
5691     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5692                           PDiag(diag::err_access_dtor_base)
5693                               << Base.getType() << Base.getSourceRange(),
5694                           Context.getTypeDeclType(ClassDecl));
5695 
5696     MarkFunctionReferenced(Location, Dtor);
5697     DiagnoseUseOfDecl(Dtor, Location);
5698   }
5699 
5700   if (VisitVirtualBases)
5701     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5702                                          &DirectVirtualBases);
5703 }
5704 
5705 void Sema::MarkVirtualBaseDestructorsReferenced(
5706     SourceLocation Location, CXXRecordDecl *ClassDecl,
5707     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5708   // Virtual bases.
5709   for (const auto &VBase : ClassDecl->vbases()) {
5710     // Bases are always records in a well-formed non-dependent class.
5711     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5712 
5713     // Ignore already visited direct virtual bases.
5714     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5715       continue;
5716 
5717     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5718     // If our base class is invalid, we probably can't get its dtor anyway.
5719     if (BaseClassDecl->isInvalidDecl())
5720       continue;
5721     if (BaseClassDecl->hasIrrelevantDestructor())
5722       continue;
5723 
5724     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5725     assert(Dtor && "No dtor found for BaseClassDecl!");
5726     if (CheckDestructorAccess(
5727             ClassDecl->getLocation(), Dtor,
5728             PDiag(diag::err_access_dtor_vbase)
5729                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5730             Context.getTypeDeclType(ClassDecl)) ==
5731         AR_accessible) {
5732       CheckDerivedToBaseConversion(
5733           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5734           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5735           SourceRange(), DeclarationName(), nullptr);
5736     }
5737 
5738     MarkFunctionReferenced(Location, Dtor);
5739     DiagnoseUseOfDecl(Dtor, Location);
5740   }
5741 }
5742 
5743 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5744   if (!CDtorDecl)
5745     return;
5746 
5747   if (CXXConstructorDecl *Constructor
5748       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5749     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5750     DiagnoseUninitializedFields(*this, Constructor);
5751   }
5752 }
5753 
5754 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5755   if (!getLangOpts().CPlusPlus)
5756     return false;
5757 
5758   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5759   if (!RD)
5760     return false;
5761 
5762   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5763   // class template specialization here, but doing so breaks a lot of code.
5764 
5765   // We can't answer whether something is abstract until it has a
5766   // definition. If it's currently being defined, we'll walk back
5767   // over all the declarations when we have a full definition.
5768   const CXXRecordDecl *Def = RD->getDefinition();
5769   if (!Def || Def->isBeingDefined())
5770     return false;
5771 
5772   return RD->isAbstract();
5773 }
5774 
5775 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5776                                   TypeDiagnoser &Diagnoser) {
5777   if (!isAbstractType(Loc, T))
5778     return false;
5779 
5780   T = Context.getBaseElementType(T);
5781   Diagnoser.diagnose(*this, Loc, T);
5782   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5783   return true;
5784 }
5785 
5786 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5787   // Check if we've already emitted the list of pure virtual functions
5788   // for this class.
5789   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5790     return;
5791 
5792   // If the diagnostic is suppressed, don't emit the notes. We're only
5793   // going to emit them once, so try to attach them to a diagnostic we're
5794   // actually going to show.
5795   if (Diags.isLastDiagnosticIgnored())
5796     return;
5797 
5798   CXXFinalOverriderMap FinalOverriders;
5799   RD->getFinalOverriders(FinalOverriders);
5800 
5801   // Keep a set of seen pure methods so we won't diagnose the same method
5802   // more than once.
5803   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5804 
5805   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5806                                    MEnd = FinalOverriders.end();
5807        M != MEnd;
5808        ++M) {
5809     for (OverridingMethods::iterator SO = M->second.begin(),
5810                                   SOEnd = M->second.end();
5811          SO != SOEnd; ++SO) {
5812       // C++ [class.abstract]p4:
5813       //   A class is abstract if it contains or inherits at least one
5814       //   pure virtual function for which the final overrider is pure
5815       //   virtual.
5816 
5817       //
5818       if (SO->second.size() != 1)
5819         continue;
5820 
5821       if (!SO->second.front().Method->isPure())
5822         continue;
5823 
5824       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5825         continue;
5826 
5827       Diag(SO->second.front().Method->getLocation(),
5828            diag::note_pure_virtual_function)
5829         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5830     }
5831   }
5832 
5833   if (!PureVirtualClassDiagSet)
5834     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5835   PureVirtualClassDiagSet->insert(RD);
5836 }
5837 
5838 namespace {
5839 struct AbstractUsageInfo {
5840   Sema &S;
5841   CXXRecordDecl *Record;
5842   CanQualType AbstractType;
5843   bool Invalid;
5844 
5845   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5846     : S(S), Record(Record),
5847       AbstractType(S.Context.getCanonicalType(
5848                    S.Context.getTypeDeclType(Record))),
5849       Invalid(false) {}
5850 
5851   void DiagnoseAbstractType() {
5852     if (Invalid) return;
5853     S.DiagnoseAbstractType(Record);
5854     Invalid = true;
5855   }
5856 
5857   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5858 };
5859 
5860 struct CheckAbstractUsage {
5861   AbstractUsageInfo &Info;
5862   const NamedDecl *Ctx;
5863 
5864   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5865     : Info(Info), Ctx(Ctx) {}
5866 
5867   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5868     switch (TL.getTypeLocClass()) {
5869 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5870 #define TYPELOC(CLASS, PARENT) \
5871     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5872 #include "clang/AST/TypeLocNodes.def"
5873     }
5874   }
5875 
5876   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5877     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5878     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5879       if (!TL.getParam(I))
5880         continue;
5881 
5882       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5883       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5884     }
5885   }
5886 
5887   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5888     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5889   }
5890 
5891   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5892     // Visit the type parameters from a permissive context.
5893     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5894       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5895       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5896         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5897           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5898       // TODO: other template argument types?
5899     }
5900   }
5901 
5902   // Visit pointee types from a permissive context.
5903 #define CheckPolymorphic(Type) \
5904   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5905     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5906   }
5907   CheckPolymorphic(PointerTypeLoc)
5908   CheckPolymorphic(ReferenceTypeLoc)
5909   CheckPolymorphic(MemberPointerTypeLoc)
5910   CheckPolymorphic(BlockPointerTypeLoc)
5911   CheckPolymorphic(AtomicTypeLoc)
5912 
5913   /// Handle all the types we haven't given a more specific
5914   /// implementation for above.
5915   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5916     // Every other kind of type that we haven't called out already
5917     // that has an inner type is either (1) sugar or (2) contains that
5918     // inner type in some way as a subobject.
5919     if (TypeLoc Next = TL.getNextTypeLoc())
5920       return Visit(Next, Sel);
5921 
5922     // If there's no inner type and we're in a permissive context,
5923     // don't diagnose.
5924     if (Sel == Sema::AbstractNone) return;
5925 
5926     // Check whether the type matches the abstract type.
5927     QualType T = TL.getType();
5928     if (T->isArrayType()) {
5929       Sel = Sema::AbstractArrayType;
5930       T = Info.S.Context.getBaseElementType(T);
5931     }
5932     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5933     if (CT != Info.AbstractType) return;
5934 
5935     // It matched; do some magic.
5936     // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
5937     if (Sel == Sema::AbstractArrayType) {
5938       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5939         << T << TL.getSourceRange();
5940     } else {
5941       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5942         << Sel << T << TL.getSourceRange();
5943     }
5944     Info.DiagnoseAbstractType();
5945   }
5946 };
5947 
5948 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5949                                   Sema::AbstractDiagSelID Sel) {
5950   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5951 }
5952 
5953 }
5954 
5955 /// Check for invalid uses of an abstract type in a function declaration.
5956 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5957                                     FunctionDecl *FD) {
5958   // No need to do the check on definitions, which require that
5959   // the return/param types be complete.
5960   if (FD->doesThisDeclarationHaveABody())
5961     return;
5962 
5963   // For safety's sake, just ignore it if we don't have type source
5964   // information.  This should never happen for non-implicit methods,
5965   // but...
5966   if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5967     Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
5968 }
5969 
5970 /// Check for invalid uses of an abstract type in a variable0 declaration.
5971 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5972                                     VarDecl *VD) {
5973   // No need to do the check on definitions, which require that
5974   // the type is complete.
5975   if (VD->isThisDeclarationADefinition())
5976     return;
5977 
5978   Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
5979                  Sema::AbstractVariableType);
5980 }
5981 
5982 /// Check for invalid uses of an abstract type within a class definition.
5983 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5984                                     CXXRecordDecl *RD) {
5985   for (auto *D : RD->decls()) {
5986     if (D->isImplicit()) continue;
5987 
5988     // Step through friends to the befriended declaration.
5989     if (auto *FD = dyn_cast<FriendDecl>(D)) {
5990       D = FD->getFriendDecl();
5991       if (!D) continue;
5992     }
5993 
5994     // Functions and function templates.
5995     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5996       CheckAbstractClassUsage(Info, FD);
5997     } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
5998       CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
5999 
6000     // Fields and static variables.
6001     } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
6002       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6003         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
6004     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
6005       CheckAbstractClassUsage(Info, VD);
6006     } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
6007       CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
6008 
6009     // Nested classes and class templates.
6010     } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6011       CheckAbstractClassUsage(Info, RD);
6012     } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
6013       CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
6014     }
6015   }
6016 }
6017 
6018 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6019   Attr *ClassAttr = getDLLAttr(Class);
6020   if (!ClassAttr)
6021     return;
6022 
6023   assert(ClassAttr->getKind() == attr::DLLExport);
6024 
6025   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6026 
6027   if (TSK == TSK_ExplicitInstantiationDeclaration)
6028     // Don't go any further if this is just an explicit instantiation
6029     // declaration.
6030     return;
6031 
6032   // Add a context note to explain how we got to any diagnostics produced below.
6033   struct MarkingClassDllexported {
6034     Sema &S;
6035     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6036                             SourceLocation AttrLoc)
6037         : S(S) {
6038       Sema::CodeSynthesisContext Ctx;
6039       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6040       Ctx.PointOfInstantiation = AttrLoc;
6041       Ctx.Entity = Class;
6042       S.pushCodeSynthesisContext(Ctx);
6043     }
6044     ~MarkingClassDllexported() {
6045       S.popCodeSynthesisContext();
6046     }
6047   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6048 
6049   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6050     S.MarkVTableUsed(Class->getLocation(), Class, true);
6051 
6052   for (Decl *Member : Class->decls()) {
6053     // Skip members that were not marked exported.
6054     if (!Member->hasAttr<DLLExportAttr>())
6055       continue;
6056 
6057     // Defined static variables that are members of an exported base
6058     // class must be marked export too.
6059     auto *VD = dyn_cast<VarDecl>(Member);
6060     if (VD && VD->getStorageClass() == SC_Static &&
6061         TSK == TSK_ImplicitInstantiation)
6062       S.MarkVariableReferenced(VD->getLocation(), VD);
6063 
6064     auto *MD = dyn_cast<CXXMethodDecl>(Member);
6065     if (!MD)
6066       continue;
6067 
6068     if (MD->isUserProvided()) {
6069       // Instantiate non-default class member functions ...
6070 
6071       // .. except for certain kinds of template specializations.
6072       if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6073         continue;
6074 
6075       // If this is an MS ABI dllexport default constructor, instantiate any
6076       // default arguments.
6077       if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6078         auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6079         if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6080           S.InstantiateDefaultCtorDefaultArgs(CD);
6081         }
6082       }
6083 
6084       S.MarkFunctionReferenced(Class->getLocation(), MD);
6085 
6086       // The function will be passed to the consumer when its definition is
6087       // encountered.
6088     } else if (MD->isExplicitlyDefaulted()) {
6089       // Synthesize and instantiate explicitly defaulted methods.
6090       S.MarkFunctionReferenced(Class->getLocation(), MD);
6091 
6092       if (TSK != TSK_ExplicitInstantiationDefinition) {
6093         // Except for explicit instantiation defs, we will not see the
6094         // definition again later, so pass it to the consumer now.
6095         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6096       }
6097     } else if (!MD->isTrivial() ||
6098                MD->isCopyAssignmentOperator() ||
6099                MD->isMoveAssignmentOperator()) {
6100       // Synthesize and instantiate non-trivial implicit methods, and the copy
6101       // and move assignment operators. The latter are exported even if they
6102       // are trivial, because the address of an operator can be taken and
6103       // should compare equal across libraries.
6104       S.MarkFunctionReferenced(Class->getLocation(), MD);
6105 
6106       // There is no later point when we will see the definition of this
6107       // function, so pass it to the consumer now.
6108       S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6109     }
6110   }
6111 }
6112 
6113 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6114                                                         CXXRecordDecl *Class) {
6115   // Only the MS ABI has default constructor closures, so we don't need to do
6116   // this semantic checking anywhere else.
6117   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6118     return;
6119 
6120   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6121   for (Decl *Member : Class->decls()) {
6122     // Look for exported default constructors.
6123     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6124     if (!CD || !CD->isDefaultConstructor())
6125       continue;
6126     auto *Attr = CD->getAttr<DLLExportAttr>();
6127     if (!Attr)
6128       continue;
6129 
6130     // If the class is non-dependent, mark the default arguments as ODR-used so
6131     // that we can properly codegen the constructor closure.
6132     if (!Class->isDependentContext()) {
6133       for (ParmVarDecl *PD : CD->parameters()) {
6134         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6135         S.DiscardCleanupsInEvaluationContext();
6136       }
6137     }
6138 
6139     if (LastExportedDefaultCtor) {
6140       S.Diag(LastExportedDefaultCtor->getLocation(),
6141              diag::err_attribute_dll_ambiguous_default_ctor)
6142           << Class;
6143       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6144           << CD->getDeclName();
6145       return;
6146     }
6147     LastExportedDefaultCtor = CD;
6148   }
6149 }
6150 
6151 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6152                                                        CXXRecordDecl *Class) {
6153   bool ErrorReported = false;
6154   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6155                                                      ClassTemplateDecl *TD) {
6156     if (ErrorReported)
6157       return;
6158     S.Diag(TD->getLocation(),
6159            diag::err_cuda_device_builtin_surftex_cls_template)
6160         << /*surface*/ 0 << TD;
6161     ErrorReported = true;
6162   };
6163 
6164   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6165   if (!TD) {
6166     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6167     if (!SD) {
6168       S.Diag(Class->getLocation(),
6169              diag::err_cuda_device_builtin_surftex_ref_decl)
6170           << /*surface*/ 0 << Class;
6171       S.Diag(Class->getLocation(),
6172              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6173           << Class;
6174       return;
6175     }
6176     TD = SD->getSpecializedTemplate();
6177   }
6178 
6179   TemplateParameterList *Params = TD->getTemplateParameters();
6180   unsigned N = Params->size();
6181 
6182   if (N != 2) {
6183     reportIllegalClassTemplate(S, TD);
6184     S.Diag(TD->getLocation(),
6185            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6186         << TD << 2;
6187   }
6188   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6189     reportIllegalClassTemplate(S, TD);
6190     S.Diag(TD->getLocation(),
6191            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6192         << TD << /*1st*/ 0 << /*type*/ 0;
6193   }
6194   if (N > 1) {
6195     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6196     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6197       reportIllegalClassTemplate(S, TD);
6198       S.Diag(TD->getLocation(),
6199              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6200           << TD << /*2nd*/ 1 << /*integer*/ 1;
6201     }
6202   }
6203 }
6204 
6205 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6206                                                        CXXRecordDecl *Class) {
6207   bool ErrorReported = false;
6208   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6209                                                      ClassTemplateDecl *TD) {
6210     if (ErrorReported)
6211       return;
6212     S.Diag(TD->getLocation(),
6213            diag::err_cuda_device_builtin_surftex_cls_template)
6214         << /*texture*/ 1 << TD;
6215     ErrorReported = true;
6216   };
6217 
6218   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6219   if (!TD) {
6220     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6221     if (!SD) {
6222       S.Diag(Class->getLocation(),
6223              diag::err_cuda_device_builtin_surftex_ref_decl)
6224           << /*texture*/ 1 << Class;
6225       S.Diag(Class->getLocation(),
6226              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6227           << Class;
6228       return;
6229     }
6230     TD = SD->getSpecializedTemplate();
6231   }
6232 
6233   TemplateParameterList *Params = TD->getTemplateParameters();
6234   unsigned N = Params->size();
6235 
6236   if (N != 3) {
6237     reportIllegalClassTemplate(S, TD);
6238     S.Diag(TD->getLocation(),
6239            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6240         << TD << 3;
6241   }
6242   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6243     reportIllegalClassTemplate(S, TD);
6244     S.Diag(TD->getLocation(),
6245            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6246         << TD << /*1st*/ 0 << /*type*/ 0;
6247   }
6248   if (N > 1) {
6249     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6250     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6251       reportIllegalClassTemplate(S, TD);
6252       S.Diag(TD->getLocation(),
6253              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6254           << TD << /*2nd*/ 1 << /*integer*/ 1;
6255     }
6256   }
6257   if (N > 2) {
6258     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6259     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6260       reportIllegalClassTemplate(S, TD);
6261       S.Diag(TD->getLocation(),
6262              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6263           << TD << /*3rd*/ 2 << /*integer*/ 1;
6264     }
6265   }
6266 }
6267 
6268 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6269   // Mark any compiler-generated routines with the implicit code_seg attribute.
6270   for (auto *Method : Class->methods()) {
6271     if (Method->isUserProvided())
6272       continue;
6273     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6274       Method->addAttr(A);
6275   }
6276 }
6277 
6278 /// Check class-level dllimport/dllexport attribute.
6279 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6280   Attr *ClassAttr = getDLLAttr(Class);
6281 
6282   // MSVC inherits DLL attributes to partial class template specializations.
6283   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6284     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6285       if (Attr *TemplateAttr =
6286               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6287         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6288         A->setInherited(true);
6289         ClassAttr = A;
6290       }
6291     }
6292   }
6293 
6294   if (!ClassAttr)
6295     return;
6296 
6297   if (!Class->isExternallyVisible()) {
6298     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6299         << Class << ClassAttr;
6300     return;
6301   }
6302 
6303   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6304       !ClassAttr->isInherited()) {
6305     // Diagnose dll attributes on members of class with dll attribute.
6306     for (Decl *Member : Class->decls()) {
6307       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6308         continue;
6309       InheritableAttr *MemberAttr = getDLLAttr(Member);
6310       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6311         continue;
6312 
6313       Diag(MemberAttr->getLocation(),
6314              diag::err_attribute_dll_member_of_dll_class)
6315           << MemberAttr << ClassAttr;
6316       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6317       Member->setInvalidDecl();
6318     }
6319   }
6320 
6321   if (Class->getDescribedClassTemplate())
6322     // Don't inherit dll attribute until the template is instantiated.
6323     return;
6324 
6325   // The class is either imported or exported.
6326   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6327 
6328   // Check if this was a dllimport attribute propagated from a derived class to
6329   // a base class template specialization. We don't apply these attributes to
6330   // static data members.
6331   const bool PropagatedImport =
6332       !ClassExported &&
6333       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6334 
6335   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6336 
6337   // Ignore explicit dllexport on explicit class template instantiation
6338   // declarations, except in MinGW mode.
6339   if (ClassExported && !ClassAttr->isInherited() &&
6340       TSK == TSK_ExplicitInstantiationDeclaration &&
6341       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6342     Class->dropAttr<DLLExportAttr>();
6343     return;
6344   }
6345 
6346   // Force declaration of implicit members so they can inherit the attribute.
6347   ForceDeclarationOfImplicitMembers(Class);
6348 
6349   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6350   // seem to be true in practice?
6351 
6352   for (Decl *Member : Class->decls()) {
6353     VarDecl *VD = dyn_cast<VarDecl>(Member);
6354     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6355 
6356     // Only methods and static fields inherit the attributes.
6357     if (!VD && !MD)
6358       continue;
6359 
6360     if (MD) {
6361       // Don't process deleted methods.
6362       if (MD->isDeleted())
6363         continue;
6364 
6365       if (MD->isInlined()) {
6366         // MinGW does not import or export inline methods. But do it for
6367         // template instantiations.
6368         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6369             TSK != TSK_ExplicitInstantiationDeclaration &&
6370             TSK != TSK_ExplicitInstantiationDefinition)
6371           continue;
6372 
6373         // MSVC versions before 2015 don't export the move assignment operators
6374         // and move constructor, so don't attempt to import/export them if
6375         // we have a definition.
6376         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6377         if ((MD->isMoveAssignmentOperator() ||
6378              (Ctor && Ctor->isMoveConstructor())) &&
6379             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6380           continue;
6381 
6382         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6383         // operator is exported anyway.
6384         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6385             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6386           continue;
6387       }
6388     }
6389 
6390     // Don't apply dllimport attributes to static data members of class template
6391     // instantiations when the attribute is propagated from a derived class.
6392     if (VD && PropagatedImport)
6393       continue;
6394 
6395     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6396       continue;
6397 
6398     if (!getDLLAttr(Member)) {
6399       InheritableAttr *NewAttr = nullptr;
6400 
6401       // Do not export/import inline function when -fno-dllexport-inlines is
6402       // passed. But add attribute for later local static var check.
6403       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6404           TSK != TSK_ExplicitInstantiationDeclaration &&
6405           TSK != TSK_ExplicitInstantiationDefinition) {
6406         if (ClassExported) {
6407           NewAttr = ::new (getASTContext())
6408               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6409         } else {
6410           NewAttr = ::new (getASTContext())
6411               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6412         }
6413       } else {
6414         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6415       }
6416 
6417       NewAttr->setInherited(true);
6418       Member->addAttr(NewAttr);
6419 
6420       if (MD) {
6421         // Propagate DLLAttr to friend re-declarations of MD that have already
6422         // been constructed.
6423         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6424              FD = FD->getPreviousDecl()) {
6425           if (FD->getFriendObjectKind() == Decl::FOK_None)
6426             continue;
6427           assert(!getDLLAttr(FD) &&
6428                  "friend re-decl should not already have a DLLAttr");
6429           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6430           NewAttr->setInherited(true);
6431           FD->addAttr(NewAttr);
6432         }
6433       }
6434     }
6435   }
6436 
6437   if (ClassExported)
6438     DelayedDllExportClasses.push_back(Class);
6439 }
6440 
6441 /// Perform propagation of DLL attributes from a derived class to a
6442 /// templated base class for MS compatibility.
6443 void Sema::propagateDLLAttrToBaseClassTemplate(
6444     CXXRecordDecl *Class, Attr *ClassAttr,
6445     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6446   if (getDLLAttr(
6447           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6448     // If the base class template has a DLL attribute, don't try to change it.
6449     return;
6450   }
6451 
6452   auto TSK = BaseTemplateSpec->getSpecializationKind();
6453   if (!getDLLAttr(BaseTemplateSpec) &&
6454       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6455        TSK == TSK_ImplicitInstantiation)) {
6456     // The template hasn't been instantiated yet (or it has, but only as an
6457     // explicit instantiation declaration or implicit instantiation, which means
6458     // we haven't codegenned any members yet), so propagate the attribute.
6459     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6460     NewAttr->setInherited(true);
6461     BaseTemplateSpec->addAttr(NewAttr);
6462 
6463     // If this was an import, mark that we propagated it from a derived class to
6464     // a base class template specialization.
6465     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6466       ImportAttr->setPropagatedToBaseTemplate();
6467 
6468     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6469     // needs to be run again to work see the new attribute. Otherwise this will
6470     // get run whenever the template is instantiated.
6471     if (TSK != TSK_Undeclared)
6472       checkClassLevelDLLAttribute(BaseTemplateSpec);
6473 
6474     return;
6475   }
6476 
6477   if (getDLLAttr(BaseTemplateSpec)) {
6478     // The template has already been specialized or instantiated with an
6479     // attribute, explicitly or through propagation. We should not try to change
6480     // it.
6481     return;
6482   }
6483 
6484   // The template was previously instantiated or explicitly specialized without
6485   // a dll attribute, It's too late for us to add an attribute, so warn that
6486   // this is unsupported.
6487   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6488       << BaseTemplateSpec->isExplicitSpecialization();
6489   Diag(ClassAttr->getLocation(), diag::note_attribute);
6490   if (BaseTemplateSpec->isExplicitSpecialization()) {
6491     Diag(BaseTemplateSpec->getLocation(),
6492            diag::note_template_class_explicit_specialization_was_here)
6493         << BaseTemplateSpec;
6494   } else {
6495     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6496            diag::note_template_class_instantiation_was_here)
6497         << BaseTemplateSpec;
6498   }
6499 }
6500 
6501 /// Determine the kind of defaulting that would be done for a given function.
6502 ///
6503 /// If the function is both a default constructor and a copy / move constructor
6504 /// (due to having a default argument for the first parameter), this picks
6505 /// CXXDefaultConstructor.
6506 ///
6507 /// FIXME: Check that case is properly handled by all callers.
6508 Sema::DefaultedFunctionKind
6509 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6510   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6511     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6512       if (Ctor->isDefaultConstructor())
6513         return Sema::CXXDefaultConstructor;
6514 
6515       if (Ctor->isCopyConstructor())
6516         return Sema::CXXCopyConstructor;
6517 
6518       if (Ctor->isMoveConstructor())
6519         return Sema::CXXMoveConstructor;
6520     }
6521 
6522     if (MD->isCopyAssignmentOperator())
6523       return Sema::CXXCopyAssignment;
6524 
6525     if (MD->isMoveAssignmentOperator())
6526       return Sema::CXXMoveAssignment;
6527 
6528     if (isa<CXXDestructorDecl>(FD))
6529       return Sema::CXXDestructor;
6530   }
6531 
6532   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6533   case OO_EqualEqual:
6534     return DefaultedComparisonKind::Equal;
6535 
6536   case OO_ExclaimEqual:
6537     return DefaultedComparisonKind::NotEqual;
6538 
6539   case OO_Spaceship:
6540     // No point allowing this if <=> doesn't exist in the current language mode.
6541     if (!getLangOpts().CPlusPlus20)
6542       break;
6543     return DefaultedComparisonKind::ThreeWay;
6544 
6545   case OO_Less:
6546   case OO_LessEqual:
6547   case OO_Greater:
6548   case OO_GreaterEqual:
6549     // No point allowing this if <=> doesn't exist in the current language mode.
6550     if (!getLangOpts().CPlusPlus20)
6551       break;
6552     return DefaultedComparisonKind::Relational;
6553 
6554   default:
6555     break;
6556   }
6557 
6558   // Not defaultable.
6559   return DefaultedFunctionKind();
6560 }
6561 
6562 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6563                                     SourceLocation DefaultLoc) {
6564   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6565   if (DFK.isComparison())
6566     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6567 
6568   switch (DFK.asSpecialMember()) {
6569   case Sema::CXXDefaultConstructor:
6570     S.DefineImplicitDefaultConstructor(DefaultLoc,
6571                                        cast<CXXConstructorDecl>(FD));
6572     break;
6573   case Sema::CXXCopyConstructor:
6574     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6575     break;
6576   case Sema::CXXCopyAssignment:
6577     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6578     break;
6579   case Sema::CXXDestructor:
6580     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6581     break;
6582   case Sema::CXXMoveConstructor:
6583     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6584     break;
6585   case Sema::CXXMoveAssignment:
6586     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6587     break;
6588   case Sema::CXXInvalid:
6589     llvm_unreachable("Invalid special member.");
6590   }
6591 }
6592 
6593 /// Determine whether a type is permitted to be passed or returned in
6594 /// registers, per C++ [class.temporary]p3.
6595 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6596                                TargetInfo::CallingConvKind CCK) {
6597   if (D->isDependentType() || D->isInvalidDecl())
6598     return false;
6599 
6600   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6601   // The PS4 platform ABI follows the behavior of Clang 3.2.
6602   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6603     return !D->hasNonTrivialDestructorForCall() &&
6604            !D->hasNonTrivialCopyConstructorForCall();
6605 
6606   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6607     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6608     bool DtorIsTrivialForCall = false;
6609 
6610     // If a class has at least one non-deleted, trivial copy constructor, it
6611     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6612     //
6613     // Note: This permits classes with non-trivial copy or move ctors to be
6614     // passed in registers, so long as they *also* have a trivial copy ctor,
6615     // which is non-conforming.
6616     if (D->needsImplicitCopyConstructor()) {
6617       if (!D->defaultedCopyConstructorIsDeleted()) {
6618         if (D->hasTrivialCopyConstructor())
6619           CopyCtorIsTrivial = true;
6620         if (D->hasTrivialCopyConstructorForCall())
6621           CopyCtorIsTrivialForCall = true;
6622       }
6623     } else {
6624       for (const CXXConstructorDecl *CD : D->ctors()) {
6625         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6626           if (CD->isTrivial())
6627             CopyCtorIsTrivial = true;
6628           if (CD->isTrivialForCall())
6629             CopyCtorIsTrivialForCall = true;
6630         }
6631       }
6632     }
6633 
6634     if (D->needsImplicitDestructor()) {
6635       if (!D->defaultedDestructorIsDeleted() &&
6636           D->hasTrivialDestructorForCall())
6637         DtorIsTrivialForCall = true;
6638     } else if (const auto *DD = D->getDestructor()) {
6639       if (!DD->isDeleted() && DD->isTrivialForCall())
6640         DtorIsTrivialForCall = true;
6641     }
6642 
6643     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6644     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6645       return true;
6646 
6647     // If a class has a destructor, we'd really like to pass it indirectly
6648     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6649     // impossible for small types, which it will pass in a single register or
6650     // stack slot. Most objects with dtors are large-ish, so handle that early.
6651     // We can't call out all large objects as being indirect because there are
6652     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6653     // how we pass large POD types.
6654 
6655     // Note: This permits small classes with nontrivial destructors to be
6656     // passed in registers, which is non-conforming.
6657     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6658     uint64_t TypeSize = isAArch64 ? 128 : 64;
6659 
6660     if (CopyCtorIsTrivial &&
6661         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6662       return true;
6663     return false;
6664   }
6665 
6666   // Per C++ [class.temporary]p3, the relevant condition is:
6667   //   each copy constructor, move constructor, and destructor of X is
6668   //   either trivial or deleted, and X has at least one non-deleted copy
6669   //   or move constructor
6670   bool HasNonDeletedCopyOrMove = false;
6671 
6672   if (D->needsImplicitCopyConstructor() &&
6673       !D->defaultedCopyConstructorIsDeleted()) {
6674     if (!D->hasTrivialCopyConstructorForCall())
6675       return false;
6676     HasNonDeletedCopyOrMove = true;
6677   }
6678 
6679   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6680       !D->defaultedMoveConstructorIsDeleted()) {
6681     if (!D->hasTrivialMoveConstructorForCall())
6682       return false;
6683     HasNonDeletedCopyOrMove = true;
6684   }
6685 
6686   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6687       !D->hasTrivialDestructorForCall())
6688     return false;
6689 
6690   for (const CXXMethodDecl *MD : D->methods()) {
6691     if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
6692       continue;
6693 
6694     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6695     if (CD && CD->isCopyOrMoveConstructor())
6696       HasNonDeletedCopyOrMove = true;
6697     else if (!isa<CXXDestructorDecl>(MD))
6698       continue;
6699 
6700     if (!MD->isTrivialForCall())
6701       return false;
6702   }
6703 
6704   return HasNonDeletedCopyOrMove;
6705 }
6706 
6707 /// Report an error regarding overriding, along with any relevant
6708 /// overridden methods.
6709 ///
6710 /// \param DiagID the primary error to report.
6711 /// \param MD the overriding method.
6712 static bool
6713 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6714                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6715   bool IssuedDiagnostic = false;
6716   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6717     if (Report(O)) {
6718       if (!IssuedDiagnostic) {
6719         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6720         IssuedDiagnostic = true;
6721       }
6722       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6723     }
6724   }
6725   return IssuedDiagnostic;
6726 }
6727 
6728 /// Perform semantic checks on a class definition that has been
6729 /// completing, introducing implicitly-declared members, checking for
6730 /// abstract types, etc.
6731 ///
6732 /// \param S The scope in which the class was parsed. Null if we didn't just
6733 ///        parse a class definition.
6734 /// \param Record The completed class.
6735 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6736   if (!Record)
6737     return;
6738 
6739   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6740     AbstractUsageInfo Info(*this, Record);
6741     CheckAbstractClassUsage(Info, Record);
6742   }
6743 
6744   // If this is not an aggregate type and has no user-declared constructor,
6745   // complain about any non-static data members of reference or const scalar
6746   // type, since they will never get initializers.
6747   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6748       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6749       !Record->isLambda()) {
6750     bool Complained = false;
6751     for (const auto *F : Record->fields()) {
6752       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6753         continue;
6754 
6755       if (F->getType()->isReferenceType() ||
6756           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6757         if (!Complained) {
6758           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6759             << Record->getTagKind() << Record;
6760           Complained = true;
6761         }
6762 
6763         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6764           << F->getType()->isReferenceType()
6765           << F->getDeclName();
6766       }
6767     }
6768   }
6769 
6770   if (Record->getIdentifier()) {
6771     // C++ [class.mem]p13:
6772     //   If T is the name of a class, then each of the following shall have a
6773     //   name different from T:
6774     //     - every member of every anonymous union that is a member of class T.
6775     //
6776     // C++ [class.mem]p14:
6777     //   In addition, if class T has a user-declared constructor (12.1), every
6778     //   non-static data member of class T shall have a name different from T.
6779     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6780     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6781          ++I) {
6782       NamedDecl *D = (*I)->getUnderlyingDecl();
6783       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6784            Record->hasUserDeclaredConstructor()) ||
6785           isa<IndirectFieldDecl>(D)) {
6786         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6787           << D->getDeclName();
6788         break;
6789       }
6790     }
6791   }
6792 
6793   // Warn if the class has virtual methods but non-virtual public destructor.
6794   if (Record->isPolymorphic() && !Record->isDependentType()) {
6795     CXXDestructorDecl *dtor = Record->getDestructor();
6796     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6797         !Record->hasAttr<FinalAttr>())
6798       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6799            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6800   }
6801 
6802   if (Record->isAbstract()) {
6803     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6804       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6805         << FA->isSpelledAsSealed();
6806       DiagnoseAbstractType(Record);
6807     }
6808   }
6809 
6810   // Warn if the class has a final destructor but is not itself marked final.
6811   if (!Record->hasAttr<FinalAttr>()) {
6812     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6813       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6814         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6815             << FA->isSpelledAsSealed()
6816             << FixItHint::CreateInsertion(
6817                    getLocForEndOfToken(Record->getLocation()),
6818                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6819         Diag(Record->getLocation(),
6820              diag::note_final_dtor_non_final_class_silence)
6821             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6822       }
6823     }
6824   }
6825 
6826   // See if trivial_abi has to be dropped.
6827   if (Record->hasAttr<TrivialABIAttr>())
6828     checkIllFormedTrivialABIStruct(*Record);
6829 
6830   // Set HasTrivialSpecialMemberForCall if the record has attribute
6831   // "trivial_abi".
6832   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6833 
6834   if (HasTrivialABI)
6835     Record->setHasTrivialSpecialMemberForCall();
6836 
6837   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6838   // We check these last because they can depend on the properties of the
6839   // primary comparison functions (==, <=>).
6840   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6841 
6842   // Perform checks that can't be done until we know all the properties of a
6843   // member function (whether it's defaulted, deleted, virtual, overriding,
6844   // ...).
6845   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6846     // A static function cannot override anything.
6847     if (MD->getStorageClass() == SC_Static) {
6848       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6849                           [](const CXXMethodDecl *) { return true; }))
6850         return;
6851     }
6852 
6853     // A deleted function cannot override a non-deleted function and vice
6854     // versa.
6855     if (ReportOverrides(*this,
6856                         MD->isDeleted() ? diag::err_deleted_override
6857                                         : diag::err_non_deleted_override,
6858                         MD, [&](const CXXMethodDecl *V) {
6859                           return MD->isDeleted() != V->isDeleted();
6860                         })) {
6861       if (MD->isDefaulted() && MD->isDeleted())
6862         // Explain why this defaulted function was deleted.
6863         DiagnoseDeletedDefaultedFunction(MD);
6864       return;
6865     }
6866 
6867     // A consteval function cannot override a non-consteval function and vice
6868     // versa.
6869     if (ReportOverrides(*this,
6870                         MD->isConsteval() ? diag::err_consteval_override
6871                                           : diag::err_non_consteval_override,
6872                         MD, [&](const CXXMethodDecl *V) {
6873                           return MD->isConsteval() != V->isConsteval();
6874                         })) {
6875       if (MD->isDefaulted() && MD->isDeleted())
6876         // Explain why this defaulted function was deleted.
6877         DiagnoseDeletedDefaultedFunction(MD);
6878       return;
6879     }
6880   };
6881 
6882   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6883     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6884       return false;
6885 
6886     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6887     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6888         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6889       DefaultedSecondaryComparisons.push_back(FD);
6890       return true;
6891     }
6892 
6893     CheckExplicitlyDefaultedFunction(S, FD);
6894     return false;
6895   };
6896 
6897   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6898     // Check whether the explicitly-defaulted members are valid.
6899     bool Incomplete = CheckForDefaultedFunction(M);
6900 
6901     // Skip the rest of the checks for a member of a dependent class.
6902     if (Record->isDependentType())
6903       return;
6904 
6905     // For an explicitly defaulted or deleted special member, we defer
6906     // determining triviality until the class is complete. That time is now!
6907     CXXSpecialMember CSM = getSpecialMember(M);
6908     if (!M->isImplicit() && !M->isUserProvided()) {
6909       if (CSM != CXXInvalid) {
6910         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6911         // Inform the class that we've finished declaring this member.
6912         Record->finishedDefaultedOrDeletedMember(M);
6913         M->setTrivialForCall(
6914             HasTrivialABI ||
6915             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6916         Record->setTrivialForCallFlags(M);
6917       }
6918     }
6919 
6920     // Set triviality for the purpose of calls if this is a user-provided
6921     // copy/move constructor or destructor.
6922     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6923          CSM == CXXDestructor) && M->isUserProvided()) {
6924       M->setTrivialForCall(HasTrivialABI);
6925       Record->setTrivialForCallFlags(M);
6926     }
6927 
6928     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6929         M->hasAttr<DLLExportAttr>()) {
6930       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6931           M->isTrivial() &&
6932           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6933            CSM == CXXDestructor))
6934         M->dropAttr<DLLExportAttr>();
6935 
6936       if (M->hasAttr<DLLExportAttr>()) {
6937         // Define after any fields with in-class initializers have been parsed.
6938         DelayedDllExportMemberFunctions.push_back(M);
6939       }
6940     }
6941 
6942     // Define defaulted constexpr virtual functions that override a base class
6943     // function right away.
6944     // FIXME: We can defer doing this until the vtable is marked as used.
6945     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6946       DefineDefaultedFunction(*this, M, M->getLocation());
6947 
6948     if (!Incomplete)
6949       CheckCompletedMemberFunction(M);
6950   };
6951 
6952   // Check the destructor before any other member function. We need to
6953   // determine whether it's trivial in order to determine whether the claas
6954   // type is a literal type, which is a prerequisite for determining whether
6955   // other special member functions are valid and whether they're implicitly
6956   // 'constexpr'.
6957   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6958     CompleteMemberFunction(Dtor);
6959 
6960   bool HasMethodWithOverrideControl = false,
6961        HasOverridingMethodWithoutOverrideControl = false;
6962   for (auto *D : Record->decls()) {
6963     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6964       // FIXME: We could do this check for dependent types with non-dependent
6965       // bases.
6966       if (!Record->isDependentType()) {
6967         // See if a method overloads virtual methods in a base
6968         // class without overriding any.
6969         if (!M->isStatic())
6970           DiagnoseHiddenVirtualMethods(M);
6971         if (M->hasAttr<OverrideAttr>())
6972           HasMethodWithOverrideControl = true;
6973         else if (M->size_overridden_methods() > 0)
6974           HasOverridingMethodWithoutOverrideControl = true;
6975       }
6976 
6977       if (!isa<CXXDestructorDecl>(M))
6978         CompleteMemberFunction(M);
6979     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6980       CheckForDefaultedFunction(
6981           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6982     }
6983   }
6984 
6985   if (HasOverridingMethodWithoutOverrideControl) {
6986     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6987     for (auto *M : Record->methods())
6988       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6989   }
6990 
6991   // Check the defaulted secondary comparisons after any other member functions.
6992   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6993     CheckExplicitlyDefaultedFunction(S, FD);
6994 
6995     // If this is a member function, we deferred checking it until now.
6996     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6997       CheckCompletedMemberFunction(MD);
6998   }
6999 
7000   // ms_struct is a request to use the same ABI rules as MSVC.  Check
7001   // whether this class uses any C++ features that are implemented
7002   // completely differently in MSVC, and if so, emit a diagnostic.
7003   // That diagnostic defaults to an error, but we allow projects to
7004   // map it down to a warning (or ignore it).  It's a fairly common
7005   // practice among users of the ms_struct pragma to mass-annotate
7006   // headers, sweeping up a bunch of types that the project doesn't
7007   // really rely on MSVC-compatible layout for.  We must therefore
7008   // support "ms_struct except for C++ stuff" as a secondary ABI.
7009   // Don't emit this diagnostic if the feature was enabled as a
7010   // language option (as opposed to via a pragma or attribute), as
7011   // the option -mms-bitfields otherwise essentially makes it impossible
7012   // to build C++ code, unless this diagnostic is turned off.
7013   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
7014       (Record->isPolymorphic() || Record->getNumBases())) {
7015     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
7016   }
7017 
7018   checkClassLevelDLLAttribute(Record);
7019   checkClassLevelCodeSegAttribute(Record);
7020 
7021   bool ClangABICompat4 =
7022       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7023   TargetInfo::CallingConvKind CCK =
7024       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7025   bool CanPass = canPassInRegisters(*this, Record, CCK);
7026 
7027   // Do not change ArgPassingRestrictions if it has already been set to
7028   // APK_CanNeverPassInRegs.
7029   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
7030     Record->setArgPassingRestrictions(CanPass
7031                                           ? RecordDecl::APK_CanPassInRegs
7032                                           : RecordDecl::APK_CannotPassInRegs);
7033 
7034   // If canPassInRegisters returns true despite the record having a non-trivial
7035   // destructor, the record is destructed in the callee. This happens only when
7036   // the record or one of its subobjects has a field annotated with trivial_abi
7037   // or a field qualified with ObjC __strong/__weak.
7038   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7039     Record->setParamDestroyedInCallee(true);
7040   else if (Record->hasNonTrivialDestructor())
7041     Record->setParamDestroyedInCallee(CanPass);
7042 
7043   if (getLangOpts().ForceEmitVTables) {
7044     // If we want to emit all the vtables, we need to mark it as used.  This
7045     // is especially required for cases like vtable assumption loads.
7046     MarkVTableUsed(Record->getInnerLocStart(), Record);
7047   }
7048 
7049   if (getLangOpts().CUDA) {
7050     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7051       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7052     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7053       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7054   }
7055 }
7056 
7057 /// Look up the special member function that would be called by a special
7058 /// member function for a subobject of class type.
7059 ///
7060 /// \param Class The class type of the subobject.
7061 /// \param CSM The kind of special member function.
7062 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7063 /// \param ConstRHS True if this is a copy operation with a const object
7064 ///        on its RHS, that is, if the argument to the outer special member
7065 ///        function is 'const' and this is not a field marked 'mutable'.
7066 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7067     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7068     unsigned FieldQuals, bool ConstRHS) {
7069   unsigned LHSQuals = 0;
7070   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7071     LHSQuals = FieldQuals;
7072 
7073   unsigned RHSQuals = FieldQuals;
7074   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7075     RHSQuals = 0;
7076   else if (ConstRHS)
7077     RHSQuals |= Qualifiers::Const;
7078 
7079   return S.LookupSpecialMember(Class, CSM,
7080                                RHSQuals & Qualifiers::Const,
7081                                RHSQuals & Qualifiers::Volatile,
7082                                false,
7083                                LHSQuals & Qualifiers::Const,
7084                                LHSQuals & Qualifiers::Volatile);
7085 }
7086 
7087 class Sema::InheritedConstructorInfo {
7088   Sema &S;
7089   SourceLocation UseLoc;
7090 
7091   /// A mapping from the base classes through which the constructor was
7092   /// inherited to the using shadow declaration in that base class (or a null
7093   /// pointer if the constructor was declared in that base class).
7094   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7095       InheritedFromBases;
7096 
7097 public:
7098   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7099                            ConstructorUsingShadowDecl *Shadow)
7100       : S(S), UseLoc(UseLoc) {
7101     bool DiagnosedMultipleConstructedBases = false;
7102     CXXRecordDecl *ConstructedBase = nullptr;
7103     BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7104 
7105     // Find the set of such base class subobjects and check that there's a
7106     // unique constructed subobject.
7107     for (auto *D : Shadow->redecls()) {
7108       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7109       auto *DNominatedBase = DShadow->getNominatedBaseClass();
7110       auto *DConstructedBase = DShadow->getConstructedBaseClass();
7111 
7112       InheritedFromBases.insert(
7113           std::make_pair(DNominatedBase->getCanonicalDecl(),
7114                          DShadow->getNominatedBaseClassShadowDecl()));
7115       if (DShadow->constructsVirtualBase())
7116         InheritedFromBases.insert(
7117             std::make_pair(DConstructedBase->getCanonicalDecl(),
7118                            DShadow->getConstructedBaseClassShadowDecl()));
7119       else
7120         assert(DNominatedBase == DConstructedBase);
7121 
7122       // [class.inhctor.init]p2:
7123       //   If the constructor was inherited from multiple base class subobjects
7124       //   of type B, the program is ill-formed.
7125       if (!ConstructedBase) {
7126         ConstructedBase = DConstructedBase;
7127         ConstructedBaseIntroducer = D->getIntroducer();
7128       } else if (ConstructedBase != DConstructedBase &&
7129                  !Shadow->isInvalidDecl()) {
7130         if (!DiagnosedMultipleConstructedBases) {
7131           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7132               << Shadow->getTargetDecl();
7133           S.Diag(ConstructedBaseIntroducer->getLocation(),
7134                  diag::note_ambiguous_inherited_constructor_using)
7135               << ConstructedBase;
7136           DiagnosedMultipleConstructedBases = true;
7137         }
7138         S.Diag(D->getIntroducer()->getLocation(),
7139                diag::note_ambiguous_inherited_constructor_using)
7140             << DConstructedBase;
7141       }
7142     }
7143 
7144     if (DiagnosedMultipleConstructedBases)
7145       Shadow->setInvalidDecl();
7146   }
7147 
7148   /// Find the constructor to use for inherited construction of a base class,
7149   /// and whether that base class constructor inherits the constructor from a
7150   /// virtual base class (in which case it won't actually invoke it).
7151   std::pair<CXXConstructorDecl *, bool>
7152   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7153     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7154     if (It == InheritedFromBases.end())
7155       return std::make_pair(nullptr, false);
7156 
7157     // This is an intermediary class.
7158     if (It->second)
7159       return std::make_pair(
7160           S.findInheritingConstructor(UseLoc, Ctor, It->second),
7161           It->second->constructsVirtualBase());
7162 
7163     // This is the base class from which the constructor was inherited.
7164     return std::make_pair(Ctor, false);
7165   }
7166 };
7167 
7168 /// Is the special member function which would be selected to perform the
7169 /// specified operation on the specified class type a constexpr constructor?
7170 static bool
7171 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7172                          Sema::CXXSpecialMember CSM, unsigned Quals,
7173                          bool ConstRHS,
7174                          CXXConstructorDecl *InheritedCtor = nullptr,
7175                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7176   // If we're inheriting a constructor, see if we need to call it for this base
7177   // class.
7178   if (InheritedCtor) {
7179     assert(CSM == Sema::CXXDefaultConstructor);
7180     auto BaseCtor =
7181         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7182     if (BaseCtor)
7183       return BaseCtor->isConstexpr();
7184   }
7185 
7186   if (CSM == Sema::CXXDefaultConstructor)
7187     return ClassDecl->hasConstexprDefaultConstructor();
7188   if (CSM == Sema::CXXDestructor)
7189     return ClassDecl->hasConstexprDestructor();
7190 
7191   Sema::SpecialMemberOverloadResult SMOR =
7192       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7193   if (!SMOR.getMethod())
7194     // A constructor we wouldn't select can't be "involved in initializing"
7195     // anything.
7196     return true;
7197   return SMOR.getMethod()->isConstexpr();
7198 }
7199 
7200 /// Determine whether the specified special member function would be constexpr
7201 /// if it were implicitly defined.
7202 static bool defaultedSpecialMemberIsConstexpr(
7203     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7204     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7205     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7206   if (!S.getLangOpts().CPlusPlus11)
7207     return false;
7208 
7209   // C++11 [dcl.constexpr]p4:
7210   // In the definition of a constexpr constructor [...]
7211   bool Ctor = true;
7212   switch (CSM) {
7213   case Sema::CXXDefaultConstructor:
7214     if (Inherited)
7215       break;
7216     // Since default constructor lookup is essentially trivial (and cannot
7217     // involve, for instance, template instantiation), we compute whether a
7218     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7219     //
7220     // This is important for performance; we need to know whether the default
7221     // constructor is constexpr to determine whether the type is a literal type.
7222     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7223 
7224   case Sema::CXXCopyConstructor:
7225   case Sema::CXXMoveConstructor:
7226     // For copy or move constructors, we need to perform overload resolution.
7227     break;
7228 
7229   case Sema::CXXCopyAssignment:
7230   case Sema::CXXMoveAssignment:
7231     if (!S.getLangOpts().CPlusPlus14)
7232       return false;
7233     // In C++1y, we need to perform overload resolution.
7234     Ctor = false;
7235     break;
7236 
7237   case Sema::CXXDestructor:
7238     return ClassDecl->defaultedDestructorIsConstexpr();
7239 
7240   case Sema::CXXInvalid:
7241     return false;
7242   }
7243 
7244   //   -- if the class is a non-empty union, or for each non-empty anonymous
7245   //      union member of a non-union class, exactly one non-static data member
7246   //      shall be initialized; [DR1359]
7247   //
7248   // If we squint, this is guaranteed, since exactly one non-static data member
7249   // will be initialized (if the constructor isn't deleted), we just don't know
7250   // which one.
7251   if (Ctor && ClassDecl->isUnion())
7252     return CSM == Sema::CXXDefaultConstructor
7253                ? ClassDecl->hasInClassInitializer() ||
7254                      !ClassDecl->hasVariantMembers()
7255                : true;
7256 
7257   //   -- the class shall not have any virtual base classes;
7258   if (Ctor && ClassDecl->getNumVBases())
7259     return false;
7260 
7261   // C++1y [class.copy]p26:
7262   //   -- [the class] is a literal type, and
7263   if (!Ctor && !ClassDecl->isLiteral())
7264     return false;
7265 
7266   //   -- every constructor involved in initializing [...] base class
7267   //      sub-objects shall be a constexpr constructor;
7268   //   -- the assignment operator selected to copy/move each direct base
7269   //      class is a constexpr function, and
7270   for (const auto &B : ClassDecl->bases()) {
7271     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7272     if (!BaseType) continue;
7273 
7274     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7275     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7276                                   InheritedCtor, Inherited))
7277       return false;
7278   }
7279 
7280   //   -- every constructor involved in initializing non-static data members
7281   //      [...] shall be a constexpr constructor;
7282   //   -- every non-static data member and base class sub-object shall be
7283   //      initialized
7284   //   -- for each non-static data member of X that is of class type (or array
7285   //      thereof), the assignment operator selected to copy/move that member is
7286   //      a constexpr function
7287   for (const auto *F : ClassDecl->fields()) {
7288     if (F->isInvalidDecl())
7289       continue;
7290     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7291       continue;
7292     QualType BaseType = S.Context.getBaseElementType(F->getType());
7293     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7294       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7295       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7296                                     BaseType.getCVRQualifiers(),
7297                                     ConstArg && !F->isMutable()))
7298         return false;
7299     } else if (CSM == Sema::CXXDefaultConstructor) {
7300       return false;
7301     }
7302   }
7303 
7304   // All OK, it's constexpr!
7305   return true;
7306 }
7307 
7308 namespace {
7309 /// RAII object to register a defaulted function as having its exception
7310 /// specification computed.
7311 struct ComputingExceptionSpec {
7312   Sema &S;
7313 
7314   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7315       : S(S) {
7316     Sema::CodeSynthesisContext Ctx;
7317     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7318     Ctx.PointOfInstantiation = Loc;
7319     Ctx.Entity = FD;
7320     S.pushCodeSynthesisContext(Ctx);
7321   }
7322   ~ComputingExceptionSpec() {
7323     S.popCodeSynthesisContext();
7324   }
7325 };
7326 }
7327 
7328 static Sema::ImplicitExceptionSpecification
7329 ComputeDefaultedSpecialMemberExceptionSpec(
7330     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7331     Sema::InheritedConstructorInfo *ICI);
7332 
7333 static Sema::ImplicitExceptionSpecification
7334 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7335                                         FunctionDecl *FD,
7336                                         Sema::DefaultedComparisonKind DCK);
7337 
7338 static Sema::ImplicitExceptionSpecification
7339 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7340   auto DFK = S.getDefaultedFunctionKind(FD);
7341   if (DFK.isSpecialMember())
7342     return ComputeDefaultedSpecialMemberExceptionSpec(
7343         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7344   if (DFK.isComparison())
7345     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7346                                                    DFK.asComparison());
7347 
7348   auto *CD = cast<CXXConstructorDecl>(FD);
7349   assert(CD->getInheritedConstructor() &&
7350          "only defaulted functions and inherited constructors have implicit "
7351          "exception specs");
7352   Sema::InheritedConstructorInfo ICI(
7353       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7354   return ComputeDefaultedSpecialMemberExceptionSpec(
7355       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7356 }
7357 
7358 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7359                                                             CXXMethodDecl *MD) {
7360   FunctionProtoType::ExtProtoInfo EPI;
7361 
7362   // Build an exception specification pointing back at this member.
7363   EPI.ExceptionSpec.Type = EST_Unevaluated;
7364   EPI.ExceptionSpec.SourceDecl = MD;
7365 
7366   // Set the calling convention to the default for C++ instance methods.
7367   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7368       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7369                                             /*IsCXXMethod=*/true));
7370   return EPI;
7371 }
7372 
7373 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7374   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7375   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7376     return;
7377 
7378   // Evaluate the exception specification.
7379   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7380   auto ESI = IES.getExceptionSpec();
7381 
7382   // Update the type of the special member to use it.
7383   UpdateExceptionSpec(FD, ESI);
7384 }
7385 
7386 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7387   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7388 
7389   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7390   if (!DefKind) {
7391     assert(FD->getDeclContext()->isDependentContext());
7392     return;
7393   }
7394 
7395   if (DefKind.isComparison())
7396     UnusedPrivateFields.clear();
7397 
7398   if (DefKind.isSpecialMember()
7399           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7400                                                   DefKind.asSpecialMember())
7401           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7402     FD->setInvalidDecl();
7403 }
7404 
7405 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7406                                                  CXXSpecialMember CSM) {
7407   CXXRecordDecl *RD = MD->getParent();
7408 
7409   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7410          "not an explicitly-defaulted special member");
7411 
7412   // Defer all checking for special members of a dependent type.
7413   if (RD->isDependentType())
7414     return false;
7415 
7416   // Whether this was the first-declared instance of the constructor.
7417   // This affects whether we implicitly add an exception spec and constexpr.
7418   bool First = MD == MD->getCanonicalDecl();
7419 
7420   bool HadError = false;
7421 
7422   // C++11 [dcl.fct.def.default]p1:
7423   //   A function that is explicitly defaulted shall
7424   //     -- be a special member function [...] (checked elsewhere),
7425   //     -- have the same type (except for ref-qualifiers, and except that a
7426   //        copy operation can take a non-const reference) as an implicit
7427   //        declaration, and
7428   //     -- not have default arguments.
7429   // C++2a changes the second bullet to instead delete the function if it's
7430   // defaulted on its first declaration, unless it's "an assignment operator,
7431   // and its return type differs or its parameter type is not a reference".
7432   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7433   bool ShouldDeleteForTypeMismatch = false;
7434   unsigned ExpectedParams = 1;
7435   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7436     ExpectedParams = 0;
7437   if (MD->getNumParams() != ExpectedParams) {
7438     // This checks for default arguments: a copy or move constructor with a
7439     // default argument is classified as a default constructor, and assignment
7440     // operations and destructors can't have default arguments.
7441     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7442       << CSM << MD->getSourceRange();
7443     HadError = true;
7444   } else if (MD->isVariadic()) {
7445     if (DeleteOnTypeMismatch)
7446       ShouldDeleteForTypeMismatch = true;
7447     else {
7448       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7449         << CSM << MD->getSourceRange();
7450       HadError = true;
7451     }
7452   }
7453 
7454   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7455 
7456   bool CanHaveConstParam = false;
7457   if (CSM == CXXCopyConstructor)
7458     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7459   else if (CSM == CXXCopyAssignment)
7460     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7461 
7462   QualType ReturnType = Context.VoidTy;
7463   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7464     // Check for return type matching.
7465     ReturnType = Type->getReturnType();
7466 
7467     QualType DeclType = Context.getTypeDeclType(RD);
7468     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7469     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7470 
7471     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7472       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7473         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7474       HadError = true;
7475     }
7476 
7477     // A defaulted special member cannot have cv-qualifiers.
7478     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7479       if (DeleteOnTypeMismatch)
7480         ShouldDeleteForTypeMismatch = true;
7481       else {
7482         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7483           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7484         HadError = true;
7485       }
7486     }
7487   }
7488 
7489   // Check for parameter type matching.
7490   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7491   bool HasConstParam = false;
7492   if (ExpectedParams && ArgType->isReferenceType()) {
7493     // Argument must be reference to possibly-const T.
7494     QualType ReferentType = ArgType->getPointeeType();
7495     HasConstParam = ReferentType.isConstQualified();
7496 
7497     if (ReferentType.isVolatileQualified()) {
7498       if (DeleteOnTypeMismatch)
7499         ShouldDeleteForTypeMismatch = true;
7500       else {
7501         Diag(MD->getLocation(),
7502              diag::err_defaulted_special_member_volatile_param) << CSM;
7503         HadError = true;
7504       }
7505     }
7506 
7507     if (HasConstParam && !CanHaveConstParam) {
7508       if (DeleteOnTypeMismatch)
7509         ShouldDeleteForTypeMismatch = true;
7510       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7511         Diag(MD->getLocation(),
7512              diag::err_defaulted_special_member_copy_const_param)
7513           << (CSM == CXXCopyAssignment);
7514         // FIXME: Explain why this special member can't be const.
7515         HadError = true;
7516       } else {
7517         Diag(MD->getLocation(),
7518              diag::err_defaulted_special_member_move_const_param)
7519           << (CSM == CXXMoveAssignment);
7520         HadError = true;
7521       }
7522     }
7523   } else if (ExpectedParams) {
7524     // A copy assignment operator can take its argument by value, but a
7525     // defaulted one cannot.
7526     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7527     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7528     HadError = true;
7529   }
7530 
7531   // C++11 [dcl.fct.def.default]p2:
7532   //   An explicitly-defaulted function may be declared constexpr only if it
7533   //   would have been implicitly declared as constexpr,
7534   // Do not apply this rule to members of class templates, since core issue 1358
7535   // makes such functions always instantiate to constexpr functions. For
7536   // functions which cannot be constexpr (for non-constructors in C++11 and for
7537   // destructors in C++14 and C++17), this is checked elsewhere.
7538   //
7539   // FIXME: This should not apply if the member is deleted.
7540   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7541                                                      HasConstParam);
7542   if ((getLangOpts().CPlusPlus20 ||
7543        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7544                                   : isa<CXXConstructorDecl>(MD))) &&
7545       MD->isConstexpr() && !Constexpr &&
7546       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7547     Diag(MD->getBeginLoc(), MD->isConsteval()
7548                                 ? diag::err_incorrect_defaulted_consteval
7549                                 : diag::err_incorrect_defaulted_constexpr)
7550         << CSM;
7551     // FIXME: Explain why the special member can't be constexpr.
7552     HadError = true;
7553   }
7554 
7555   if (First) {
7556     // C++2a [dcl.fct.def.default]p3:
7557     //   If a function is explicitly defaulted on its first declaration, it is
7558     //   implicitly considered to be constexpr if the implicit declaration
7559     //   would be.
7560     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7561                                           ? ConstexprSpecKind::Consteval
7562                                           : ConstexprSpecKind::Constexpr)
7563                                    : ConstexprSpecKind::Unspecified);
7564 
7565     if (!Type->hasExceptionSpec()) {
7566       // C++2a [except.spec]p3:
7567       //   If a declaration of a function does not have a noexcept-specifier
7568       //   [and] is defaulted on its first declaration, [...] the exception
7569       //   specification is as specified below
7570       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7571       EPI.ExceptionSpec.Type = EST_Unevaluated;
7572       EPI.ExceptionSpec.SourceDecl = MD;
7573       MD->setType(Context.getFunctionType(ReturnType,
7574                                           llvm::makeArrayRef(&ArgType,
7575                                                              ExpectedParams),
7576                                           EPI));
7577     }
7578   }
7579 
7580   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7581     if (First) {
7582       SetDeclDeleted(MD, MD->getLocation());
7583       if (!inTemplateInstantiation() && !HadError) {
7584         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7585         if (ShouldDeleteForTypeMismatch) {
7586           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7587         } else {
7588           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7589         }
7590       }
7591       if (ShouldDeleteForTypeMismatch && !HadError) {
7592         Diag(MD->getLocation(),
7593              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7594       }
7595     } else {
7596       // C++11 [dcl.fct.def.default]p4:
7597       //   [For a] user-provided explicitly-defaulted function [...] if such a
7598       //   function is implicitly defined as deleted, the program is ill-formed.
7599       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7600       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7601       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7602       HadError = true;
7603     }
7604   }
7605 
7606   return HadError;
7607 }
7608 
7609 namespace {
7610 /// Helper class for building and checking a defaulted comparison.
7611 ///
7612 /// Defaulted functions are built in two phases:
7613 ///
7614 ///  * First, the set of operations that the function will perform are
7615 ///    identified, and some of them are checked. If any of the checked
7616 ///    operations is invalid in certain ways, the comparison function is
7617 ///    defined as deleted and no body is built.
7618 ///  * Then, if the function is not defined as deleted, the body is built.
7619 ///
7620 /// This is accomplished by performing two visitation steps over the eventual
7621 /// body of the function.
7622 template<typename Derived, typename ResultList, typename Result,
7623          typename Subobject>
7624 class DefaultedComparisonVisitor {
7625 public:
7626   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7627 
7628   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7629                              DefaultedComparisonKind DCK)
7630       : S(S), RD(RD), FD(FD), DCK(DCK) {
7631     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7632       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7633       // UnresolvedSet to avoid this copy.
7634       Fns.assign(Info->getUnqualifiedLookups().begin(),
7635                  Info->getUnqualifiedLookups().end());
7636     }
7637   }
7638 
7639   ResultList visit() {
7640     // The type of an lvalue naming a parameter of this function.
7641     QualType ParamLvalType =
7642         FD->getParamDecl(0)->getType().getNonReferenceType();
7643 
7644     ResultList Results;
7645 
7646     switch (DCK) {
7647     case DefaultedComparisonKind::None:
7648       llvm_unreachable("not a defaulted comparison");
7649 
7650     case DefaultedComparisonKind::Equal:
7651     case DefaultedComparisonKind::ThreeWay:
7652       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7653       return Results;
7654 
7655     case DefaultedComparisonKind::NotEqual:
7656     case DefaultedComparisonKind::Relational:
7657       Results.add(getDerived().visitExpandedSubobject(
7658           ParamLvalType, getDerived().getCompleteObject()));
7659       return Results;
7660     }
7661     llvm_unreachable("");
7662   }
7663 
7664 protected:
7665   Derived &getDerived() { return static_cast<Derived&>(*this); }
7666 
7667   /// Visit the expanded list of subobjects of the given type, as specified in
7668   /// C++2a [class.compare.default].
7669   ///
7670   /// \return \c true if the ResultList object said we're done, \c false if not.
7671   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7672                        Qualifiers Quals) {
7673     // C++2a [class.compare.default]p4:
7674     //   The direct base class subobjects of C
7675     for (CXXBaseSpecifier &Base : Record->bases())
7676       if (Results.add(getDerived().visitSubobject(
7677               S.Context.getQualifiedType(Base.getType(), Quals),
7678               getDerived().getBase(&Base))))
7679         return true;
7680 
7681     //   followed by the non-static data members of C
7682     for (FieldDecl *Field : Record->fields()) {
7683       // Recursively expand anonymous structs.
7684       if (Field->isAnonymousStructOrUnion()) {
7685         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7686                             Quals))
7687           return true;
7688         continue;
7689       }
7690 
7691       // Figure out the type of an lvalue denoting this field.
7692       Qualifiers FieldQuals = Quals;
7693       if (Field->isMutable())
7694         FieldQuals.removeConst();
7695       QualType FieldType =
7696           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7697 
7698       if (Results.add(getDerived().visitSubobject(
7699               FieldType, getDerived().getField(Field))))
7700         return true;
7701     }
7702 
7703     //   form a list of subobjects.
7704     return false;
7705   }
7706 
7707   Result visitSubobject(QualType Type, Subobject Subobj) {
7708     //   In that list, any subobject of array type is recursively expanded
7709     const ArrayType *AT = S.Context.getAsArrayType(Type);
7710     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7711       return getDerived().visitSubobjectArray(CAT->getElementType(),
7712                                               CAT->getSize(), Subobj);
7713     return getDerived().visitExpandedSubobject(Type, Subobj);
7714   }
7715 
7716   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7717                              Subobject Subobj) {
7718     return getDerived().visitSubobject(Type, Subobj);
7719   }
7720 
7721 protected:
7722   Sema &S;
7723   CXXRecordDecl *RD;
7724   FunctionDecl *FD;
7725   DefaultedComparisonKind DCK;
7726   UnresolvedSet<16> Fns;
7727 };
7728 
7729 /// Information about a defaulted comparison, as determined by
7730 /// DefaultedComparisonAnalyzer.
7731 struct DefaultedComparisonInfo {
7732   bool Deleted = false;
7733   bool Constexpr = true;
7734   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7735 
7736   static DefaultedComparisonInfo deleted() {
7737     DefaultedComparisonInfo Deleted;
7738     Deleted.Deleted = true;
7739     return Deleted;
7740   }
7741 
7742   bool add(const DefaultedComparisonInfo &R) {
7743     Deleted |= R.Deleted;
7744     Constexpr &= R.Constexpr;
7745     Category = commonComparisonType(Category, R.Category);
7746     return Deleted;
7747   }
7748 };
7749 
7750 /// An element in the expanded list of subobjects of a defaulted comparison, as
7751 /// specified in C++2a [class.compare.default]p4.
7752 struct DefaultedComparisonSubobject {
7753   enum { CompleteObject, Member, Base } Kind;
7754   NamedDecl *Decl;
7755   SourceLocation Loc;
7756 };
7757 
7758 /// A visitor over the notional body of a defaulted comparison that determines
7759 /// whether that body would be deleted or constexpr.
7760 class DefaultedComparisonAnalyzer
7761     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7762                                         DefaultedComparisonInfo,
7763                                         DefaultedComparisonInfo,
7764                                         DefaultedComparisonSubobject> {
7765 public:
7766   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7767 
7768 private:
7769   DiagnosticKind Diagnose;
7770 
7771 public:
7772   using Base = DefaultedComparisonVisitor;
7773   using Result = DefaultedComparisonInfo;
7774   using Subobject = DefaultedComparisonSubobject;
7775 
7776   friend Base;
7777 
7778   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7779                               DefaultedComparisonKind DCK,
7780                               DiagnosticKind Diagnose = NoDiagnostics)
7781       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7782 
7783   Result visit() {
7784     if ((DCK == DefaultedComparisonKind::Equal ||
7785          DCK == DefaultedComparisonKind::ThreeWay) &&
7786         RD->hasVariantMembers()) {
7787       // C++2a [class.compare.default]p2 [P2002R0]:
7788       //   A defaulted comparison operator function for class C is defined as
7789       //   deleted if [...] C has variant members.
7790       if (Diagnose == ExplainDeleted) {
7791         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7792           << FD << RD->isUnion() << RD;
7793       }
7794       return Result::deleted();
7795     }
7796 
7797     return Base::visit();
7798   }
7799 
7800 private:
7801   Subobject getCompleteObject() {
7802     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7803   }
7804 
7805   Subobject getBase(CXXBaseSpecifier *Base) {
7806     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7807                      Base->getBaseTypeLoc()};
7808   }
7809 
7810   Subobject getField(FieldDecl *Field) {
7811     return Subobject{Subobject::Member, Field, Field->getLocation()};
7812   }
7813 
7814   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7815     // C++2a [class.compare.default]p2 [P2002R0]:
7816     //   A defaulted <=> or == operator function for class C is defined as
7817     //   deleted if any non-static data member of C is of reference type
7818     if (Type->isReferenceType()) {
7819       if (Diagnose == ExplainDeleted) {
7820         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7821             << FD << RD;
7822       }
7823       return Result::deleted();
7824     }
7825 
7826     // [...] Let xi be an lvalue denoting the ith element [...]
7827     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7828     Expr *Args[] = {&Xi, &Xi};
7829 
7830     // All operators start by trying to apply that same operator recursively.
7831     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7832     assert(OO != OO_None && "not an overloaded operator!");
7833     return visitBinaryOperator(OO, Args, Subobj);
7834   }
7835 
7836   Result
7837   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7838                       Subobject Subobj,
7839                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7840     // Note that there is no need to consider rewritten candidates here if
7841     // we've already found there is no viable 'operator<=>' candidate (and are
7842     // considering synthesizing a '<=>' from '==' and '<').
7843     OverloadCandidateSet CandidateSet(
7844         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7845         OverloadCandidateSet::OperatorRewriteInfo(
7846             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7847 
7848     /// C++2a [class.compare.default]p1 [P2002R0]:
7849     ///   [...] the defaulted function itself is never a candidate for overload
7850     ///   resolution [...]
7851     CandidateSet.exclude(FD);
7852 
7853     if (Args[0]->getType()->isOverloadableType())
7854       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7855     else
7856       // FIXME: We determine whether this is a valid expression by checking to
7857       // see if there's a viable builtin operator candidate for it. That isn't
7858       // really what the rules ask us to do, but should give the right results.
7859       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7860 
7861     Result R;
7862 
7863     OverloadCandidateSet::iterator Best;
7864     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7865     case OR_Success: {
7866       // C++2a [class.compare.secondary]p2 [P2002R0]:
7867       //   The operator function [...] is defined as deleted if [...] the
7868       //   candidate selected by overload resolution is not a rewritten
7869       //   candidate.
7870       if ((DCK == DefaultedComparisonKind::NotEqual ||
7871            DCK == DefaultedComparisonKind::Relational) &&
7872           !Best->RewriteKind) {
7873         if (Diagnose == ExplainDeleted) {
7874           if (Best->Function) {
7875             S.Diag(Best->Function->getLocation(),
7876                    diag::note_defaulted_comparison_not_rewritten_callee)
7877                 << FD;
7878           } else {
7879             assert(Best->Conversions.size() == 2 &&
7880                    Best->Conversions[0].isUserDefined() &&
7881                    "non-user-defined conversion from class to built-in "
7882                    "comparison");
7883             S.Diag(Best->Conversions[0]
7884                        .UserDefined.FoundConversionFunction.getDecl()
7885                        ->getLocation(),
7886                    diag::note_defaulted_comparison_not_rewritten_conversion)
7887                 << FD;
7888           }
7889         }
7890         return Result::deleted();
7891       }
7892 
7893       // Throughout C++2a [class.compare]: if overload resolution does not
7894       // result in a usable function, the candidate function is defined as
7895       // deleted. This requires that we selected an accessible function.
7896       //
7897       // Note that this only considers the access of the function when named
7898       // within the type of the subobject, and not the access path for any
7899       // derived-to-base conversion.
7900       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7901       if (ArgClass && Best->FoundDecl.getDecl() &&
7902           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7903         QualType ObjectType = Subobj.Kind == Subobject::Member
7904                                   ? Args[0]->getType()
7905                                   : S.Context.getRecordType(RD);
7906         if (!S.isMemberAccessibleForDeletion(
7907                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7908                 Diagnose == ExplainDeleted
7909                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7910                           << FD << Subobj.Kind << Subobj.Decl
7911                     : S.PDiag()))
7912           return Result::deleted();
7913       }
7914 
7915       bool NeedsDeducing =
7916           OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7917 
7918       if (FunctionDecl *BestFD = Best->Function) {
7919         // C++2a [class.compare.default]p3 [P2002R0]:
7920         //   A defaulted comparison function is constexpr-compatible if
7921         //   [...] no overlod resolution performed [...] results in a
7922         //   non-constexpr function.
7923         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7924         // If it's not constexpr, explain why not.
7925         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7926           if (Subobj.Kind != Subobject::CompleteObject)
7927             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7928               << Subobj.Kind << Subobj.Decl;
7929           S.Diag(BestFD->getLocation(),
7930                  diag::note_defaulted_comparison_not_constexpr_here);
7931           // Bail out after explaining; we don't want any more notes.
7932           return Result::deleted();
7933         }
7934         R.Constexpr &= BestFD->isConstexpr();
7935 
7936         if (NeedsDeducing) {
7937           // If any callee has an undeduced return type, deduce it now.
7938           // FIXME: It's not clear how a failure here should be handled. For
7939           // now, we produce an eager diagnostic, because that is forward
7940           // compatible with most (all?) other reasonable options.
7941           if (BestFD->getReturnType()->isUndeducedType() &&
7942               S.DeduceReturnType(BestFD, FD->getLocation(),
7943                                  /*Diagnose=*/false)) {
7944             // Don't produce a duplicate error when asked to explain why the
7945             // comparison is deleted: we diagnosed that when initially checking
7946             // the defaulted operator.
7947             if (Diagnose == NoDiagnostics) {
7948               S.Diag(
7949                   FD->getLocation(),
7950                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7951                   << Subobj.Kind << Subobj.Decl;
7952               S.Diag(
7953                   Subobj.Loc,
7954                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7955                   << Subobj.Kind << Subobj.Decl;
7956               S.Diag(BestFD->getLocation(),
7957                      diag::note_defaulted_comparison_cannot_deduce_callee)
7958                   << Subobj.Kind << Subobj.Decl;
7959             }
7960             return Result::deleted();
7961           }
7962           auto *Info = S.Context.CompCategories.lookupInfoForType(
7963               BestFD->getCallResultType());
7964           if (!Info) {
7965             if (Diagnose == ExplainDeleted) {
7966               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7967                   << Subobj.Kind << Subobj.Decl
7968                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7969               S.Diag(BestFD->getLocation(),
7970                      diag::note_defaulted_comparison_cannot_deduce_callee)
7971                   << Subobj.Kind << Subobj.Decl;
7972             }
7973             return Result::deleted();
7974           }
7975           R.Category = Info->Kind;
7976         }
7977       } else {
7978         QualType T = Best->BuiltinParamTypes[0];
7979         assert(T == Best->BuiltinParamTypes[1] &&
7980                "builtin comparison for different types?");
7981         assert(Best->BuiltinParamTypes[2].isNull() &&
7982                "invalid builtin comparison");
7983 
7984         if (NeedsDeducing) {
7985           Optional<ComparisonCategoryType> Cat =
7986               getComparisonCategoryForBuiltinCmp(T);
7987           assert(Cat && "no category for builtin comparison?");
7988           R.Category = *Cat;
7989         }
7990       }
7991 
7992       // Note that we might be rewriting to a different operator. That call is
7993       // not considered until we come to actually build the comparison function.
7994       break;
7995     }
7996 
7997     case OR_Ambiguous:
7998       if (Diagnose == ExplainDeleted) {
7999         unsigned Kind = 0;
8000         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8001           Kind = OO == OO_EqualEqual ? 1 : 2;
8002         CandidateSet.NoteCandidates(
8003             PartialDiagnosticAt(
8004                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
8005                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
8006             S, OCD_AmbiguousCandidates, Args);
8007       }
8008       R = Result::deleted();
8009       break;
8010 
8011     case OR_Deleted:
8012       if (Diagnose == ExplainDeleted) {
8013         if ((DCK == DefaultedComparisonKind::NotEqual ||
8014              DCK == DefaultedComparisonKind::Relational) &&
8015             !Best->RewriteKind) {
8016           S.Diag(Best->Function->getLocation(),
8017                  diag::note_defaulted_comparison_not_rewritten_callee)
8018               << FD;
8019         } else {
8020           S.Diag(Subobj.Loc,
8021                  diag::note_defaulted_comparison_calls_deleted)
8022               << FD << Subobj.Kind << Subobj.Decl;
8023           S.NoteDeletedFunction(Best->Function);
8024         }
8025       }
8026       R = Result::deleted();
8027       break;
8028 
8029     case OR_No_Viable_Function:
8030       // If there's no usable candidate, we're done unless we can rewrite a
8031       // '<=>' in terms of '==' and '<'.
8032       if (OO == OO_Spaceship &&
8033           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
8034         // For any kind of comparison category return type, we need a usable
8035         // '==' and a usable '<'.
8036         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
8037                                        &CandidateSet)))
8038           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
8039         break;
8040       }
8041 
8042       if (Diagnose == ExplainDeleted) {
8043         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
8044             << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
8045 
8046         // For a three-way comparison, list both the candidates for the
8047         // original operator and the candidates for the synthesized operator.
8048         if (SpaceshipCandidates) {
8049           SpaceshipCandidates->NoteCandidates(
8050               S, Args,
8051               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8052                                                       Args, FD->getLocation()));
8053           S.Diag(Subobj.Loc,
8054                  diag::note_defaulted_comparison_no_viable_function_synthesized)
8055               << (OO == OO_EqualEqual ? 0 : 1);
8056         }
8057 
8058         CandidateSet.NoteCandidates(
8059             S, Args,
8060             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8061                                             FD->getLocation()));
8062       }
8063       R = Result::deleted();
8064       break;
8065     }
8066 
8067     return R;
8068   }
8069 };
8070 
8071 /// A list of statements.
8072 struct StmtListResult {
8073   bool IsInvalid = false;
8074   llvm::SmallVector<Stmt*, 16> Stmts;
8075 
8076   bool add(const StmtResult &S) {
8077     IsInvalid |= S.isInvalid();
8078     if (IsInvalid)
8079       return true;
8080     Stmts.push_back(S.get());
8081     return false;
8082   }
8083 };
8084 
8085 /// A visitor over the notional body of a defaulted comparison that synthesizes
8086 /// the actual body.
8087 class DefaultedComparisonSynthesizer
8088     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8089                                         StmtListResult, StmtResult,
8090                                         std::pair<ExprResult, ExprResult>> {
8091   SourceLocation Loc;
8092   unsigned ArrayDepth = 0;
8093 
8094 public:
8095   using Base = DefaultedComparisonVisitor;
8096   using ExprPair = std::pair<ExprResult, ExprResult>;
8097 
8098   friend Base;
8099 
8100   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8101                                  DefaultedComparisonKind DCK,
8102                                  SourceLocation BodyLoc)
8103       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8104 
8105   /// Build a suitable function body for this defaulted comparison operator.
8106   StmtResult build() {
8107     Sema::CompoundScopeRAII CompoundScope(S);
8108 
8109     StmtListResult Stmts = visit();
8110     if (Stmts.IsInvalid)
8111       return StmtError();
8112 
8113     ExprResult RetVal;
8114     switch (DCK) {
8115     case DefaultedComparisonKind::None:
8116       llvm_unreachable("not a defaulted comparison");
8117 
8118     case DefaultedComparisonKind::Equal: {
8119       // C++2a [class.eq]p3:
8120       //   [...] compar[e] the corresponding elements [...] until the first
8121       //   index i where xi == yi yields [...] false. If no such index exists,
8122       //   V is true. Otherwise, V is false.
8123       //
8124       // Join the comparisons with '&&'s and return the result. Use a right
8125       // fold (traversing the conditions right-to-left), because that
8126       // short-circuits more naturally.
8127       auto OldStmts = std::move(Stmts.Stmts);
8128       Stmts.Stmts.clear();
8129       ExprResult CmpSoFar;
8130       // Finish a particular comparison chain.
8131       auto FinishCmp = [&] {
8132         if (Expr *Prior = CmpSoFar.get()) {
8133           // Convert the last expression to 'return ...;'
8134           if (RetVal.isUnset() && Stmts.Stmts.empty())
8135             RetVal = CmpSoFar;
8136           // Convert any prior comparison to 'if (!(...)) return false;'
8137           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8138             return true;
8139           CmpSoFar = ExprResult();
8140         }
8141         return false;
8142       };
8143       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8144         Expr *E = dyn_cast<Expr>(EAsStmt);
8145         if (!E) {
8146           // Found an array comparison.
8147           if (FinishCmp() || Stmts.add(EAsStmt))
8148             return StmtError();
8149           continue;
8150         }
8151 
8152         if (CmpSoFar.isUnset()) {
8153           CmpSoFar = E;
8154           continue;
8155         }
8156         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8157         if (CmpSoFar.isInvalid())
8158           return StmtError();
8159       }
8160       if (FinishCmp())
8161         return StmtError();
8162       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8163       //   If no such index exists, V is true.
8164       if (RetVal.isUnset())
8165         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8166       break;
8167     }
8168 
8169     case DefaultedComparisonKind::ThreeWay: {
8170       // Per C++2a [class.spaceship]p3, as a fallback add:
8171       // return static_cast<R>(std::strong_ordering::equal);
8172       QualType StrongOrdering = S.CheckComparisonCategoryType(
8173           ComparisonCategoryType::StrongOrdering, Loc,
8174           Sema::ComparisonCategoryUsage::DefaultedOperator);
8175       if (StrongOrdering.isNull())
8176         return StmtError();
8177       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8178                              .getValueInfo(ComparisonCategoryResult::Equal)
8179                              ->VD;
8180       RetVal = getDecl(EqualVD);
8181       if (RetVal.isInvalid())
8182         return StmtError();
8183       RetVal = buildStaticCastToR(RetVal.get());
8184       break;
8185     }
8186 
8187     case DefaultedComparisonKind::NotEqual:
8188     case DefaultedComparisonKind::Relational:
8189       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8190       break;
8191     }
8192 
8193     // Build the final return statement.
8194     if (RetVal.isInvalid())
8195       return StmtError();
8196     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8197     if (ReturnStmt.isInvalid())
8198       return StmtError();
8199     Stmts.Stmts.push_back(ReturnStmt.get());
8200 
8201     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8202   }
8203 
8204 private:
8205   ExprResult getDecl(ValueDecl *VD) {
8206     return S.BuildDeclarationNameExpr(
8207         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8208   }
8209 
8210   ExprResult getParam(unsigned I) {
8211     ParmVarDecl *PD = FD->getParamDecl(I);
8212     return getDecl(PD);
8213   }
8214 
8215   ExprPair getCompleteObject() {
8216     unsigned Param = 0;
8217     ExprResult LHS;
8218     if (isa<CXXMethodDecl>(FD)) {
8219       // LHS is '*this'.
8220       LHS = S.ActOnCXXThis(Loc);
8221       if (!LHS.isInvalid())
8222         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8223     } else {
8224       LHS = getParam(Param++);
8225     }
8226     ExprResult RHS = getParam(Param++);
8227     assert(Param == FD->getNumParams());
8228     return {LHS, RHS};
8229   }
8230 
8231   ExprPair getBase(CXXBaseSpecifier *Base) {
8232     ExprPair Obj = getCompleteObject();
8233     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8234       return {ExprError(), ExprError()};
8235     CXXCastPath Path = {Base};
8236     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8237                                 CK_DerivedToBase, VK_LValue, &Path),
8238             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8239                                 CK_DerivedToBase, VK_LValue, &Path)};
8240   }
8241 
8242   ExprPair getField(FieldDecl *Field) {
8243     ExprPair Obj = getCompleteObject();
8244     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8245       return {ExprError(), ExprError()};
8246 
8247     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8248     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8249     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8250                                       CXXScopeSpec(), Field, Found, NameInfo),
8251             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8252                                       CXXScopeSpec(), Field, Found, NameInfo)};
8253   }
8254 
8255   // FIXME: When expanding a subobject, register a note in the code synthesis
8256   // stack to say which subobject we're comparing.
8257 
8258   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8259     if (Cond.isInvalid())
8260       return StmtError();
8261 
8262     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8263     if (NotCond.isInvalid())
8264       return StmtError();
8265 
8266     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8267     assert(!False.isInvalid() && "should never fail");
8268     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8269     if (ReturnFalse.isInvalid())
8270       return StmtError();
8271 
8272     return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8273                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8274                                           Sema::ConditionKind::Boolean),
8275                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8276   }
8277 
8278   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8279                                  ExprPair Subobj) {
8280     QualType SizeType = S.Context.getSizeType();
8281     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8282 
8283     // Build 'size_t i$n = 0'.
8284     IdentifierInfo *IterationVarName = nullptr;
8285     {
8286       SmallString<8> Str;
8287       llvm::raw_svector_ostream OS(Str);
8288       OS << "i" << ArrayDepth;
8289       IterationVarName = &S.Context.Idents.get(OS.str());
8290     }
8291     VarDecl *IterationVar = VarDecl::Create(
8292         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8293         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8294     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8295     IterationVar->setInit(
8296         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8297     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8298 
8299     auto IterRef = [&] {
8300       ExprResult Ref = S.BuildDeclarationNameExpr(
8301           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8302           IterationVar);
8303       assert(!Ref.isInvalid() && "can't reference our own variable?");
8304       return Ref.get();
8305     };
8306 
8307     // Build 'i$n != Size'.
8308     ExprResult Cond = S.CreateBuiltinBinOp(
8309         Loc, BO_NE, IterRef(),
8310         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8311     assert(!Cond.isInvalid() && "should never fail");
8312 
8313     // Build '++i$n'.
8314     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8315     assert(!Inc.isInvalid() && "should never fail");
8316 
8317     // Build 'a[i$n]' and 'b[i$n]'.
8318     auto Index = [&](ExprResult E) {
8319       if (E.isInvalid())
8320         return ExprError();
8321       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8322     };
8323     Subobj.first = Index(Subobj.first);
8324     Subobj.second = Index(Subobj.second);
8325 
8326     // Compare the array elements.
8327     ++ArrayDepth;
8328     StmtResult Substmt = visitSubobject(Type, Subobj);
8329     --ArrayDepth;
8330 
8331     if (Substmt.isInvalid())
8332       return StmtError();
8333 
8334     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8335     // For outer levels or for an 'operator<=>' we already have a suitable
8336     // statement that returns as necessary.
8337     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8338       assert(DCK == DefaultedComparisonKind::Equal &&
8339              "should have non-expression statement");
8340       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8341       if (Substmt.isInvalid())
8342         return StmtError();
8343     }
8344 
8345     // Build 'for (...) ...'
8346     return S.ActOnForStmt(Loc, Loc, Init,
8347                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8348                                            Sema::ConditionKind::Boolean),
8349                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8350                           Substmt.get());
8351   }
8352 
8353   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8354     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8355       return StmtError();
8356 
8357     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8358     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8359     ExprResult Op;
8360     if (Type->isOverloadableType())
8361       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8362                                    Obj.second.get(), /*PerformADL=*/true,
8363                                    /*AllowRewrittenCandidates=*/true, FD);
8364     else
8365       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8366     if (Op.isInvalid())
8367       return StmtError();
8368 
8369     switch (DCK) {
8370     case DefaultedComparisonKind::None:
8371       llvm_unreachable("not a defaulted comparison");
8372 
8373     case DefaultedComparisonKind::Equal:
8374       // Per C++2a [class.eq]p2, each comparison is individually contextually
8375       // converted to bool.
8376       Op = S.PerformContextuallyConvertToBool(Op.get());
8377       if (Op.isInvalid())
8378         return StmtError();
8379       return Op.get();
8380 
8381     case DefaultedComparisonKind::ThreeWay: {
8382       // Per C++2a [class.spaceship]p3, form:
8383       //   if (R cmp = static_cast<R>(op); cmp != 0)
8384       //     return cmp;
8385       QualType R = FD->getReturnType();
8386       Op = buildStaticCastToR(Op.get());
8387       if (Op.isInvalid())
8388         return StmtError();
8389 
8390       // R cmp = ...;
8391       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8392       VarDecl *VD =
8393           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8394                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8395       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8396       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8397 
8398       // cmp != 0
8399       ExprResult VDRef = getDecl(VD);
8400       if (VDRef.isInvalid())
8401         return StmtError();
8402       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8403       Expr *Zero =
8404           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8405       ExprResult Comp;
8406       if (VDRef.get()->getType()->isOverloadableType())
8407         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8408                                        true, FD);
8409       else
8410         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8411       if (Comp.isInvalid())
8412         return StmtError();
8413       Sema::ConditionResult Cond = S.ActOnCondition(
8414           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8415       if (Cond.isInvalid())
8416         return StmtError();
8417 
8418       // return cmp;
8419       VDRef = getDecl(VD);
8420       if (VDRef.isInvalid())
8421         return StmtError();
8422       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8423       if (ReturnStmt.isInvalid())
8424         return StmtError();
8425 
8426       // if (...)
8427       return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8428                            Loc, ReturnStmt.get(),
8429                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8430     }
8431 
8432     case DefaultedComparisonKind::NotEqual:
8433     case DefaultedComparisonKind::Relational:
8434       // C++2a [class.compare.secondary]p2:
8435       //   Otherwise, the operator function yields x @ y.
8436       return Op.get();
8437     }
8438     llvm_unreachable("");
8439   }
8440 
8441   /// Build "static_cast<R>(E)".
8442   ExprResult buildStaticCastToR(Expr *E) {
8443     QualType R = FD->getReturnType();
8444     assert(!R->isUndeducedType() && "type should have been deduced already");
8445 
8446     // Don't bother forming a no-op cast in the common case.
8447     if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8448       return E;
8449     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8450                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8451                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8452   }
8453 };
8454 }
8455 
8456 /// Perform the unqualified lookups that might be needed to form a defaulted
8457 /// comparison function for the given operator.
8458 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8459                                                   UnresolvedSetImpl &Operators,
8460                                                   OverloadedOperatorKind Op) {
8461   auto Lookup = [&](OverloadedOperatorKind OO) {
8462     Self.LookupOverloadedOperatorName(OO, S, Operators);
8463   };
8464 
8465   // Every defaulted operator looks up itself.
8466   Lookup(Op);
8467   // ... and the rewritten form of itself, if any.
8468   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8469     Lookup(ExtraOp);
8470 
8471   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8472   // synthesize a three-way comparison from '<' and '=='. In a dependent
8473   // context, we also need to look up '==' in case we implicitly declare a
8474   // defaulted 'operator=='.
8475   if (Op == OO_Spaceship) {
8476     Lookup(OO_ExclaimEqual);
8477     Lookup(OO_Less);
8478     Lookup(OO_EqualEqual);
8479   }
8480 }
8481 
8482 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8483                                               DefaultedComparisonKind DCK) {
8484   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8485 
8486   // Perform any unqualified lookups we're going to need to default this
8487   // function.
8488   if (S) {
8489     UnresolvedSet<32> Operators;
8490     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8491                                           FD->getOverloadedOperator());
8492     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8493         Context, Operators.pairs()));
8494   }
8495 
8496   // C++2a [class.compare.default]p1:
8497   //   A defaulted comparison operator function for some class C shall be a
8498   //   non-template function declared in the member-specification of C that is
8499   //    -- a non-static const member of C having one parameter of type
8500   //       const C&, or
8501   //    -- a friend of C having two parameters of type const C& or two
8502   //       parameters of type C.
8503 
8504   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8505   bool IsMethod = isa<CXXMethodDecl>(FD);
8506   if (IsMethod) {
8507     auto *MD = cast<CXXMethodDecl>(FD);
8508     assert(!MD->isStatic() && "comparison function cannot be a static member");
8509 
8510     // If we're out-of-class, this is the class we're comparing.
8511     if (!RD)
8512       RD = MD->getParent();
8513 
8514     if (!MD->isConst()) {
8515       SourceLocation InsertLoc;
8516       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8517         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8518       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8519       // corresponding defaulted 'operator<=>' already.
8520       if (!MD->isImplicit()) {
8521         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8522             << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8523       }
8524 
8525       // Add the 'const' to the type to recover.
8526       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8527       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8528       EPI.TypeQuals.addConst();
8529       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8530                                           FPT->getParamTypes(), EPI));
8531     }
8532   }
8533 
8534   if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8535     // Let's not worry about using a variadic template pack here -- who would do
8536     // such a thing?
8537     Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8538         << int(IsMethod) << int(DCK);
8539     return true;
8540   }
8541 
8542   const ParmVarDecl *KnownParm = nullptr;
8543   for (const ParmVarDecl *Param : FD->parameters()) {
8544     QualType ParmTy = Param->getType();
8545     if (ParmTy->isDependentType())
8546       continue;
8547     if (!KnownParm) {
8548       auto CTy = ParmTy;
8549       // Is it `T const &`?
8550       bool Ok = !IsMethod;
8551       QualType ExpectedTy;
8552       if (RD)
8553         ExpectedTy = Context.getRecordType(RD);
8554       if (auto *Ref = CTy->getAs<ReferenceType>()) {
8555         CTy = Ref->getPointeeType();
8556         if (RD)
8557           ExpectedTy.addConst();
8558         Ok = true;
8559       }
8560 
8561       // Is T a class?
8562       if (!Ok) {
8563       } else if (RD) {
8564         if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8565           Ok = false;
8566       } else if (auto *CRD = CTy->getAsRecordDecl()) {
8567         RD = cast<CXXRecordDecl>(CRD);
8568       } else {
8569         Ok = false;
8570       }
8571 
8572       if (Ok) {
8573         KnownParm = Param;
8574       } else {
8575         // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8576         // corresponding defaulted 'operator<=>' already.
8577         if (!FD->isImplicit()) {
8578           if (RD) {
8579             QualType PlainTy = Context.getRecordType(RD);
8580             QualType RefTy =
8581                 Context.getLValueReferenceType(PlainTy.withConst());
8582             Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8583                 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8584                 << Param->getSourceRange();
8585           } else {
8586             assert(!IsMethod && "should know expected type for method");
8587             Diag(FD->getLocation(),
8588                  diag::err_defaulted_comparison_param_unknown)
8589                 << int(DCK) << ParmTy << Param->getSourceRange();
8590           }
8591         }
8592         return true;
8593       }
8594     } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8595       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8596           << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8597           << ParmTy << Param->getSourceRange();
8598       return true;
8599     }
8600   }
8601 
8602   assert(RD && "must have determined class");
8603   if (IsMethod) {
8604   } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8605     // In-class, must be a friend decl.
8606     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8607   } else {
8608     // Out of class, require the defaulted comparison to be a friend (of a
8609     // complete type).
8610     if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8611                             diag::err_defaulted_comparison_not_friend, int(DCK),
8612                             int(1)))
8613       return true;
8614 
8615     if (llvm::none_of(RD->friends(), [&](const FriendDecl *F) {
8616           return FD->getCanonicalDecl() ==
8617                  F->getFriendDecl()->getCanonicalDecl();
8618         })) {
8619       Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8620           << int(DCK) << int(0) << RD;
8621       Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8622       return true;
8623     }
8624   }
8625 
8626   // C++2a [class.eq]p1, [class.rel]p1:
8627   //   A [defaulted comparison other than <=>] shall have a declared return
8628   //   type bool.
8629   if (DCK != DefaultedComparisonKind::ThreeWay &&
8630       !FD->getDeclaredReturnType()->isDependentType() &&
8631       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8632     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8633         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8634         << FD->getReturnTypeSourceRange();
8635     return true;
8636   }
8637   // C++2a [class.spaceship]p2 [P2002R0]:
8638   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8639   //   R shall not contain a placeholder type.
8640   if (DCK == DefaultedComparisonKind::ThreeWay &&
8641       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8642       !Context.hasSameType(FD->getDeclaredReturnType(),
8643                            Context.getAutoDeductType())) {
8644     Diag(FD->getLocation(),
8645          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8646         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8647         << FD->getReturnTypeSourceRange();
8648     return true;
8649   }
8650 
8651   // For a defaulted function in a dependent class, defer all remaining checks
8652   // until instantiation.
8653   if (RD->isDependentType())
8654     return false;
8655 
8656   // Determine whether the function should be defined as deleted.
8657   DefaultedComparisonInfo Info =
8658       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8659 
8660   bool First = FD == FD->getCanonicalDecl();
8661 
8662   // If we want to delete the function, then do so; there's nothing else to
8663   // check in that case.
8664   if (Info.Deleted) {
8665     if (!First) {
8666       // C++11 [dcl.fct.def.default]p4:
8667       //   [For a] user-provided explicitly-defaulted function [...] if such a
8668       //   function is implicitly defined as deleted, the program is ill-formed.
8669       //
8670       // This is really just a consequence of the general rule that you can
8671       // only delete a function on its first declaration.
8672       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8673           << FD->isImplicit() << (int)DCK;
8674       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8675                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8676           .visit();
8677       return true;
8678     }
8679 
8680     SetDeclDeleted(FD, FD->getLocation());
8681     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8682       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8683           << (int)DCK;
8684       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8685                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8686           .visit();
8687     }
8688     return false;
8689   }
8690 
8691   // C++2a [class.spaceship]p2:
8692   //   The return type is deduced as the common comparison type of R0, R1, ...
8693   if (DCK == DefaultedComparisonKind::ThreeWay &&
8694       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8695     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8696     if (RetLoc.isInvalid())
8697       RetLoc = FD->getBeginLoc();
8698     // FIXME: Should we really care whether we have the complete type and the
8699     // 'enumerator' constants here? A forward declaration seems sufficient.
8700     QualType Cat = CheckComparisonCategoryType(
8701         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8702     if (Cat.isNull())
8703       return true;
8704     Context.adjustDeducedFunctionResultType(
8705         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8706   }
8707 
8708   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8709   //   An explicitly-defaulted function that is not defined as deleted may be
8710   //   declared constexpr or consteval only if it is constexpr-compatible.
8711   // C++2a [class.compare.default]p3 [P2002R0]:
8712   //   A defaulted comparison function is constexpr-compatible if it satisfies
8713   //   the requirements for a constexpr function [...]
8714   // The only relevant requirements are that the parameter and return types are
8715   // literal types. The remaining conditions are checked by the analyzer.
8716   if (FD->isConstexpr()) {
8717     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8718         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8719         !Info.Constexpr) {
8720       Diag(FD->getBeginLoc(),
8721            diag::err_incorrect_defaulted_comparison_constexpr)
8722           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8723       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8724                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8725           .visit();
8726     }
8727   }
8728 
8729   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8730   //   If a constexpr-compatible function is explicitly defaulted on its first
8731   //   declaration, it is implicitly considered to be constexpr.
8732   // FIXME: Only applying this to the first declaration seems problematic, as
8733   // simple reorderings can affect the meaning of the program.
8734   if (First && !FD->isConstexpr() && Info.Constexpr)
8735     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8736 
8737   // C++2a [except.spec]p3:
8738   //   If a declaration of a function does not have a noexcept-specifier
8739   //   [and] is defaulted on its first declaration, [...] the exception
8740   //   specification is as specified below
8741   if (FD->getExceptionSpecType() == EST_None) {
8742     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8743     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8744     EPI.ExceptionSpec.Type = EST_Unevaluated;
8745     EPI.ExceptionSpec.SourceDecl = FD;
8746     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8747                                         FPT->getParamTypes(), EPI));
8748   }
8749 
8750   return false;
8751 }
8752 
8753 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8754                                              FunctionDecl *Spaceship) {
8755   Sema::CodeSynthesisContext Ctx;
8756   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8757   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8758   Ctx.Entity = Spaceship;
8759   pushCodeSynthesisContext(Ctx);
8760 
8761   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8762     EqualEqual->setImplicit();
8763 
8764   popCodeSynthesisContext();
8765 }
8766 
8767 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8768                                      DefaultedComparisonKind DCK) {
8769   assert(FD->isDefaulted() && !FD->isDeleted() &&
8770          !FD->doesThisDeclarationHaveABody());
8771   if (FD->willHaveBody() || FD->isInvalidDecl())
8772     return;
8773 
8774   SynthesizedFunctionScope Scope(*this, FD);
8775 
8776   // Add a context note for diagnostics produced after this point.
8777   Scope.addContextNote(UseLoc);
8778 
8779   {
8780     // Build and set up the function body.
8781     // The first parameter has type maybe-ref-to maybe-const T, use that to get
8782     // the type of the class being compared.
8783     auto PT = FD->getParamDecl(0)->getType();
8784     CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
8785     SourceLocation BodyLoc =
8786         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8787     StmtResult Body =
8788         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8789     if (Body.isInvalid()) {
8790       FD->setInvalidDecl();
8791       return;
8792     }
8793     FD->setBody(Body.get());
8794     FD->markUsed(Context);
8795   }
8796 
8797   // The exception specification is needed because we are defining the
8798   // function. Note that this will reuse the body we just built.
8799   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8800 
8801   if (ASTMutationListener *L = getASTMutationListener())
8802     L->CompletedImplicitDefinition(FD);
8803 }
8804 
8805 static Sema::ImplicitExceptionSpecification
8806 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8807                                         FunctionDecl *FD,
8808                                         Sema::DefaultedComparisonKind DCK) {
8809   ComputingExceptionSpec CES(S, FD, Loc);
8810   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8811 
8812   if (FD->isInvalidDecl())
8813     return ExceptSpec;
8814 
8815   // The common case is that we just defined the comparison function. In that
8816   // case, just look at whether the body can throw.
8817   if (FD->hasBody()) {
8818     ExceptSpec.CalledStmt(FD->getBody());
8819   } else {
8820     // Otherwise, build a body so we can check it. This should ideally only
8821     // happen when we're not actually marking the function referenced. (This is
8822     // only really important for efficiency: we don't want to build and throw
8823     // away bodies for comparison functions more than we strictly need to.)
8824 
8825     // Pretend to synthesize the function body in an unevaluated context.
8826     // Note that we can't actually just go ahead and define the function here:
8827     // we are not permitted to mark its callees as referenced.
8828     Sema::SynthesizedFunctionScope Scope(S, FD);
8829     EnterExpressionEvaluationContext Context(
8830         S, Sema::ExpressionEvaluationContext::Unevaluated);
8831 
8832     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8833     SourceLocation BodyLoc =
8834         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8835     StmtResult Body =
8836         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8837     if (!Body.isInvalid())
8838       ExceptSpec.CalledStmt(Body.get());
8839 
8840     // FIXME: Can we hold onto this body and just transform it to potentially
8841     // evaluated when we're asked to define the function rather than rebuilding
8842     // it? Either that, or we should only build the bits of the body that we
8843     // need (the expressions, not the statements).
8844   }
8845 
8846   return ExceptSpec;
8847 }
8848 
8849 void Sema::CheckDelayedMemberExceptionSpecs() {
8850   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8851   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8852 
8853   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8854   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8855 
8856   // Perform any deferred checking of exception specifications for virtual
8857   // destructors.
8858   for (auto &Check : Overriding)
8859     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8860 
8861   // Perform any deferred checking of exception specifications for befriended
8862   // special members.
8863   for (auto &Check : Equivalent)
8864     CheckEquivalentExceptionSpec(Check.second, Check.first);
8865 }
8866 
8867 namespace {
8868 /// CRTP base class for visiting operations performed by a special member
8869 /// function (or inherited constructor).
8870 template<typename Derived>
8871 struct SpecialMemberVisitor {
8872   Sema &S;
8873   CXXMethodDecl *MD;
8874   Sema::CXXSpecialMember CSM;
8875   Sema::InheritedConstructorInfo *ICI;
8876 
8877   // Properties of the special member, computed for convenience.
8878   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8879 
8880   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8881                        Sema::InheritedConstructorInfo *ICI)
8882       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8883     switch (CSM) {
8884     case Sema::CXXDefaultConstructor:
8885     case Sema::CXXCopyConstructor:
8886     case Sema::CXXMoveConstructor:
8887       IsConstructor = true;
8888       break;
8889     case Sema::CXXCopyAssignment:
8890     case Sema::CXXMoveAssignment:
8891       IsAssignment = true;
8892       break;
8893     case Sema::CXXDestructor:
8894       break;
8895     case Sema::CXXInvalid:
8896       llvm_unreachable("invalid special member kind");
8897     }
8898 
8899     if (MD->getNumParams()) {
8900       if (const ReferenceType *RT =
8901               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8902         ConstArg = RT->getPointeeType().isConstQualified();
8903     }
8904   }
8905 
8906   Derived &getDerived() { return static_cast<Derived&>(*this); }
8907 
8908   /// Is this a "move" special member?
8909   bool isMove() const {
8910     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8911   }
8912 
8913   /// Look up the corresponding special member in the given class.
8914   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8915                                              unsigned Quals, bool IsMutable) {
8916     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8917                                        ConstArg && !IsMutable);
8918   }
8919 
8920   /// Look up the constructor for the specified base class to see if it's
8921   /// overridden due to this being an inherited constructor.
8922   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8923     if (!ICI)
8924       return {};
8925     assert(CSM == Sema::CXXDefaultConstructor);
8926     auto *BaseCtor =
8927       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8928     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8929       return MD;
8930     return {};
8931   }
8932 
8933   /// A base or member subobject.
8934   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8935 
8936   /// Get the location to use for a subobject in diagnostics.
8937   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8938     // FIXME: For an indirect virtual base, the direct base leading to
8939     // the indirect virtual base would be a more useful choice.
8940     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8941       return B->getBaseTypeLoc();
8942     else
8943       return Subobj.get<FieldDecl*>()->getLocation();
8944   }
8945 
8946   enum BasesToVisit {
8947     /// Visit all non-virtual (direct) bases.
8948     VisitNonVirtualBases,
8949     /// Visit all direct bases, virtual or not.
8950     VisitDirectBases,
8951     /// Visit all non-virtual bases, and all virtual bases if the class
8952     /// is not abstract.
8953     VisitPotentiallyConstructedBases,
8954     /// Visit all direct or virtual bases.
8955     VisitAllBases
8956   };
8957 
8958   // Visit the bases and members of the class.
8959   bool visit(BasesToVisit Bases) {
8960     CXXRecordDecl *RD = MD->getParent();
8961 
8962     if (Bases == VisitPotentiallyConstructedBases)
8963       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8964 
8965     for (auto &B : RD->bases())
8966       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8967           getDerived().visitBase(&B))
8968         return true;
8969 
8970     if (Bases == VisitAllBases)
8971       for (auto &B : RD->vbases())
8972         if (getDerived().visitBase(&B))
8973           return true;
8974 
8975     for (auto *F : RD->fields())
8976       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8977           getDerived().visitField(F))
8978         return true;
8979 
8980     return false;
8981   }
8982 };
8983 }
8984 
8985 namespace {
8986 struct SpecialMemberDeletionInfo
8987     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8988   bool Diagnose;
8989 
8990   SourceLocation Loc;
8991 
8992   bool AllFieldsAreConst;
8993 
8994   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8995                             Sema::CXXSpecialMember CSM,
8996                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8997       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8998         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8999 
9000   bool inUnion() const { return MD->getParent()->isUnion(); }
9001 
9002   Sema::CXXSpecialMember getEffectiveCSM() {
9003     return ICI ? Sema::CXXInvalid : CSM;
9004   }
9005 
9006   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9007 
9008   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9009   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
9010 
9011   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9012   bool shouldDeleteForField(FieldDecl *FD);
9013   bool shouldDeleteForAllConstMembers();
9014 
9015   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9016                                      unsigned Quals);
9017   bool shouldDeleteForSubobjectCall(Subobject Subobj,
9018                                     Sema::SpecialMemberOverloadResult SMOR,
9019                                     bool IsDtorCallInCtor);
9020 
9021   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9022 };
9023 }
9024 
9025 /// Is the given special member inaccessible when used on the given
9026 /// sub-object.
9027 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9028                                              CXXMethodDecl *target) {
9029   /// If we're operating on a base class, the object type is the
9030   /// type of this special member.
9031   QualType objectTy;
9032   AccessSpecifier access = target->getAccess();
9033   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9034     objectTy = S.Context.getTypeDeclType(MD->getParent());
9035     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
9036 
9037   // If we're operating on a field, the object type is the type of the field.
9038   } else {
9039     objectTy = S.Context.getTypeDeclType(target->getParent());
9040   }
9041 
9042   return S.isMemberAccessibleForDeletion(
9043       target->getParent(), DeclAccessPair::make(target, access), objectTy);
9044 }
9045 
9046 /// Check whether we should delete a special member due to the implicit
9047 /// definition containing a call to a special member of a subobject.
9048 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9049     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9050     bool IsDtorCallInCtor) {
9051   CXXMethodDecl *Decl = SMOR.getMethod();
9052   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9053 
9054   int DiagKind = -1;
9055 
9056   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9057     DiagKind = !Decl ? 0 : 1;
9058   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9059     DiagKind = 2;
9060   else if (!isAccessible(Subobj, Decl))
9061     DiagKind = 3;
9062   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9063            !Decl->isTrivial()) {
9064     // A member of a union must have a trivial corresponding special member.
9065     // As a weird special case, a destructor call from a union's constructor
9066     // must be accessible and non-deleted, but need not be trivial. Such a
9067     // destructor is never actually called, but is semantically checked as
9068     // if it were.
9069     DiagKind = 4;
9070   }
9071 
9072   if (DiagKind == -1)
9073     return false;
9074 
9075   if (Diagnose) {
9076     if (Field) {
9077       S.Diag(Field->getLocation(),
9078              diag::note_deleted_special_member_class_subobject)
9079         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9080         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9081     } else {
9082       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9083       S.Diag(Base->getBeginLoc(),
9084              diag::note_deleted_special_member_class_subobject)
9085           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9086           << Base->getType() << DiagKind << IsDtorCallInCtor
9087           << /*IsObjCPtr*/false;
9088     }
9089 
9090     if (DiagKind == 1)
9091       S.NoteDeletedFunction(Decl);
9092     // FIXME: Explain inaccessibility if DiagKind == 3.
9093   }
9094 
9095   return true;
9096 }
9097 
9098 /// Check whether we should delete a special member function due to having a
9099 /// direct or virtual base class or non-static data member of class type M.
9100 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9101     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9102   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9103   bool IsMutable = Field && Field->isMutable();
9104 
9105   // C++11 [class.ctor]p5:
9106   // -- any direct or virtual base class, or non-static data member with no
9107   //    brace-or-equal-initializer, has class type M (or array thereof) and
9108   //    either M has no default constructor or overload resolution as applied
9109   //    to M's default constructor results in an ambiguity or in a function
9110   //    that is deleted or inaccessible
9111   // C++11 [class.copy]p11, C++11 [class.copy]p23:
9112   // -- a direct or virtual base class B that cannot be copied/moved because
9113   //    overload resolution, as applied to B's corresponding special member,
9114   //    results in an ambiguity or a function that is deleted or inaccessible
9115   //    from the defaulted special member
9116   // C++11 [class.dtor]p5:
9117   // -- any direct or virtual base class [...] has a type with a destructor
9118   //    that is deleted or inaccessible
9119   if (!(CSM == Sema::CXXDefaultConstructor &&
9120         Field && Field->hasInClassInitializer()) &&
9121       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9122                                    false))
9123     return true;
9124 
9125   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9126   // -- any direct or virtual base class or non-static data member has a
9127   //    type with a destructor that is deleted or inaccessible
9128   if (IsConstructor) {
9129     Sema::SpecialMemberOverloadResult SMOR =
9130         S.LookupSpecialMember(Class, Sema::CXXDestructor,
9131                               false, false, false, false, false);
9132     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9133       return true;
9134   }
9135 
9136   return false;
9137 }
9138 
9139 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9140     FieldDecl *FD, QualType FieldType) {
9141   // The defaulted special functions are defined as deleted if this is a variant
9142   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9143   // type under ARC.
9144   if (!FieldType.hasNonTrivialObjCLifetime())
9145     return false;
9146 
9147   // Don't make the defaulted default constructor defined as deleted if the
9148   // member has an in-class initializer.
9149   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9150     return false;
9151 
9152   if (Diagnose) {
9153     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9154     S.Diag(FD->getLocation(),
9155            diag::note_deleted_special_member_class_subobject)
9156         << getEffectiveCSM() << ParentClass << /*IsField*/true
9157         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9158   }
9159 
9160   return true;
9161 }
9162 
9163 /// Check whether we should delete a special member function due to the class
9164 /// having a particular direct or virtual base class.
9165 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9166   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9167   // If program is correct, BaseClass cannot be null, but if it is, the error
9168   // must be reported elsewhere.
9169   if (!BaseClass)
9170     return false;
9171   // If we have an inheriting constructor, check whether we're calling an
9172   // inherited constructor instead of a default constructor.
9173   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9174   if (auto *BaseCtor = SMOR.getMethod()) {
9175     // Note that we do not check access along this path; other than that,
9176     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9177     // FIXME: Check that the base has a usable destructor! Sink this into
9178     // shouldDeleteForClassSubobject.
9179     if (BaseCtor->isDeleted() && Diagnose) {
9180       S.Diag(Base->getBeginLoc(),
9181              diag::note_deleted_special_member_class_subobject)
9182           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9183           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9184           << /*IsObjCPtr*/false;
9185       S.NoteDeletedFunction(BaseCtor);
9186     }
9187     return BaseCtor->isDeleted();
9188   }
9189   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9190 }
9191 
9192 /// Check whether we should delete a special member function due to the class
9193 /// having a particular non-static data member.
9194 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9195   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9196   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9197 
9198   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9199     return true;
9200 
9201   if (CSM == Sema::CXXDefaultConstructor) {
9202     // For a default constructor, all references must be initialized in-class
9203     // and, if a union, it must have a non-const member.
9204     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9205       if (Diagnose)
9206         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9207           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9208       return true;
9209     }
9210     // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9211     // data member of const-qualified type (or array thereof) with no
9212     // brace-or-equal-initializer is not const-default-constructible.
9213     if (!inUnion() && FieldType.isConstQualified() &&
9214         !FD->hasInClassInitializer() &&
9215         (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9216       if (Diagnose)
9217         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9218           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9219       return true;
9220     }
9221 
9222     if (inUnion() && !FieldType.isConstQualified())
9223       AllFieldsAreConst = false;
9224   } else if (CSM == Sema::CXXCopyConstructor) {
9225     // For a copy constructor, data members must not be of rvalue reference
9226     // type.
9227     if (FieldType->isRValueReferenceType()) {
9228       if (Diagnose)
9229         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9230           << MD->getParent() << FD << FieldType;
9231       return true;
9232     }
9233   } else if (IsAssignment) {
9234     // For an assignment operator, data members must not be of reference type.
9235     if (FieldType->isReferenceType()) {
9236       if (Diagnose)
9237         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9238           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9239       return true;
9240     }
9241     if (!FieldRecord && FieldType.isConstQualified()) {
9242       // C++11 [class.copy]p23:
9243       // -- a non-static data member of const non-class type (or array thereof)
9244       if (Diagnose)
9245         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9246           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9247       return true;
9248     }
9249   }
9250 
9251   if (FieldRecord) {
9252     // Some additional restrictions exist on the variant members.
9253     if (!inUnion() && FieldRecord->isUnion() &&
9254         FieldRecord->isAnonymousStructOrUnion()) {
9255       bool AllVariantFieldsAreConst = true;
9256 
9257       // FIXME: Handle anonymous unions declared within anonymous unions.
9258       for (auto *UI : FieldRecord->fields()) {
9259         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9260 
9261         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9262           return true;
9263 
9264         if (!UnionFieldType.isConstQualified())
9265           AllVariantFieldsAreConst = false;
9266 
9267         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9268         if (UnionFieldRecord &&
9269             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9270                                           UnionFieldType.getCVRQualifiers()))
9271           return true;
9272       }
9273 
9274       // At least one member in each anonymous union must be non-const
9275       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9276           !FieldRecord->field_empty()) {
9277         if (Diagnose)
9278           S.Diag(FieldRecord->getLocation(),
9279                  diag::note_deleted_default_ctor_all_const)
9280             << !!ICI << MD->getParent() << /*anonymous union*/1;
9281         return true;
9282       }
9283 
9284       // Don't check the implicit member of the anonymous union type.
9285       // This is technically non-conformant but supported, and we have a
9286       // diagnostic for this elsewhere.
9287       return false;
9288     }
9289 
9290     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9291                                       FieldType.getCVRQualifiers()))
9292       return true;
9293   }
9294 
9295   return false;
9296 }
9297 
9298 /// C++11 [class.ctor] p5:
9299 ///   A defaulted default constructor for a class X is defined as deleted if
9300 /// X is a union and all of its variant members are of const-qualified type.
9301 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9302   // This is a silly definition, because it gives an empty union a deleted
9303   // default constructor. Don't do that.
9304   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9305     bool AnyFields = false;
9306     for (auto *F : MD->getParent()->fields())
9307       if ((AnyFields = !F->isUnnamedBitfield()))
9308         break;
9309     if (!AnyFields)
9310       return false;
9311     if (Diagnose)
9312       S.Diag(MD->getParent()->getLocation(),
9313              diag::note_deleted_default_ctor_all_const)
9314         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9315     return true;
9316   }
9317   return false;
9318 }
9319 
9320 /// Determine whether a defaulted special member function should be defined as
9321 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9322 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9323 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9324                                      InheritedConstructorInfo *ICI,
9325                                      bool Diagnose) {
9326   if (MD->isInvalidDecl())
9327     return false;
9328   CXXRecordDecl *RD = MD->getParent();
9329   assert(!RD->isDependentType() && "do deletion after instantiation");
9330   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9331     return false;
9332 
9333   // C++11 [expr.lambda.prim]p19:
9334   //   The closure type associated with a lambda-expression has a
9335   //   deleted (8.4.3) default constructor and a deleted copy
9336   //   assignment operator.
9337   // C++2a adds back these operators if the lambda has no lambda-capture.
9338   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9339       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9340     if (Diagnose)
9341       Diag(RD->getLocation(), diag::note_lambda_decl);
9342     return true;
9343   }
9344 
9345   // For an anonymous struct or union, the copy and assignment special members
9346   // will never be used, so skip the check. For an anonymous union declared at
9347   // namespace scope, the constructor and destructor are used.
9348   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9349       RD->isAnonymousStructOrUnion())
9350     return false;
9351 
9352   // C++11 [class.copy]p7, p18:
9353   //   If the class definition declares a move constructor or move assignment
9354   //   operator, an implicitly declared copy constructor or copy assignment
9355   //   operator is defined as deleted.
9356   if (MD->isImplicit() &&
9357       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9358     CXXMethodDecl *UserDeclaredMove = nullptr;
9359 
9360     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9361     // deletion of the corresponding copy operation, not both copy operations.
9362     // MSVC 2015 has adopted the standards conforming behavior.
9363     bool DeletesOnlyMatchingCopy =
9364         getLangOpts().MSVCCompat &&
9365         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9366 
9367     if (RD->hasUserDeclaredMoveConstructor() &&
9368         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9369       if (!Diagnose) return true;
9370 
9371       // Find any user-declared move constructor.
9372       for (auto *I : RD->ctors()) {
9373         if (I->isMoveConstructor()) {
9374           UserDeclaredMove = I;
9375           break;
9376         }
9377       }
9378       assert(UserDeclaredMove);
9379     } else if (RD->hasUserDeclaredMoveAssignment() &&
9380                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9381       if (!Diagnose) return true;
9382 
9383       // Find any user-declared move assignment operator.
9384       for (auto *I : RD->methods()) {
9385         if (I->isMoveAssignmentOperator()) {
9386           UserDeclaredMove = I;
9387           break;
9388         }
9389       }
9390       assert(UserDeclaredMove);
9391     }
9392 
9393     if (UserDeclaredMove) {
9394       Diag(UserDeclaredMove->getLocation(),
9395            diag::note_deleted_copy_user_declared_move)
9396         << (CSM == CXXCopyAssignment) << RD
9397         << UserDeclaredMove->isMoveAssignmentOperator();
9398       return true;
9399     }
9400   }
9401 
9402   // Do access control from the special member function
9403   ContextRAII MethodContext(*this, MD);
9404 
9405   // C++11 [class.dtor]p5:
9406   // -- for a virtual destructor, lookup of the non-array deallocation function
9407   //    results in an ambiguity or in a function that is deleted or inaccessible
9408   if (CSM == CXXDestructor && MD->isVirtual()) {
9409     FunctionDecl *OperatorDelete = nullptr;
9410     DeclarationName Name =
9411       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9412     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9413                                  OperatorDelete, /*Diagnose*/false)) {
9414       if (Diagnose)
9415         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9416       return true;
9417     }
9418   }
9419 
9420   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9421 
9422   // Per DR1611, do not consider virtual bases of constructors of abstract
9423   // classes, since we are not going to construct them.
9424   // Per DR1658, do not consider virtual bases of destructors of abstract
9425   // classes either.
9426   // Per DR2180, for assignment operators we only assign (and thus only
9427   // consider) direct bases.
9428   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9429                                  : SMI.VisitPotentiallyConstructedBases))
9430     return true;
9431 
9432   if (SMI.shouldDeleteForAllConstMembers())
9433     return true;
9434 
9435   if (getLangOpts().CUDA) {
9436     // We should delete the special member in CUDA mode if target inference
9437     // failed.
9438     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9439     // is treated as certain special member, which may not reflect what special
9440     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9441     // expects CSM to match MD, therefore recalculate CSM.
9442     assert(ICI || CSM == getSpecialMember(MD));
9443     auto RealCSM = CSM;
9444     if (ICI)
9445       RealCSM = getSpecialMember(MD);
9446 
9447     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9448                                                    SMI.ConstArg, Diagnose);
9449   }
9450 
9451   return false;
9452 }
9453 
9454 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9455   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9456   assert(DFK && "not a defaultable function");
9457   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9458 
9459   if (DFK.isSpecialMember()) {
9460     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9461                               nullptr, /*Diagnose=*/true);
9462   } else {
9463     DefaultedComparisonAnalyzer(
9464         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9465         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9466         .visit();
9467   }
9468 }
9469 
9470 /// Perform lookup for a special member of the specified kind, and determine
9471 /// whether it is trivial. If the triviality can be determined without the
9472 /// lookup, skip it. This is intended for use when determining whether a
9473 /// special member of a containing object is trivial, and thus does not ever
9474 /// perform overload resolution for default constructors.
9475 ///
9476 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9477 /// member that was most likely to be intended to be trivial, if any.
9478 ///
9479 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9480 /// determine whether the special member is trivial.
9481 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9482                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9483                                      bool ConstRHS,
9484                                      Sema::TrivialABIHandling TAH,
9485                                      CXXMethodDecl **Selected) {
9486   if (Selected)
9487     *Selected = nullptr;
9488 
9489   switch (CSM) {
9490   case Sema::CXXInvalid:
9491     llvm_unreachable("not a special member");
9492 
9493   case Sema::CXXDefaultConstructor:
9494     // C++11 [class.ctor]p5:
9495     //   A default constructor is trivial if:
9496     //    - all the [direct subobjects] have trivial default constructors
9497     //
9498     // Note, no overload resolution is performed in this case.
9499     if (RD->hasTrivialDefaultConstructor())
9500       return true;
9501 
9502     if (Selected) {
9503       // If there's a default constructor which could have been trivial, dig it
9504       // out. Otherwise, if there's any user-provided default constructor, point
9505       // to that as an example of why there's not a trivial one.
9506       CXXConstructorDecl *DefCtor = nullptr;
9507       if (RD->needsImplicitDefaultConstructor())
9508         S.DeclareImplicitDefaultConstructor(RD);
9509       for (auto *CI : RD->ctors()) {
9510         if (!CI->isDefaultConstructor())
9511           continue;
9512         DefCtor = CI;
9513         if (!DefCtor->isUserProvided())
9514           break;
9515       }
9516 
9517       *Selected = DefCtor;
9518     }
9519 
9520     return false;
9521 
9522   case Sema::CXXDestructor:
9523     // C++11 [class.dtor]p5:
9524     //   A destructor is trivial if:
9525     //    - all the direct [subobjects] have trivial destructors
9526     if (RD->hasTrivialDestructor() ||
9527         (TAH == Sema::TAH_ConsiderTrivialABI &&
9528          RD->hasTrivialDestructorForCall()))
9529       return true;
9530 
9531     if (Selected) {
9532       if (RD->needsImplicitDestructor())
9533         S.DeclareImplicitDestructor(RD);
9534       *Selected = RD->getDestructor();
9535     }
9536 
9537     return false;
9538 
9539   case Sema::CXXCopyConstructor:
9540     // C++11 [class.copy]p12:
9541     //   A copy constructor is trivial if:
9542     //    - the constructor selected to copy each direct [subobject] is trivial
9543     if (RD->hasTrivialCopyConstructor() ||
9544         (TAH == Sema::TAH_ConsiderTrivialABI &&
9545          RD->hasTrivialCopyConstructorForCall())) {
9546       if (Quals == Qualifiers::Const)
9547         // We must either select the trivial copy constructor or reach an
9548         // ambiguity; no need to actually perform overload resolution.
9549         return true;
9550     } else if (!Selected) {
9551       return false;
9552     }
9553     // In C++98, we are not supposed to perform overload resolution here, but we
9554     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9555     // cases like B as having a non-trivial copy constructor:
9556     //   struct A { template<typename T> A(T&); };
9557     //   struct B { mutable A a; };
9558     goto NeedOverloadResolution;
9559 
9560   case Sema::CXXCopyAssignment:
9561     // C++11 [class.copy]p25:
9562     //   A copy assignment operator is trivial if:
9563     //    - the assignment operator selected to copy each direct [subobject] is
9564     //      trivial
9565     if (RD->hasTrivialCopyAssignment()) {
9566       if (Quals == Qualifiers::Const)
9567         return true;
9568     } else if (!Selected) {
9569       return false;
9570     }
9571     // In C++98, we are not supposed to perform overload resolution here, but we
9572     // treat that as a language defect.
9573     goto NeedOverloadResolution;
9574 
9575   case Sema::CXXMoveConstructor:
9576   case Sema::CXXMoveAssignment:
9577   NeedOverloadResolution:
9578     Sema::SpecialMemberOverloadResult SMOR =
9579         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9580 
9581     // The standard doesn't describe how to behave if the lookup is ambiguous.
9582     // We treat it as not making the member non-trivial, just like the standard
9583     // mandates for the default constructor. This should rarely matter, because
9584     // the member will also be deleted.
9585     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9586       return true;
9587 
9588     if (!SMOR.getMethod()) {
9589       assert(SMOR.getKind() ==
9590              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9591       return false;
9592     }
9593 
9594     // We deliberately don't check if we found a deleted special member. We're
9595     // not supposed to!
9596     if (Selected)
9597       *Selected = SMOR.getMethod();
9598 
9599     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9600         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9601       return SMOR.getMethod()->isTrivialForCall();
9602     return SMOR.getMethod()->isTrivial();
9603   }
9604 
9605   llvm_unreachable("unknown special method kind");
9606 }
9607 
9608 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9609   for (auto *CI : RD->ctors())
9610     if (!CI->isImplicit())
9611       return CI;
9612 
9613   // Look for constructor templates.
9614   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9615   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9616     if (CXXConstructorDecl *CD =
9617           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9618       return CD;
9619   }
9620 
9621   return nullptr;
9622 }
9623 
9624 /// The kind of subobject we are checking for triviality. The values of this
9625 /// enumeration are used in diagnostics.
9626 enum TrivialSubobjectKind {
9627   /// The subobject is a base class.
9628   TSK_BaseClass,
9629   /// The subobject is a non-static data member.
9630   TSK_Field,
9631   /// The object is actually the complete object.
9632   TSK_CompleteObject
9633 };
9634 
9635 /// Check whether the special member selected for a given type would be trivial.
9636 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9637                                       QualType SubType, bool ConstRHS,
9638                                       Sema::CXXSpecialMember CSM,
9639                                       TrivialSubobjectKind Kind,
9640                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9641   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9642   if (!SubRD)
9643     return true;
9644 
9645   CXXMethodDecl *Selected;
9646   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9647                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9648     return true;
9649 
9650   if (Diagnose) {
9651     if (ConstRHS)
9652       SubType.addConst();
9653 
9654     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9655       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9656         << Kind << SubType.getUnqualifiedType();
9657       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9658         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9659     } else if (!Selected)
9660       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9661         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9662     else if (Selected->isUserProvided()) {
9663       if (Kind == TSK_CompleteObject)
9664         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9665           << Kind << SubType.getUnqualifiedType() << CSM;
9666       else {
9667         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9668           << Kind << SubType.getUnqualifiedType() << CSM;
9669         S.Diag(Selected->getLocation(), diag::note_declared_at);
9670       }
9671     } else {
9672       if (Kind != TSK_CompleteObject)
9673         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9674           << Kind << SubType.getUnqualifiedType() << CSM;
9675 
9676       // Explain why the defaulted or deleted special member isn't trivial.
9677       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9678                                Diagnose);
9679     }
9680   }
9681 
9682   return false;
9683 }
9684 
9685 /// Check whether the members of a class type allow a special member to be
9686 /// trivial.
9687 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9688                                      Sema::CXXSpecialMember CSM,
9689                                      bool ConstArg,
9690                                      Sema::TrivialABIHandling TAH,
9691                                      bool Diagnose) {
9692   for (const auto *FI : RD->fields()) {
9693     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9694       continue;
9695 
9696     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9697 
9698     // Pretend anonymous struct or union members are members of this class.
9699     if (FI->isAnonymousStructOrUnion()) {
9700       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9701                                     CSM, ConstArg, TAH, Diagnose))
9702         return false;
9703       continue;
9704     }
9705 
9706     // C++11 [class.ctor]p5:
9707     //   A default constructor is trivial if [...]
9708     //    -- no non-static data member of its class has a
9709     //       brace-or-equal-initializer
9710     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9711       if (Diagnose)
9712         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9713             << FI;
9714       return false;
9715     }
9716 
9717     // Objective C ARC 4.3.5:
9718     //   [...] nontrivally ownership-qualified types are [...] not trivially
9719     //   default constructible, copy constructible, move constructible, copy
9720     //   assignable, move assignable, or destructible [...]
9721     if (FieldType.hasNonTrivialObjCLifetime()) {
9722       if (Diagnose)
9723         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9724           << RD << FieldType.getObjCLifetime();
9725       return false;
9726     }
9727 
9728     bool ConstRHS = ConstArg && !FI->isMutable();
9729     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9730                                    CSM, TSK_Field, TAH, Diagnose))
9731       return false;
9732   }
9733 
9734   return true;
9735 }
9736 
9737 /// Diagnose why the specified class does not have a trivial special member of
9738 /// the given kind.
9739 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9740   QualType Ty = Context.getRecordType(RD);
9741 
9742   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9743   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9744                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9745                             /*Diagnose*/true);
9746 }
9747 
9748 /// Determine whether a defaulted or deleted special member function is trivial,
9749 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9750 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9751 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9752                                   TrivialABIHandling TAH, bool Diagnose) {
9753   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9754 
9755   CXXRecordDecl *RD = MD->getParent();
9756 
9757   bool ConstArg = false;
9758 
9759   // C++11 [class.copy]p12, p25: [DR1593]
9760   //   A [special member] is trivial if [...] its parameter-type-list is
9761   //   equivalent to the parameter-type-list of an implicit declaration [...]
9762   switch (CSM) {
9763   case CXXDefaultConstructor:
9764   case CXXDestructor:
9765     // Trivial default constructors and destructors cannot have parameters.
9766     break;
9767 
9768   case CXXCopyConstructor:
9769   case CXXCopyAssignment: {
9770     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9771     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9772 
9773     // When ClangABICompat14 is true, CXX copy constructors will only be trivial
9774     // if they are not user-provided and their parameter-type-list is equivalent
9775     // to the parameter-type-list of an implicit declaration. This maintains the
9776     // behavior before dr2171 was implemented.
9777     //
9778     // Otherwise, if ClangABICompat14 is false, All copy constructors can be
9779     // trivial, if they are not user-provided, regardless of the qualifiers on
9780     // the reference type.
9781     const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
9782                                   LangOptions::ClangABI::Ver14;
9783     if (!RT ||
9784         ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
9785          ClangABICompat14)) {
9786       if (Diagnose)
9787         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9788           << Param0->getSourceRange() << Param0->getType()
9789           << Context.getLValueReferenceType(
9790                Context.getRecordType(RD).withConst());
9791       return false;
9792     }
9793 
9794     ConstArg = RT->getPointeeType().isConstQualified();
9795     break;
9796   }
9797 
9798   case CXXMoveConstructor:
9799   case CXXMoveAssignment: {
9800     // Trivial move operations always have non-cv-qualified parameters.
9801     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9802     const RValueReferenceType *RT =
9803       Param0->getType()->getAs<RValueReferenceType>();
9804     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9805       if (Diagnose)
9806         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9807           << Param0->getSourceRange() << Param0->getType()
9808           << Context.getRValueReferenceType(Context.getRecordType(RD));
9809       return false;
9810     }
9811     break;
9812   }
9813 
9814   case CXXInvalid:
9815     llvm_unreachable("not a special member");
9816   }
9817 
9818   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9819     if (Diagnose)
9820       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9821            diag::note_nontrivial_default_arg)
9822         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9823     return false;
9824   }
9825   if (MD->isVariadic()) {
9826     if (Diagnose)
9827       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9828     return false;
9829   }
9830 
9831   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9832   //   A copy/move [constructor or assignment operator] is trivial if
9833   //    -- the [member] selected to copy/move each direct base class subobject
9834   //       is trivial
9835   //
9836   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9837   //   A [default constructor or destructor] is trivial if
9838   //    -- all the direct base classes have trivial [default constructors or
9839   //       destructors]
9840   for (const auto &BI : RD->bases())
9841     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9842                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9843       return false;
9844 
9845   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9846   //   A copy/move [constructor or assignment operator] for a class X is
9847   //   trivial if
9848   //    -- for each non-static data member of X that is of class type (or array
9849   //       thereof), the constructor selected to copy/move that member is
9850   //       trivial
9851   //
9852   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9853   //   A [default constructor or destructor] is trivial if
9854   //    -- for all of the non-static data members of its class that are of class
9855   //       type (or array thereof), each such class has a trivial [default
9856   //       constructor or destructor]
9857   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9858     return false;
9859 
9860   // C++11 [class.dtor]p5:
9861   //   A destructor is trivial if [...]
9862   //    -- the destructor is not virtual
9863   if (CSM == CXXDestructor && MD->isVirtual()) {
9864     if (Diagnose)
9865       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9866     return false;
9867   }
9868 
9869   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9870   //   A [special member] for class X is trivial if [...]
9871   //    -- class X has no virtual functions and no virtual base classes
9872   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9873     if (!Diagnose)
9874       return false;
9875 
9876     if (RD->getNumVBases()) {
9877       // Check for virtual bases. We already know that the corresponding
9878       // member in all bases is trivial, so vbases must all be direct.
9879       CXXBaseSpecifier &BS = *RD->vbases_begin();
9880       assert(BS.isVirtual());
9881       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9882       return false;
9883     }
9884 
9885     // Must have a virtual method.
9886     for (const auto *MI : RD->methods()) {
9887       if (MI->isVirtual()) {
9888         SourceLocation MLoc = MI->getBeginLoc();
9889         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9890         return false;
9891       }
9892     }
9893 
9894     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9895   }
9896 
9897   // Looks like it's trivial!
9898   return true;
9899 }
9900 
9901 namespace {
9902 struct FindHiddenVirtualMethod {
9903   Sema *S;
9904   CXXMethodDecl *Method;
9905   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9906   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9907 
9908 private:
9909   /// Check whether any most overridden method from MD in Methods
9910   static bool CheckMostOverridenMethods(
9911       const CXXMethodDecl *MD,
9912       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9913     if (MD->size_overridden_methods() == 0)
9914       return Methods.count(MD->getCanonicalDecl());
9915     for (const CXXMethodDecl *O : MD->overridden_methods())
9916       if (CheckMostOverridenMethods(O, Methods))
9917         return true;
9918     return false;
9919   }
9920 
9921 public:
9922   /// Member lookup function that determines whether a given C++
9923   /// method overloads virtual methods in a base class without overriding any,
9924   /// to be used with CXXRecordDecl::lookupInBases().
9925   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9926     RecordDecl *BaseRecord =
9927         Specifier->getType()->castAs<RecordType>()->getDecl();
9928 
9929     DeclarationName Name = Method->getDeclName();
9930     assert(Name.getNameKind() == DeclarationName::Identifier);
9931 
9932     bool foundSameNameMethod = false;
9933     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9934     for (Path.Decls = BaseRecord->lookup(Name).begin();
9935          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9936       NamedDecl *D = *Path.Decls;
9937       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9938         MD = MD->getCanonicalDecl();
9939         foundSameNameMethod = true;
9940         // Interested only in hidden virtual methods.
9941         if (!MD->isVirtual())
9942           continue;
9943         // If the method we are checking overrides a method from its base
9944         // don't warn about the other overloaded methods. Clang deviates from
9945         // GCC by only diagnosing overloads of inherited virtual functions that
9946         // do not override any other virtual functions in the base. GCC's
9947         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9948         // function from a base class. These cases may be better served by a
9949         // warning (not specific to virtual functions) on call sites when the
9950         // call would select a different function from the base class, were it
9951         // visible.
9952         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9953         if (!S->IsOverload(Method, MD, false))
9954           return true;
9955         // Collect the overload only if its hidden.
9956         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9957           overloadedMethods.push_back(MD);
9958       }
9959     }
9960 
9961     if (foundSameNameMethod)
9962       OverloadedMethods.append(overloadedMethods.begin(),
9963                                overloadedMethods.end());
9964     return foundSameNameMethod;
9965   }
9966 };
9967 } // end anonymous namespace
9968 
9969 /// Add the most overridden methods from MD to Methods
9970 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9971                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9972   if (MD->size_overridden_methods() == 0)
9973     Methods.insert(MD->getCanonicalDecl());
9974   else
9975     for (const CXXMethodDecl *O : MD->overridden_methods())
9976       AddMostOverridenMethods(O, Methods);
9977 }
9978 
9979 /// Check if a method overloads virtual methods in a base class without
9980 /// overriding any.
9981 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9982                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9983   if (!MD->getDeclName().isIdentifier())
9984     return;
9985 
9986   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9987                      /*bool RecordPaths=*/false,
9988                      /*bool DetectVirtual=*/false);
9989   FindHiddenVirtualMethod FHVM;
9990   FHVM.Method = MD;
9991   FHVM.S = this;
9992 
9993   // Keep the base methods that were overridden or introduced in the subclass
9994   // by 'using' in a set. A base method not in this set is hidden.
9995   CXXRecordDecl *DC = MD->getParent();
9996   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9997   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9998     NamedDecl *ND = *I;
9999     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
10000       ND = shad->getTargetDecl();
10001     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
10002       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
10003   }
10004 
10005   if (DC->lookupInBases(FHVM, Paths))
10006     OverloadedMethods = FHVM.OverloadedMethods;
10007 }
10008 
10009 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10010                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10011   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
10012     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
10013     PartialDiagnostic PD = PDiag(
10014          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10015     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
10016     Diag(overloadedMD->getLocation(), PD);
10017   }
10018 }
10019 
10020 /// Diagnose methods which overload virtual methods in a base class
10021 /// without overriding any.
10022 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10023   if (MD->isInvalidDecl())
10024     return;
10025 
10026   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
10027     return;
10028 
10029   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10030   FindHiddenVirtualMethods(MD, OverloadedMethods);
10031   if (!OverloadedMethods.empty()) {
10032     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
10033       << MD << (OverloadedMethods.size() > 1);
10034 
10035     NoteHiddenVirtualMethods(MD, OverloadedMethods);
10036   }
10037 }
10038 
10039 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10040   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10041     // No diagnostics if this is a template instantiation.
10042     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
10043       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10044            diag::ext_cannot_use_trivial_abi) << &RD;
10045       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
10046            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10047     }
10048     RD.dropAttr<TrivialABIAttr>();
10049   };
10050 
10051   // Ill-formed if the copy and move constructors are deleted.
10052   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10053     // If the type is dependent, then assume it might have
10054     // implicit copy or move ctor because we won't know yet at this point.
10055     if (RD.isDependentType())
10056       return true;
10057     if (RD.needsImplicitCopyConstructor() &&
10058         !RD.defaultedCopyConstructorIsDeleted())
10059       return true;
10060     if (RD.needsImplicitMoveConstructor() &&
10061         !RD.defaultedMoveConstructorIsDeleted())
10062       return true;
10063     for (const CXXConstructorDecl *CD : RD.ctors())
10064       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10065         return true;
10066     return false;
10067   };
10068 
10069   if (!HasNonDeletedCopyOrMoveConstructor()) {
10070     PrintDiagAndRemoveAttr(0);
10071     return;
10072   }
10073 
10074   // Ill-formed if the struct has virtual functions.
10075   if (RD.isPolymorphic()) {
10076     PrintDiagAndRemoveAttr(1);
10077     return;
10078   }
10079 
10080   for (const auto &B : RD.bases()) {
10081     // Ill-formed if the base class is non-trivial for the purpose of calls or a
10082     // virtual base.
10083     if (!B.getType()->isDependentType() &&
10084         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10085       PrintDiagAndRemoveAttr(2);
10086       return;
10087     }
10088 
10089     if (B.isVirtual()) {
10090       PrintDiagAndRemoveAttr(3);
10091       return;
10092     }
10093   }
10094 
10095   for (const auto *FD : RD.fields()) {
10096     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10097     // non-trivial for the purpose of calls.
10098     QualType FT = FD->getType();
10099     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10100       PrintDiagAndRemoveAttr(4);
10101       return;
10102     }
10103 
10104     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10105       if (!RT->isDependentType() &&
10106           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10107         PrintDiagAndRemoveAttr(5);
10108         return;
10109       }
10110   }
10111 }
10112 
10113 void Sema::ActOnFinishCXXMemberSpecification(
10114     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10115     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10116   if (!TagDecl)
10117     return;
10118 
10119   AdjustDeclIfTemplate(TagDecl);
10120 
10121   for (const ParsedAttr &AL : AttrList) {
10122     if (AL.getKind() != ParsedAttr::AT_Visibility)
10123       continue;
10124     AL.setInvalid();
10125     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10126   }
10127 
10128   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
10129               // strict aliasing violation!
10130               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
10131               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
10132 
10133   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10134 }
10135 
10136 /// Find the equality comparison functions that should be implicitly declared
10137 /// in a given class definition, per C++2a [class.compare.default]p3.
10138 static void findImplicitlyDeclaredEqualityComparisons(
10139     ASTContext &Ctx, CXXRecordDecl *RD,
10140     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10141   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10142   if (!RD->lookup(EqEq).empty())
10143     // Member operator== explicitly declared: no implicit operator==s.
10144     return;
10145 
10146   // Traverse friends looking for an '==' or a '<=>'.
10147   for (FriendDecl *Friend : RD->friends()) {
10148     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10149     if (!FD) continue;
10150 
10151     if (FD->getOverloadedOperator() == OO_EqualEqual) {
10152       // Friend operator== explicitly declared: no implicit operator==s.
10153       Spaceships.clear();
10154       return;
10155     }
10156 
10157     if (FD->getOverloadedOperator() == OO_Spaceship &&
10158         FD->isExplicitlyDefaulted())
10159       Spaceships.push_back(FD);
10160   }
10161 
10162   // Look for members named 'operator<=>'.
10163   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10164   for (NamedDecl *ND : RD->lookup(Cmp)) {
10165     // Note that we could find a non-function here (either a function template
10166     // or a using-declaration). Neither case results in an implicit
10167     // 'operator=='.
10168     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10169       if (FD->isExplicitlyDefaulted())
10170         Spaceships.push_back(FD);
10171   }
10172 }
10173 
10174 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10175 /// special functions, such as the default constructor, copy
10176 /// constructor, or destructor, to the given C++ class (C++
10177 /// [special]p1).  This routine can only be executed just before the
10178 /// definition of the class is complete.
10179 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10180   // Don't add implicit special members to templated classes.
10181   // FIXME: This means unqualified lookups for 'operator=' within a class
10182   // template don't work properly.
10183   if (!ClassDecl->isDependentType()) {
10184     if (ClassDecl->needsImplicitDefaultConstructor()) {
10185       ++getASTContext().NumImplicitDefaultConstructors;
10186 
10187       if (ClassDecl->hasInheritedConstructor())
10188         DeclareImplicitDefaultConstructor(ClassDecl);
10189     }
10190 
10191     if (ClassDecl->needsImplicitCopyConstructor()) {
10192       ++getASTContext().NumImplicitCopyConstructors;
10193 
10194       // If the properties or semantics of the copy constructor couldn't be
10195       // determined while the class was being declared, force a declaration
10196       // of it now.
10197       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10198           ClassDecl->hasInheritedConstructor())
10199         DeclareImplicitCopyConstructor(ClassDecl);
10200       // For the MS ABI we need to know whether the copy ctor is deleted. A
10201       // prerequisite for deleting the implicit copy ctor is that the class has
10202       // a move ctor or move assignment that is either user-declared or whose
10203       // semantics are inherited from a subobject. FIXME: We should provide a
10204       // more direct way for CodeGen to ask whether the constructor was deleted.
10205       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10206                (ClassDecl->hasUserDeclaredMoveConstructor() ||
10207                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10208                 ClassDecl->hasUserDeclaredMoveAssignment() ||
10209                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10210         DeclareImplicitCopyConstructor(ClassDecl);
10211     }
10212 
10213     if (getLangOpts().CPlusPlus11 &&
10214         ClassDecl->needsImplicitMoveConstructor()) {
10215       ++getASTContext().NumImplicitMoveConstructors;
10216 
10217       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10218           ClassDecl->hasInheritedConstructor())
10219         DeclareImplicitMoveConstructor(ClassDecl);
10220     }
10221 
10222     if (ClassDecl->needsImplicitCopyAssignment()) {
10223       ++getASTContext().NumImplicitCopyAssignmentOperators;
10224 
10225       // If we have a dynamic class, then the copy assignment operator may be
10226       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10227       // it shows up in the right place in the vtable and that we diagnose
10228       // problems with the implicit exception specification.
10229       if (ClassDecl->isDynamicClass() ||
10230           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10231           ClassDecl->hasInheritedAssignment())
10232         DeclareImplicitCopyAssignment(ClassDecl);
10233     }
10234 
10235     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10236       ++getASTContext().NumImplicitMoveAssignmentOperators;
10237 
10238       // Likewise for the move assignment operator.
10239       if (ClassDecl->isDynamicClass() ||
10240           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10241           ClassDecl->hasInheritedAssignment())
10242         DeclareImplicitMoveAssignment(ClassDecl);
10243     }
10244 
10245     if (ClassDecl->needsImplicitDestructor()) {
10246       ++getASTContext().NumImplicitDestructors;
10247 
10248       // If we have a dynamic class, then the destructor may be virtual, so we
10249       // have to declare the destructor immediately. This ensures that, e.g., it
10250       // shows up in the right place in the vtable and that we diagnose problems
10251       // with the implicit exception specification.
10252       if (ClassDecl->isDynamicClass() ||
10253           ClassDecl->needsOverloadResolutionForDestructor())
10254         DeclareImplicitDestructor(ClassDecl);
10255     }
10256   }
10257 
10258   // C++2a [class.compare.default]p3:
10259   //   If the member-specification does not explicitly declare any member or
10260   //   friend named operator==, an == operator function is declared implicitly
10261   //   for each defaulted three-way comparison operator function defined in
10262   //   the member-specification
10263   // FIXME: Consider doing this lazily.
10264   // We do this during the initial parse for a class template, not during
10265   // instantiation, so that we can handle unqualified lookups for 'operator=='
10266   // when parsing the template.
10267   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10268     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10269     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10270                                               DefaultedSpaceships);
10271     for (auto *FD : DefaultedSpaceships)
10272       DeclareImplicitEqualityComparison(ClassDecl, FD);
10273   }
10274 }
10275 
10276 unsigned
10277 Sema::ActOnReenterTemplateScope(Decl *D,
10278                                 llvm::function_ref<Scope *()> EnterScope) {
10279   if (!D)
10280     return 0;
10281   AdjustDeclIfTemplate(D);
10282 
10283   // In order to get name lookup right, reenter template scopes in order from
10284   // outermost to innermost.
10285   SmallVector<TemplateParameterList *, 4> ParameterLists;
10286   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10287 
10288   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10289     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10290       ParameterLists.push_back(DD->getTemplateParameterList(i));
10291 
10292     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10293       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10294         ParameterLists.push_back(FTD->getTemplateParameters());
10295     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10296       LookupDC = VD->getDeclContext();
10297 
10298       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10299         ParameterLists.push_back(VTD->getTemplateParameters());
10300       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10301         ParameterLists.push_back(PSD->getTemplateParameters());
10302     }
10303   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10304     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10305       ParameterLists.push_back(TD->getTemplateParameterList(i));
10306 
10307     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10308       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10309         ParameterLists.push_back(CTD->getTemplateParameters());
10310       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10311         ParameterLists.push_back(PSD->getTemplateParameters());
10312     }
10313   }
10314   // FIXME: Alias declarations and concepts.
10315 
10316   unsigned Count = 0;
10317   Scope *InnermostTemplateScope = nullptr;
10318   for (TemplateParameterList *Params : ParameterLists) {
10319     // Ignore explicit specializations; they don't contribute to the template
10320     // depth.
10321     if (Params->size() == 0)
10322       continue;
10323 
10324     InnermostTemplateScope = EnterScope();
10325     for (NamedDecl *Param : *Params) {
10326       if (Param->getDeclName()) {
10327         InnermostTemplateScope->AddDecl(Param);
10328         IdResolver.AddDecl(Param);
10329       }
10330     }
10331     ++Count;
10332   }
10333 
10334   // Associate the new template scopes with the corresponding entities.
10335   if (InnermostTemplateScope) {
10336     assert(LookupDC && "no enclosing DeclContext for template lookup");
10337     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10338   }
10339 
10340   return Count;
10341 }
10342 
10343 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10344   if (!RecordD) return;
10345   AdjustDeclIfTemplate(RecordD);
10346   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10347   PushDeclContext(S, Record);
10348 }
10349 
10350 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10351   if (!RecordD) return;
10352   PopDeclContext();
10353 }
10354 
10355 /// This is used to implement the constant expression evaluation part of the
10356 /// attribute enable_if extension. There is nothing in standard C++ which would
10357 /// require reentering parameters.
10358 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10359   if (!Param)
10360     return;
10361 
10362   S->AddDecl(Param);
10363   if (Param->getDeclName())
10364     IdResolver.AddDecl(Param);
10365 }
10366 
10367 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10368 /// parsing a top-level (non-nested) C++ class, and we are now
10369 /// parsing those parts of the given Method declaration that could
10370 /// not be parsed earlier (C++ [class.mem]p2), such as default
10371 /// arguments. This action should enter the scope of the given
10372 /// Method declaration as if we had just parsed the qualified method
10373 /// name. However, it should not bring the parameters into scope;
10374 /// that will be performed by ActOnDelayedCXXMethodParameter.
10375 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10376 }
10377 
10378 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10379 /// C++ method declaration. We're (re-)introducing the given
10380 /// function parameter into scope for use in parsing later parts of
10381 /// the method declaration. For example, we could see an
10382 /// ActOnParamDefaultArgument event for this parameter.
10383 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10384   if (!ParamD)
10385     return;
10386 
10387   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10388 
10389   S->AddDecl(Param);
10390   if (Param->getDeclName())
10391     IdResolver.AddDecl(Param);
10392 }
10393 
10394 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10395 /// processing the delayed method declaration for Method. The method
10396 /// declaration is now considered finished. There may be a separate
10397 /// ActOnStartOfFunctionDef action later (not necessarily
10398 /// immediately!) for this method, if it was also defined inside the
10399 /// class body.
10400 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10401   if (!MethodD)
10402     return;
10403 
10404   AdjustDeclIfTemplate(MethodD);
10405 
10406   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10407 
10408   // Now that we have our default arguments, check the constructor
10409   // again. It could produce additional diagnostics or affect whether
10410   // the class has implicitly-declared destructors, among other
10411   // things.
10412   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10413     CheckConstructor(Constructor);
10414 
10415   // Check the default arguments, which we may have added.
10416   if (!Method->isInvalidDecl())
10417     CheckCXXDefaultArguments(Method);
10418 }
10419 
10420 // Emit the given diagnostic for each non-address-space qualifier.
10421 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10422 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10423   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10424   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10425     bool DiagOccured = false;
10426     FTI.MethodQualifiers->forEachQualifier(
10427         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10428                                    SourceLocation SL) {
10429           // This diagnostic should be emitted on any qualifier except an addr
10430           // space qualifier. However, forEachQualifier currently doesn't visit
10431           // addr space qualifiers, so there's no way to write this condition
10432           // right now; we just diagnose on everything.
10433           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10434           DiagOccured = true;
10435         });
10436     if (DiagOccured)
10437       D.setInvalidType();
10438   }
10439 }
10440 
10441 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10442 /// the well-formedness of the constructor declarator @p D with type @p
10443 /// R. If there are any errors in the declarator, this routine will
10444 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10445 /// will be updated to reflect a well-formed type for the constructor and
10446 /// returned.
10447 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10448                                           StorageClass &SC) {
10449   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10450 
10451   // C++ [class.ctor]p3:
10452   //   A constructor shall not be virtual (10.3) or static (9.4). A
10453   //   constructor can be invoked for a const, volatile or const
10454   //   volatile object. A constructor shall not be declared const,
10455   //   volatile, or const volatile (9.3.2).
10456   if (isVirtual) {
10457     if (!D.isInvalidType())
10458       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10459         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10460         << SourceRange(D.getIdentifierLoc());
10461     D.setInvalidType();
10462   }
10463   if (SC == SC_Static) {
10464     if (!D.isInvalidType())
10465       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10466         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10467         << SourceRange(D.getIdentifierLoc());
10468     D.setInvalidType();
10469     SC = SC_None;
10470   }
10471 
10472   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10473     diagnoseIgnoredQualifiers(
10474         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10475         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10476         D.getDeclSpec().getRestrictSpecLoc(),
10477         D.getDeclSpec().getAtomicSpecLoc());
10478     D.setInvalidType();
10479   }
10480 
10481   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10482 
10483   // C++0x [class.ctor]p4:
10484   //   A constructor shall not be declared with a ref-qualifier.
10485   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10486   if (FTI.hasRefQualifier()) {
10487     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10488       << FTI.RefQualifierIsLValueRef
10489       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10490     D.setInvalidType();
10491   }
10492 
10493   // Rebuild the function type "R" without any type qualifiers (in
10494   // case any of the errors above fired) and with "void" as the
10495   // return type, since constructors don't have return types.
10496   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10497   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10498     return R;
10499 
10500   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10501   EPI.TypeQuals = Qualifiers();
10502   EPI.RefQualifier = RQ_None;
10503 
10504   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10505 }
10506 
10507 /// CheckConstructor - Checks a fully-formed constructor for
10508 /// well-formedness, issuing any diagnostics required. Returns true if
10509 /// the constructor declarator is invalid.
10510 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10511   CXXRecordDecl *ClassDecl
10512     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10513   if (!ClassDecl)
10514     return Constructor->setInvalidDecl();
10515 
10516   // C++ [class.copy]p3:
10517   //   A declaration of a constructor for a class X is ill-formed if
10518   //   its first parameter is of type (optionally cv-qualified) X and
10519   //   either there are no other parameters or else all other
10520   //   parameters have default arguments.
10521   if (!Constructor->isInvalidDecl() &&
10522       Constructor->hasOneParamOrDefaultArgs() &&
10523       Constructor->getTemplateSpecializationKind() !=
10524           TSK_ImplicitInstantiation) {
10525     QualType ParamType = Constructor->getParamDecl(0)->getType();
10526     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10527     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10528       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10529       const char *ConstRef
10530         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10531                                                         : " const &";
10532       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10533         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10534 
10535       // FIXME: Rather that making the constructor invalid, we should endeavor
10536       // to fix the type.
10537       Constructor->setInvalidDecl();
10538     }
10539   }
10540 }
10541 
10542 /// CheckDestructor - Checks a fully-formed destructor definition for
10543 /// well-formedness, issuing any diagnostics required.  Returns true
10544 /// on error.
10545 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10546   CXXRecordDecl *RD = Destructor->getParent();
10547 
10548   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10549     SourceLocation Loc;
10550 
10551     if (!Destructor->isImplicit())
10552       Loc = Destructor->getLocation();
10553     else
10554       Loc = RD->getLocation();
10555 
10556     // If we have a virtual destructor, look up the deallocation function
10557     if (FunctionDecl *OperatorDelete =
10558             FindDeallocationFunctionForDestructor(Loc, RD)) {
10559       Expr *ThisArg = nullptr;
10560 
10561       // If the notional 'delete this' expression requires a non-trivial
10562       // conversion from 'this' to the type of a destroying operator delete's
10563       // first parameter, perform that conversion now.
10564       if (OperatorDelete->isDestroyingOperatorDelete()) {
10565         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10566         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10567           // C++ [class.dtor]p13:
10568           //   ... as if for the expression 'delete this' appearing in a
10569           //   non-virtual destructor of the destructor's class.
10570           ContextRAII SwitchContext(*this, Destructor);
10571           ExprResult This =
10572               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10573           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10574           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10575           if (This.isInvalid()) {
10576             // FIXME: Register this as a context note so that it comes out
10577             // in the right order.
10578             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10579             return true;
10580           }
10581           ThisArg = This.get();
10582         }
10583       }
10584 
10585       DiagnoseUseOfDecl(OperatorDelete, Loc);
10586       MarkFunctionReferenced(Loc, OperatorDelete);
10587       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10588     }
10589   }
10590 
10591   return false;
10592 }
10593 
10594 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10595 /// the well-formednes of the destructor declarator @p D with type @p
10596 /// R. If there are any errors in the declarator, this routine will
10597 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10598 /// will be updated to reflect a well-formed type for the destructor and
10599 /// returned.
10600 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10601                                          StorageClass& SC) {
10602   // C++ [class.dtor]p1:
10603   //   [...] A typedef-name that names a class is a class-name
10604   //   (7.1.3); however, a typedef-name that names a class shall not
10605   //   be used as the identifier in the declarator for a destructor
10606   //   declaration.
10607   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10608   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10609     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10610       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10611   else if (const TemplateSpecializationType *TST =
10612              DeclaratorType->getAs<TemplateSpecializationType>())
10613     if (TST->isTypeAlias())
10614       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10615         << DeclaratorType << 1;
10616 
10617   // C++ [class.dtor]p2:
10618   //   A destructor is used to destroy objects of its class type. A
10619   //   destructor takes no parameters, and no return type can be
10620   //   specified for it (not even void). The address of a destructor
10621   //   shall not be taken. A destructor shall not be static. A
10622   //   destructor can be invoked for a const, volatile or const
10623   //   volatile object. A destructor shall not be declared const,
10624   //   volatile or const volatile (9.3.2).
10625   if (SC == SC_Static) {
10626     if (!D.isInvalidType())
10627       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10628         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10629         << SourceRange(D.getIdentifierLoc())
10630         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10631 
10632     SC = SC_None;
10633   }
10634   if (!D.isInvalidType()) {
10635     // Destructors don't have return types, but the parser will
10636     // happily parse something like:
10637     //
10638     //   class X {
10639     //     float ~X();
10640     //   };
10641     //
10642     // The return type will be eliminated later.
10643     if (D.getDeclSpec().hasTypeSpecifier())
10644       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10645         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10646         << SourceRange(D.getIdentifierLoc());
10647     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10648       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10649                                 SourceLocation(),
10650                                 D.getDeclSpec().getConstSpecLoc(),
10651                                 D.getDeclSpec().getVolatileSpecLoc(),
10652                                 D.getDeclSpec().getRestrictSpecLoc(),
10653                                 D.getDeclSpec().getAtomicSpecLoc());
10654       D.setInvalidType();
10655     }
10656   }
10657 
10658   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10659 
10660   // C++0x [class.dtor]p2:
10661   //   A destructor shall not be declared with a ref-qualifier.
10662   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10663   if (FTI.hasRefQualifier()) {
10664     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10665       << FTI.RefQualifierIsLValueRef
10666       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10667     D.setInvalidType();
10668   }
10669 
10670   // Make sure we don't have any parameters.
10671   if (FTIHasNonVoidParameters(FTI)) {
10672     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10673 
10674     // Delete the parameters.
10675     FTI.freeParams();
10676     D.setInvalidType();
10677   }
10678 
10679   // Make sure the destructor isn't variadic.
10680   if (FTI.isVariadic) {
10681     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10682     D.setInvalidType();
10683   }
10684 
10685   // Rebuild the function type "R" without any type qualifiers or
10686   // parameters (in case any of the errors above fired) and with
10687   // "void" as the return type, since destructors don't have return
10688   // types.
10689   if (!D.isInvalidType())
10690     return R;
10691 
10692   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10693   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10694   EPI.Variadic = false;
10695   EPI.TypeQuals = Qualifiers();
10696   EPI.RefQualifier = RQ_None;
10697   return Context.getFunctionType(Context.VoidTy, None, EPI);
10698 }
10699 
10700 static void extendLeft(SourceRange &R, SourceRange Before) {
10701   if (Before.isInvalid())
10702     return;
10703   R.setBegin(Before.getBegin());
10704   if (R.getEnd().isInvalid())
10705     R.setEnd(Before.getEnd());
10706 }
10707 
10708 static void extendRight(SourceRange &R, SourceRange After) {
10709   if (After.isInvalid())
10710     return;
10711   if (R.getBegin().isInvalid())
10712     R.setBegin(After.getBegin());
10713   R.setEnd(After.getEnd());
10714 }
10715 
10716 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10717 /// well-formednes of the conversion function declarator @p D with
10718 /// type @p R. If there are any errors in the declarator, this routine
10719 /// will emit diagnostics and return true. Otherwise, it will return
10720 /// false. Either way, the type @p R will be updated to reflect a
10721 /// well-formed type for the conversion operator.
10722 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10723                                      StorageClass& SC) {
10724   // C++ [class.conv.fct]p1:
10725   //   Neither parameter types nor return type can be specified. The
10726   //   type of a conversion function (8.3.5) is "function taking no
10727   //   parameter returning conversion-type-id."
10728   if (SC == SC_Static) {
10729     if (!D.isInvalidType())
10730       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10731         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10732         << D.getName().getSourceRange();
10733     D.setInvalidType();
10734     SC = SC_None;
10735   }
10736 
10737   TypeSourceInfo *ConvTSI = nullptr;
10738   QualType ConvType =
10739       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10740 
10741   const DeclSpec &DS = D.getDeclSpec();
10742   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10743     // Conversion functions don't have return types, but the parser will
10744     // happily parse something like:
10745     //
10746     //   class X {
10747     //     float operator bool();
10748     //   };
10749     //
10750     // The return type will be changed later anyway.
10751     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10752       << SourceRange(DS.getTypeSpecTypeLoc())
10753       << SourceRange(D.getIdentifierLoc());
10754     D.setInvalidType();
10755   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10756     // It's also plausible that the user writes type qualifiers in the wrong
10757     // place, such as:
10758     //   struct S { const operator int(); };
10759     // FIXME: we could provide a fixit to move the qualifiers onto the
10760     // conversion type.
10761     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10762         << SourceRange(D.getIdentifierLoc()) << 0;
10763     D.setInvalidType();
10764   }
10765 
10766   const auto *Proto = R->castAs<FunctionProtoType>();
10767 
10768   // Make sure we don't have any parameters.
10769   if (Proto->getNumParams() > 0) {
10770     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10771 
10772     // Delete the parameters.
10773     D.getFunctionTypeInfo().freeParams();
10774     D.setInvalidType();
10775   } else if (Proto->isVariadic()) {
10776     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10777     D.setInvalidType();
10778   }
10779 
10780   // Diagnose "&operator bool()" and other such nonsense.  This
10781   // is actually a gcc extension which we don't support.
10782   if (Proto->getReturnType() != ConvType) {
10783     bool NeedsTypedef = false;
10784     SourceRange Before, After;
10785 
10786     // Walk the chunks and extract information on them for our diagnostic.
10787     bool PastFunctionChunk = false;
10788     for (auto &Chunk : D.type_objects()) {
10789       switch (Chunk.Kind) {
10790       case DeclaratorChunk::Function:
10791         if (!PastFunctionChunk) {
10792           if (Chunk.Fun.HasTrailingReturnType) {
10793             TypeSourceInfo *TRT = nullptr;
10794             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10795             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10796           }
10797           PastFunctionChunk = true;
10798           break;
10799         }
10800         LLVM_FALLTHROUGH;
10801       case DeclaratorChunk::Array:
10802         NeedsTypedef = true;
10803         extendRight(After, Chunk.getSourceRange());
10804         break;
10805 
10806       case DeclaratorChunk::Pointer:
10807       case DeclaratorChunk::BlockPointer:
10808       case DeclaratorChunk::Reference:
10809       case DeclaratorChunk::MemberPointer:
10810       case DeclaratorChunk::Pipe:
10811         extendLeft(Before, Chunk.getSourceRange());
10812         break;
10813 
10814       case DeclaratorChunk::Paren:
10815         extendLeft(Before, Chunk.Loc);
10816         extendRight(After, Chunk.EndLoc);
10817         break;
10818       }
10819     }
10820 
10821     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10822                          After.isValid()  ? After.getBegin() :
10823                                             D.getIdentifierLoc();
10824     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10825     DB << Before << After;
10826 
10827     if (!NeedsTypedef) {
10828       DB << /*don't need a typedef*/0;
10829 
10830       // If we can provide a correct fix-it hint, do so.
10831       if (After.isInvalid() && ConvTSI) {
10832         SourceLocation InsertLoc =
10833             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10834         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10835            << FixItHint::CreateInsertionFromRange(
10836                   InsertLoc, CharSourceRange::getTokenRange(Before))
10837            << FixItHint::CreateRemoval(Before);
10838       }
10839     } else if (!Proto->getReturnType()->isDependentType()) {
10840       DB << /*typedef*/1 << Proto->getReturnType();
10841     } else if (getLangOpts().CPlusPlus11) {
10842       DB << /*alias template*/2 << Proto->getReturnType();
10843     } else {
10844       DB << /*might not be fixable*/3;
10845     }
10846 
10847     // Recover by incorporating the other type chunks into the result type.
10848     // Note, this does *not* change the name of the function. This is compatible
10849     // with the GCC extension:
10850     //   struct S { &operator int(); } s;
10851     //   int &r = s.operator int(); // ok in GCC
10852     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10853     ConvType = Proto->getReturnType();
10854   }
10855 
10856   // C++ [class.conv.fct]p4:
10857   //   The conversion-type-id shall not represent a function type nor
10858   //   an array type.
10859   if (ConvType->isArrayType()) {
10860     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10861     ConvType = Context.getPointerType(ConvType);
10862     D.setInvalidType();
10863   } else if (ConvType->isFunctionType()) {
10864     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10865     ConvType = Context.getPointerType(ConvType);
10866     D.setInvalidType();
10867   }
10868 
10869   // Rebuild the function type "R" without any parameters (in case any
10870   // of the errors above fired) and with the conversion type as the
10871   // return type.
10872   if (D.isInvalidType())
10873     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10874 
10875   // C++0x explicit conversion operators.
10876   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10877     Diag(DS.getExplicitSpecLoc(),
10878          getLangOpts().CPlusPlus11
10879              ? diag::warn_cxx98_compat_explicit_conversion_functions
10880              : diag::ext_explicit_conversion_functions)
10881         << SourceRange(DS.getExplicitSpecRange());
10882 }
10883 
10884 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10885 /// the declaration of the given C++ conversion function. This routine
10886 /// is responsible for recording the conversion function in the C++
10887 /// class, if possible.
10888 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10889   assert(Conversion && "Expected to receive a conversion function declaration");
10890 
10891   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10892 
10893   // Make sure we aren't redeclaring the conversion function.
10894   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10895   // C++ [class.conv.fct]p1:
10896   //   [...] A conversion function is never used to convert a
10897   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10898   //   same object type (or a reference to it), to a (possibly
10899   //   cv-qualified) base class of that type (or a reference to it),
10900   //   or to (possibly cv-qualified) void.
10901   QualType ClassType
10902     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10903   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10904     ConvType = ConvTypeRef->getPointeeType();
10905   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10906       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10907     /* Suppress diagnostics for instantiations. */;
10908   else if (Conversion->size_overridden_methods() != 0)
10909     /* Suppress diagnostics for overriding virtual function in a base class. */;
10910   else if (ConvType->isRecordType()) {
10911     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10912     if (ConvType == ClassType)
10913       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10914         << ClassType;
10915     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10916       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10917         <<  ClassType << ConvType;
10918   } else if (ConvType->isVoidType()) {
10919     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10920       << ClassType << ConvType;
10921   }
10922 
10923   if (FunctionTemplateDecl *ConversionTemplate
10924                                 = Conversion->getDescribedFunctionTemplate())
10925     return ConversionTemplate;
10926 
10927   return Conversion;
10928 }
10929 
10930 namespace {
10931 /// Utility class to accumulate and print a diagnostic listing the invalid
10932 /// specifier(s) on a declaration.
10933 struct BadSpecifierDiagnoser {
10934   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10935       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10936   ~BadSpecifierDiagnoser() {
10937     Diagnostic << Specifiers;
10938   }
10939 
10940   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10941     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10942   }
10943   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10944     return check(SpecLoc,
10945                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10946   }
10947   void check(SourceLocation SpecLoc, const char *Spec) {
10948     if (SpecLoc.isInvalid()) return;
10949     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10950     if (!Specifiers.empty()) Specifiers += " ";
10951     Specifiers += Spec;
10952   }
10953 
10954   Sema &S;
10955   Sema::SemaDiagnosticBuilder Diagnostic;
10956   std::string Specifiers;
10957 };
10958 }
10959 
10960 /// Check the validity of a declarator that we parsed for a deduction-guide.
10961 /// These aren't actually declarators in the grammar, so we need to check that
10962 /// the user didn't specify any pieces that are not part of the deduction-guide
10963 /// grammar.
10964 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10965                                          StorageClass &SC) {
10966   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10967   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10968   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10969 
10970   // C++ [temp.deduct.guide]p3:
10971   //   A deduction-gide shall be declared in the same scope as the
10972   //   corresponding class template.
10973   if (!CurContext->getRedeclContext()->Equals(
10974           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10975     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10976       << GuidedTemplateDecl;
10977     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10978   }
10979 
10980   auto &DS = D.getMutableDeclSpec();
10981   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10982   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10983       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10984       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10985     BadSpecifierDiagnoser Diagnoser(
10986         *this, D.getIdentifierLoc(),
10987         diag::err_deduction_guide_invalid_specifier);
10988 
10989     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10990     DS.ClearStorageClassSpecs();
10991     SC = SC_None;
10992 
10993     // 'explicit' is permitted.
10994     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10995     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10996     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10997     DS.ClearConstexprSpec();
10998 
10999     Diagnoser.check(DS.getConstSpecLoc(), "const");
11000     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
11001     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
11002     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
11003     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
11004     DS.ClearTypeQualifiers();
11005 
11006     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
11007     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
11008     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
11009     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
11010     DS.ClearTypeSpecType();
11011   }
11012 
11013   if (D.isInvalidType())
11014     return;
11015 
11016   // Check the declarator is simple enough.
11017   bool FoundFunction = false;
11018   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
11019     if (Chunk.Kind == DeclaratorChunk::Paren)
11020       continue;
11021     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11022       Diag(D.getDeclSpec().getBeginLoc(),
11023            diag::err_deduction_guide_with_complex_decl)
11024           << D.getSourceRange();
11025       break;
11026     }
11027     if (!Chunk.Fun.hasTrailingReturnType()) {
11028       Diag(D.getName().getBeginLoc(),
11029            diag::err_deduction_guide_no_trailing_return_type);
11030       break;
11031     }
11032 
11033     // Check that the return type is written as a specialization of
11034     // the template specified as the deduction-guide's name.
11035     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11036     TypeSourceInfo *TSI = nullptr;
11037     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
11038     assert(TSI && "deduction guide has valid type but invalid return type?");
11039     bool AcceptableReturnType = false;
11040     bool MightInstantiateToSpecialization = false;
11041     if (auto RetTST =
11042             TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11043       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11044       bool TemplateMatches =
11045           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
11046       // FIXME: We should consider other template kinds (using, qualified),
11047       // otherwise we will emit bogus diagnostics.
11048       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
11049         AcceptableReturnType = true;
11050       else {
11051         // This could still instantiate to the right type, unless we know it
11052         // names the wrong class template.
11053         auto *TD = SpecifiedName.getAsTemplateDecl();
11054         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
11055                                              !TemplateMatches);
11056       }
11057     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11058       MightInstantiateToSpecialization = true;
11059     }
11060 
11061     if (!AcceptableReturnType) {
11062       Diag(TSI->getTypeLoc().getBeginLoc(),
11063            diag::err_deduction_guide_bad_trailing_return_type)
11064           << GuidedTemplate << TSI->getType()
11065           << MightInstantiateToSpecialization
11066           << TSI->getTypeLoc().getSourceRange();
11067     }
11068 
11069     // Keep going to check that we don't have any inner declarator pieces (we
11070     // could still have a function returning a pointer to a function).
11071     FoundFunction = true;
11072   }
11073 
11074   if (D.isFunctionDefinition())
11075     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11076 }
11077 
11078 //===----------------------------------------------------------------------===//
11079 // Namespace Handling
11080 //===----------------------------------------------------------------------===//
11081 
11082 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11083 /// reopened.
11084 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11085                                             SourceLocation Loc,
11086                                             IdentifierInfo *II, bool *IsInline,
11087                                             NamespaceDecl *PrevNS) {
11088   assert(*IsInline != PrevNS->isInline());
11089 
11090   // 'inline' must appear on the original definition, but not necessarily
11091   // on all extension definitions, so the note should point to the first
11092   // definition to avoid confusion.
11093   PrevNS = PrevNS->getFirstDecl();
11094 
11095   if (PrevNS->isInline())
11096     // The user probably just forgot the 'inline', so suggest that it
11097     // be added back.
11098     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11099       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11100   else
11101     S.Diag(Loc, diag::err_inline_namespace_mismatch);
11102 
11103   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11104   *IsInline = PrevNS->isInline();
11105 }
11106 
11107 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11108 /// definition.
11109 Decl *Sema::ActOnStartNamespaceDef(
11110     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
11111     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
11112     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
11113   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11114   // For anonymous namespace, take the location of the left brace.
11115   SourceLocation Loc = II ? IdentLoc : LBrace;
11116   bool IsInline = InlineLoc.isValid();
11117   bool IsInvalid = false;
11118   bool IsStd = false;
11119   bool AddToKnown = false;
11120   Scope *DeclRegionScope = NamespcScope->getParent();
11121 
11122   NamespaceDecl *PrevNS = nullptr;
11123   if (II) {
11124     // C++ [namespace.def]p2:
11125     //   The identifier in an original-namespace-definition shall not
11126     //   have been previously defined in the declarative region in
11127     //   which the original-namespace-definition appears. The
11128     //   identifier in an original-namespace-definition is the name of
11129     //   the namespace. Subsequently in that declarative region, it is
11130     //   treated as an original-namespace-name.
11131     //
11132     // Since namespace names are unique in their scope, and we don't
11133     // look through using directives, just look for any ordinary names
11134     // as if by qualified name lookup.
11135     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11136                    ForExternalRedeclaration);
11137     LookupQualifiedName(R, CurContext->getRedeclContext());
11138     NamedDecl *PrevDecl =
11139         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11140     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11141 
11142     if (PrevNS) {
11143       // This is an extended namespace definition.
11144       if (IsInline != PrevNS->isInline())
11145         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11146                                         &IsInline, PrevNS);
11147     } else if (PrevDecl) {
11148       // This is an invalid name redefinition.
11149       Diag(Loc, diag::err_redefinition_different_kind)
11150         << II;
11151       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11152       IsInvalid = true;
11153       // Continue on to push Namespc as current DeclContext and return it.
11154     } else if (II->isStr("std") &&
11155                CurContext->getRedeclContext()->isTranslationUnit()) {
11156       // This is the first "real" definition of the namespace "std", so update
11157       // our cache of the "std" namespace to point at this definition.
11158       PrevNS = getStdNamespace();
11159       IsStd = true;
11160       AddToKnown = !IsInline;
11161     } else {
11162       // We've seen this namespace for the first time.
11163       AddToKnown = !IsInline;
11164     }
11165   } else {
11166     // Anonymous namespaces.
11167 
11168     // Determine whether the parent already has an anonymous namespace.
11169     DeclContext *Parent = CurContext->getRedeclContext();
11170     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11171       PrevNS = TU->getAnonymousNamespace();
11172     } else {
11173       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11174       PrevNS = ND->getAnonymousNamespace();
11175     }
11176 
11177     if (PrevNS && IsInline != PrevNS->isInline())
11178       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11179                                       &IsInline, PrevNS);
11180   }
11181 
11182   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
11183                                                  StartLoc, Loc, II, PrevNS);
11184   if (IsInvalid)
11185     Namespc->setInvalidDecl();
11186 
11187   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11188   AddPragmaAttributes(DeclRegionScope, Namespc);
11189 
11190   // FIXME: Should we be merging attributes?
11191   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11192     PushNamespaceVisibilityAttr(Attr, Loc);
11193 
11194   if (IsStd)
11195     StdNamespace = Namespc;
11196   if (AddToKnown)
11197     KnownNamespaces[Namespc] = false;
11198 
11199   if (II) {
11200     PushOnScopeChains(Namespc, DeclRegionScope);
11201   } else {
11202     // Link the anonymous namespace into its parent.
11203     DeclContext *Parent = CurContext->getRedeclContext();
11204     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11205       TU->setAnonymousNamespace(Namespc);
11206     } else {
11207       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11208     }
11209 
11210     CurContext->addDecl(Namespc);
11211 
11212     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11213     //   behaves as if it were replaced by
11214     //     namespace unique { /* empty body */ }
11215     //     using namespace unique;
11216     //     namespace unique { namespace-body }
11217     //   where all occurrences of 'unique' in a translation unit are
11218     //   replaced by the same identifier and this identifier differs
11219     //   from all other identifiers in the entire program.
11220 
11221     // We just create the namespace with an empty name and then add an
11222     // implicit using declaration, just like the standard suggests.
11223     //
11224     // CodeGen enforces the "universally unique" aspect by giving all
11225     // declarations semantically contained within an anonymous
11226     // namespace internal linkage.
11227 
11228     if (!PrevNS) {
11229       UD = UsingDirectiveDecl::Create(Context, Parent,
11230                                       /* 'using' */ LBrace,
11231                                       /* 'namespace' */ SourceLocation(),
11232                                       /* qualifier */ NestedNameSpecifierLoc(),
11233                                       /* identifier */ SourceLocation(),
11234                                       Namespc,
11235                                       /* Ancestor */ Parent);
11236       UD->setImplicit();
11237       Parent->addDecl(UD);
11238     }
11239   }
11240 
11241   ActOnDocumentableDecl(Namespc);
11242 
11243   // Although we could have an invalid decl (i.e. the namespace name is a
11244   // redefinition), push it as current DeclContext and try to continue parsing.
11245   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11246   // for the namespace has the declarations that showed up in that particular
11247   // namespace definition.
11248   PushDeclContext(NamespcScope, Namespc);
11249   return Namespc;
11250 }
11251 
11252 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11253 /// is a namespace alias, returns the namespace it points to.
11254 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11255   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11256     return AD->getNamespace();
11257   return dyn_cast_or_null<NamespaceDecl>(D);
11258 }
11259 
11260 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11261 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11262 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11263   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11264   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11265   Namespc->setRBraceLoc(RBrace);
11266   PopDeclContext();
11267   if (Namespc->hasAttr<VisibilityAttr>())
11268     PopPragmaVisibility(true, RBrace);
11269   // If this namespace contains an export-declaration, export it now.
11270   if (DeferredExportedNamespaces.erase(Namespc))
11271     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11272 }
11273 
11274 CXXRecordDecl *Sema::getStdBadAlloc() const {
11275   return cast_or_null<CXXRecordDecl>(
11276                                   StdBadAlloc.get(Context.getExternalSource()));
11277 }
11278 
11279 EnumDecl *Sema::getStdAlignValT() const {
11280   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11281 }
11282 
11283 NamespaceDecl *Sema::getStdNamespace() const {
11284   return cast_or_null<NamespaceDecl>(
11285                                  StdNamespace.get(Context.getExternalSource()));
11286 }
11287 
11288 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11289   if (!StdExperimentalNamespaceCache) {
11290     if (auto Std = getStdNamespace()) {
11291       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11292                           SourceLocation(), LookupNamespaceName);
11293       if (!LookupQualifiedName(Result, Std) ||
11294           !(StdExperimentalNamespaceCache =
11295                 Result.getAsSingle<NamespaceDecl>()))
11296         Result.suppressDiagnostics();
11297     }
11298   }
11299   return StdExperimentalNamespaceCache;
11300 }
11301 
11302 namespace {
11303 
11304 enum UnsupportedSTLSelect {
11305   USS_InvalidMember,
11306   USS_MissingMember,
11307   USS_NonTrivial,
11308   USS_Other
11309 };
11310 
11311 struct InvalidSTLDiagnoser {
11312   Sema &S;
11313   SourceLocation Loc;
11314   QualType TyForDiags;
11315 
11316   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11317                       const VarDecl *VD = nullptr) {
11318     {
11319       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11320                << TyForDiags << ((int)Sel);
11321       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11322         assert(!Name.empty());
11323         D << Name;
11324       }
11325     }
11326     if (Sel == USS_InvalidMember) {
11327       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11328           << VD << VD->getSourceRange();
11329     }
11330     return QualType();
11331   }
11332 };
11333 } // namespace
11334 
11335 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11336                                            SourceLocation Loc,
11337                                            ComparisonCategoryUsage Usage) {
11338   assert(getLangOpts().CPlusPlus &&
11339          "Looking for comparison category type outside of C++.");
11340 
11341   // Use an elaborated type for diagnostics which has a name containing the
11342   // prepended 'std' namespace but not any inline namespace names.
11343   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11344     auto *NNS =
11345         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11346     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11347   };
11348 
11349   // Check if we've already successfully checked the comparison category type
11350   // before. If so, skip checking it again.
11351   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11352   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11353     // The only thing we need to check is that the type has a reachable
11354     // definition in the current context.
11355     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11356       return QualType();
11357 
11358     return Info->getType();
11359   }
11360 
11361   // If lookup failed
11362   if (!Info) {
11363     std::string NameForDiags = "std::";
11364     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11365     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11366         << NameForDiags << (int)Usage;
11367     return QualType();
11368   }
11369 
11370   assert(Info->Kind == Kind);
11371   assert(Info->Record);
11372 
11373   // Update the Record decl in case we encountered a forward declaration on our
11374   // first pass. FIXME: This is a bit of a hack.
11375   if (Info->Record->hasDefinition())
11376     Info->Record = Info->Record->getDefinition();
11377 
11378   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11379     return QualType();
11380 
11381   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11382 
11383   if (!Info->Record->isTriviallyCopyable())
11384     return UnsupportedSTLError(USS_NonTrivial);
11385 
11386   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11387     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11388     // Tolerate empty base classes.
11389     if (Base->isEmpty())
11390       continue;
11391     // Reject STL implementations which have at least one non-empty base.
11392     return UnsupportedSTLError();
11393   }
11394 
11395   // Check that the STL has implemented the types using a single integer field.
11396   // This expectation allows better codegen for builtin operators. We require:
11397   //   (1) The class has exactly one field.
11398   //   (2) The field is an integral or enumeration type.
11399   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11400   if (std::distance(FIt, FEnd) != 1 ||
11401       !FIt->getType()->isIntegralOrEnumerationType()) {
11402     return UnsupportedSTLError();
11403   }
11404 
11405   // Build each of the require values and store them in Info.
11406   for (ComparisonCategoryResult CCR :
11407        ComparisonCategories::getPossibleResultsForType(Kind)) {
11408     StringRef MemName = ComparisonCategories::getResultString(CCR);
11409     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11410 
11411     if (!ValInfo)
11412       return UnsupportedSTLError(USS_MissingMember, MemName);
11413 
11414     VarDecl *VD = ValInfo->VD;
11415     assert(VD && "should not be null!");
11416 
11417     // Attempt to diagnose reasons why the STL definition of this type
11418     // might be foobar, including it failing to be a constant expression.
11419     // TODO Handle more ways the lookup or result can be invalid.
11420     if (!VD->isStaticDataMember() ||
11421         !VD->isUsableInConstantExpressions(Context))
11422       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11423 
11424     // Attempt to evaluate the var decl as a constant expression and extract
11425     // the value of its first field as a ICE. If this fails, the STL
11426     // implementation is not supported.
11427     if (!ValInfo->hasValidIntValue())
11428       return UnsupportedSTLError();
11429 
11430     MarkVariableReferenced(Loc, VD);
11431   }
11432 
11433   // We've successfully built the required types and expressions. Update
11434   // the cache and return the newly cached value.
11435   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11436   return Info->getType();
11437 }
11438 
11439 /// Retrieve the special "std" namespace, which may require us to
11440 /// implicitly define the namespace.
11441 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11442   if (!StdNamespace) {
11443     // The "std" namespace has not yet been defined, so build one implicitly.
11444     StdNamespace = NamespaceDecl::Create(Context,
11445                                          Context.getTranslationUnitDecl(),
11446                                          /*Inline=*/false,
11447                                          SourceLocation(), SourceLocation(),
11448                                          &PP.getIdentifierTable().get("std"),
11449                                          /*PrevDecl=*/nullptr);
11450     getStdNamespace()->setImplicit(true);
11451   }
11452 
11453   return getStdNamespace();
11454 }
11455 
11456 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11457   assert(getLangOpts().CPlusPlus &&
11458          "Looking for std::initializer_list outside of C++.");
11459 
11460   // We're looking for implicit instantiations of
11461   // template <typename E> class std::initializer_list.
11462 
11463   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11464     return false;
11465 
11466   ClassTemplateDecl *Template = nullptr;
11467   const TemplateArgument *Arguments = nullptr;
11468 
11469   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11470 
11471     ClassTemplateSpecializationDecl *Specialization =
11472         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11473     if (!Specialization)
11474       return false;
11475 
11476     Template = Specialization->getSpecializedTemplate();
11477     Arguments = Specialization->getTemplateArgs().data();
11478   } else if (const TemplateSpecializationType *TST =
11479                  Ty->getAs<TemplateSpecializationType>()) {
11480     Template = dyn_cast_or_null<ClassTemplateDecl>(
11481         TST->getTemplateName().getAsTemplateDecl());
11482     Arguments = TST->getArgs();
11483   }
11484   if (!Template)
11485     return false;
11486 
11487   if (!StdInitializerList) {
11488     // Haven't recognized std::initializer_list yet, maybe this is it.
11489     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11490     if (TemplateClass->getIdentifier() !=
11491             &PP.getIdentifierTable().get("initializer_list") ||
11492         !getStdNamespace()->InEnclosingNamespaceSetOf(
11493             TemplateClass->getDeclContext()))
11494       return false;
11495     // This is a template called std::initializer_list, but is it the right
11496     // template?
11497     TemplateParameterList *Params = Template->getTemplateParameters();
11498     if (Params->getMinRequiredArguments() != 1)
11499       return false;
11500     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11501       return false;
11502 
11503     // It's the right template.
11504     StdInitializerList = Template;
11505   }
11506 
11507   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11508     return false;
11509 
11510   // This is an instance of std::initializer_list. Find the argument type.
11511   if (Element)
11512     *Element = Arguments[0].getAsType();
11513   return true;
11514 }
11515 
11516 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11517   NamespaceDecl *Std = S.getStdNamespace();
11518   if (!Std) {
11519     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11520     return nullptr;
11521   }
11522 
11523   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11524                       Loc, Sema::LookupOrdinaryName);
11525   if (!S.LookupQualifiedName(Result, Std)) {
11526     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11527     return nullptr;
11528   }
11529   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11530   if (!Template) {
11531     Result.suppressDiagnostics();
11532     // We found something weird. Complain about the first thing we found.
11533     NamedDecl *Found = *Result.begin();
11534     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11535     return nullptr;
11536   }
11537 
11538   // We found some template called std::initializer_list. Now verify that it's
11539   // correct.
11540   TemplateParameterList *Params = Template->getTemplateParameters();
11541   if (Params->getMinRequiredArguments() != 1 ||
11542       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11543     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11544     return nullptr;
11545   }
11546 
11547   return Template;
11548 }
11549 
11550 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11551   if (!StdInitializerList) {
11552     StdInitializerList = LookupStdInitializerList(*this, Loc);
11553     if (!StdInitializerList)
11554       return QualType();
11555   }
11556 
11557   TemplateArgumentListInfo Args(Loc, Loc);
11558   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11559                                        Context.getTrivialTypeSourceInfo(Element,
11560                                                                         Loc)));
11561   return Context.getCanonicalType(
11562       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11563 }
11564 
11565 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11566   // C++ [dcl.init.list]p2:
11567   //   A constructor is an initializer-list constructor if its first parameter
11568   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11569   //   std::initializer_list<E> for some type E, and either there are no other
11570   //   parameters or else all other parameters have default arguments.
11571   if (!Ctor->hasOneParamOrDefaultArgs())
11572     return false;
11573 
11574   QualType ArgType = Ctor->getParamDecl(0)->getType();
11575   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11576     ArgType = RT->getPointeeType().getUnqualifiedType();
11577 
11578   return isStdInitializerList(ArgType, nullptr);
11579 }
11580 
11581 /// Determine whether a using statement is in a context where it will be
11582 /// apply in all contexts.
11583 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11584   switch (CurContext->getDeclKind()) {
11585     case Decl::TranslationUnit:
11586       return true;
11587     case Decl::LinkageSpec:
11588       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11589     default:
11590       return false;
11591   }
11592 }
11593 
11594 namespace {
11595 
11596 // Callback to only accept typo corrections that are namespaces.
11597 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11598 public:
11599   bool ValidateCandidate(const TypoCorrection &candidate) override {
11600     if (NamedDecl *ND = candidate.getCorrectionDecl())
11601       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11602     return false;
11603   }
11604 
11605   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11606     return std::make_unique<NamespaceValidatorCCC>(*this);
11607   }
11608 };
11609 
11610 }
11611 
11612 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11613                                        CXXScopeSpec &SS,
11614                                        SourceLocation IdentLoc,
11615                                        IdentifierInfo *Ident) {
11616   R.clear();
11617   NamespaceValidatorCCC CCC{};
11618   if (TypoCorrection Corrected =
11619           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11620                         Sema::CTK_ErrorRecovery)) {
11621     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11622       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11623       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11624                               Ident->getName().equals(CorrectedStr);
11625       S.diagnoseTypo(Corrected,
11626                      S.PDiag(diag::err_using_directive_member_suggest)
11627                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11628                      S.PDiag(diag::note_namespace_defined_here));
11629     } else {
11630       S.diagnoseTypo(Corrected,
11631                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11632                      S.PDiag(diag::note_namespace_defined_here));
11633     }
11634     R.addDecl(Corrected.getFoundDecl());
11635     return true;
11636   }
11637   return false;
11638 }
11639 
11640 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11641                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11642                                 SourceLocation IdentLoc,
11643                                 IdentifierInfo *NamespcName,
11644                                 const ParsedAttributesView &AttrList) {
11645   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11646   assert(NamespcName && "Invalid NamespcName.");
11647   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11648 
11649   // This can only happen along a recovery path.
11650   while (S->isTemplateParamScope())
11651     S = S->getParent();
11652   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11653 
11654   UsingDirectiveDecl *UDir = nullptr;
11655   NestedNameSpecifier *Qualifier = nullptr;
11656   if (SS.isSet())
11657     Qualifier = SS.getScopeRep();
11658 
11659   // Lookup namespace name.
11660   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11661   LookupParsedName(R, S, &SS);
11662   if (R.isAmbiguous())
11663     return nullptr;
11664 
11665   if (R.empty()) {
11666     R.clear();
11667     // Allow "using namespace std;" or "using namespace ::std;" even if
11668     // "std" hasn't been defined yet, for GCC compatibility.
11669     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11670         NamespcName->isStr("std")) {
11671       Diag(IdentLoc, diag::ext_using_undefined_std);
11672       R.addDecl(getOrCreateStdNamespace());
11673       R.resolveKind();
11674     }
11675     // Otherwise, attempt typo correction.
11676     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11677   }
11678 
11679   if (!R.empty()) {
11680     NamedDecl *Named = R.getRepresentativeDecl();
11681     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11682     assert(NS && "expected namespace decl");
11683 
11684     // The use of a nested name specifier may trigger deprecation warnings.
11685     DiagnoseUseOfDecl(Named, IdentLoc);
11686 
11687     // C++ [namespace.udir]p1:
11688     //   A using-directive specifies that the names in the nominated
11689     //   namespace can be used in the scope in which the
11690     //   using-directive appears after the using-directive. During
11691     //   unqualified name lookup (3.4.1), the names appear as if they
11692     //   were declared in the nearest enclosing namespace which
11693     //   contains both the using-directive and the nominated
11694     //   namespace. [Note: in this context, "contains" means "contains
11695     //   directly or indirectly". ]
11696 
11697     // Find enclosing context containing both using-directive and
11698     // nominated namespace.
11699     DeclContext *CommonAncestor = NS;
11700     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11701       CommonAncestor = CommonAncestor->getParent();
11702 
11703     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11704                                       SS.getWithLocInContext(Context),
11705                                       IdentLoc, Named, CommonAncestor);
11706 
11707     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11708         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11709       Diag(IdentLoc, diag::warn_using_directive_in_header);
11710     }
11711 
11712     PushUsingDirective(S, UDir);
11713   } else {
11714     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11715   }
11716 
11717   if (UDir)
11718     ProcessDeclAttributeList(S, UDir, AttrList);
11719 
11720   return UDir;
11721 }
11722 
11723 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11724   // If the scope has an associated entity and the using directive is at
11725   // namespace or translation unit scope, add the UsingDirectiveDecl into
11726   // its lookup structure so qualified name lookup can find it.
11727   DeclContext *Ctx = S->getEntity();
11728   if (Ctx && !Ctx->isFunctionOrMethod())
11729     Ctx->addDecl(UDir);
11730   else
11731     // Otherwise, it is at block scope. The using-directives will affect lookup
11732     // only to the end of the scope.
11733     S->PushUsingDirective(UDir);
11734 }
11735 
11736 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11737                                   SourceLocation UsingLoc,
11738                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11739                                   UnqualifiedId &Name,
11740                                   SourceLocation EllipsisLoc,
11741                                   const ParsedAttributesView &AttrList) {
11742   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11743 
11744   if (SS.isEmpty()) {
11745     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11746     return nullptr;
11747   }
11748 
11749   switch (Name.getKind()) {
11750   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11751   case UnqualifiedIdKind::IK_Identifier:
11752   case UnqualifiedIdKind::IK_OperatorFunctionId:
11753   case UnqualifiedIdKind::IK_LiteralOperatorId:
11754   case UnqualifiedIdKind::IK_ConversionFunctionId:
11755     break;
11756 
11757   case UnqualifiedIdKind::IK_ConstructorName:
11758   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11759     // C++11 inheriting constructors.
11760     Diag(Name.getBeginLoc(),
11761          getLangOpts().CPlusPlus11
11762              ? diag::warn_cxx98_compat_using_decl_constructor
11763              : diag::err_using_decl_constructor)
11764         << SS.getRange();
11765 
11766     if (getLangOpts().CPlusPlus11) break;
11767 
11768     return nullptr;
11769 
11770   case UnqualifiedIdKind::IK_DestructorName:
11771     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11772     return nullptr;
11773 
11774   case UnqualifiedIdKind::IK_TemplateId:
11775     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11776         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11777     return nullptr;
11778 
11779   case UnqualifiedIdKind::IK_DeductionGuideName:
11780     llvm_unreachable("cannot parse qualified deduction guide name");
11781   }
11782 
11783   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11784   DeclarationName TargetName = TargetNameInfo.getName();
11785   if (!TargetName)
11786     return nullptr;
11787 
11788   // Warn about access declarations.
11789   if (UsingLoc.isInvalid()) {
11790     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11791                                  ? diag::err_access_decl
11792                                  : diag::warn_access_decl_deprecated)
11793         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11794   }
11795 
11796   if (EllipsisLoc.isInvalid()) {
11797     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11798         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11799       return nullptr;
11800   } else {
11801     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11802         !TargetNameInfo.containsUnexpandedParameterPack()) {
11803       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11804         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11805       EllipsisLoc = SourceLocation();
11806     }
11807   }
11808 
11809   NamedDecl *UD =
11810       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11811                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11812                             /*IsInstantiation*/ false,
11813                             AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11814   if (UD)
11815     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11816 
11817   return UD;
11818 }
11819 
11820 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
11821                                       SourceLocation UsingLoc,
11822                                       SourceLocation EnumLoc,
11823                                       const DeclSpec &DS) {
11824   switch (DS.getTypeSpecType()) {
11825   case DeclSpec::TST_error:
11826     // This will already have been diagnosed
11827     return nullptr;
11828 
11829   case DeclSpec::TST_enum:
11830     break;
11831 
11832   case DeclSpec::TST_typename:
11833     Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
11834     return nullptr;
11835 
11836   default:
11837     llvm_unreachable("unexpected DeclSpec type");
11838   }
11839 
11840   // As with enum-decls, we ignore attributes for now.
11841   auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
11842   if (auto *Def = Enum->getDefinition())
11843     Enum = Def;
11844 
11845   auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
11846                                        DS.getTypeSpecTypeNameLoc(), Enum);
11847   if (UD)
11848     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11849 
11850   return UD;
11851 }
11852 
11853 /// Determine whether a using declaration considers the given
11854 /// declarations as "equivalent", e.g., if they are redeclarations of
11855 /// the same entity or are both typedefs of the same type.
11856 static bool
11857 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11858   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11859     return true;
11860 
11861   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11862     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11863       return Context.hasSameType(TD1->getUnderlyingType(),
11864                                  TD2->getUnderlyingType());
11865 
11866   // Two using_if_exists using-declarations are equivalent if both are
11867   // unresolved.
11868   if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11869       isa<UnresolvedUsingIfExistsDecl>(D2))
11870     return true;
11871 
11872   return false;
11873 }
11874 
11875 
11876 /// Determines whether to create a using shadow decl for a particular
11877 /// decl, given the set of decls existing prior to this using lookup.
11878 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
11879                                 const LookupResult &Previous,
11880                                 UsingShadowDecl *&PrevShadow) {
11881   // Diagnose finding a decl which is not from a base class of the
11882   // current class.  We do this now because there are cases where this
11883   // function will silently decide not to build a shadow decl, which
11884   // will pre-empt further diagnostics.
11885   //
11886   // We don't need to do this in C++11 because we do the check once on
11887   // the qualifier.
11888   //
11889   // FIXME: diagnose the following if we care enough:
11890   //   struct A { int foo; };
11891   //   struct B : A { using A::foo; };
11892   //   template <class T> struct C : A {};
11893   //   template <class T> struct D : C<T> { using B::foo; } // <---
11894   // This is invalid (during instantiation) in C++03 because B::foo
11895   // resolves to the using decl in B, which is not a base class of D<T>.
11896   // We can't diagnose it immediately because C<T> is an unknown
11897   // specialization. The UsingShadowDecl in D<T> then points directly
11898   // to A::foo, which will look well-formed when we instantiate.
11899   // The right solution is to not collapse the shadow-decl chain.
11900   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
11901     if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
11902       DeclContext *OrigDC = Orig->getDeclContext();
11903 
11904       // Handle enums and anonymous structs.
11905       if (isa<EnumDecl>(OrigDC))
11906         OrigDC = OrigDC->getParent();
11907       CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11908       while (OrigRec->isAnonymousStructOrUnion())
11909         OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11910 
11911       if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11912         if (OrigDC == CurContext) {
11913           Diag(Using->getLocation(),
11914                diag::err_using_decl_nested_name_specifier_is_current_class)
11915               << Using->getQualifierLoc().getSourceRange();
11916           Diag(Orig->getLocation(), diag::note_using_decl_target);
11917           Using->setInvalidDecl();
11918           return true;
11919         }
11920 
11921         Diag(Using->getQualifierLoc().getBeginLoc(),
11922              diag::err_using_decl_nested_name_specifier_is_not_base_class)
11923             << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
11924             << Using->getQualifierLoc().getSourceRange();
11925         Diag(Orig->getLocation(), diag::note_using_decl_target);
11926         Using->setInvalidDecl();
11927         return true;
11928       }
11929     }
11930 
11931   if (Previous.empty()) return false;
11932 
11933   NamedDecl *Target = Orig;
11934   if (isa<UsingShadowDecl>(Target))
11935     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11936 
11937   // If the target happens to be one of the previous declarations, we
11938   // don't have a conflict.
11939   //
11940   // FIXME: but we might be increasing its access, in which case we
11941   // should redeclare it.
11942   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11943   bool FoundEquivalentDecl = false;
11944   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11945          I != E; ++I) {
11946     NamedDecl *D = (*I)->getUnderlyingDecl();
11947     // We can have UsingDecls in our Previous results because we use the same
11948     // LookupResult for checking whether the UsingDecl itself is a valid
11949     // redeclaration.
11950     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
11951       continue;
11952 
11953     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11954       // C++ [class.mem]p19:
11955       //   If T is the name of a class, then [every named member other than
11956       //   a non-static data member] shall have a name different from T
11957       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11958           !isa<IndirectFieldDecl>(Target) &&
11959           !isa<UnresolvedUsingValueDecl>(Target) &&
11960           DiagnoseClassNameShadow(
11961               CurContext,
11962               DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
11963         return true;
11964     }
11965 
11966     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11967       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11968         PrevShadow = Shadow;
11969       FoundEquivalentDecl = true;
11970     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11971       // We don't conflict with an existing using shadow decl of an equivalent
11972       // declaration, but we're not a redeclaration of it.
11973       FoundEquivalentDecl = true;
11974     }
11975 
11976     if (isVisible(D))
11977       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11978   }
11979 
11980   if (FoundEquivalentDecl)
11981     return false;
11982 
11983   // Always emit a diagnostic for a mismatch between an unresolved
11984   // using_if_exists and a resolved using declaration in either direction.
11985   if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
11986       (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
11987     if (!NonTag && !Tag)
11988       return false;
11989     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11990     Diag(Target->getLocation(), diag::note_using_decl_target);
11991     Diag((NonTag ? NonTag : Tag)->getLocation(),
11992          diag::note_using_decl_conflict);
11993     BUD->setInvalidDecl();
11994     return true;
11995   }
11996 
11997   if (FunctionDecl *FD = Target->getAsFunction()) {
11998     NamedDecl *OldDecl = nullptr;
11999     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
12000                           /*IsForUsingDecl*/ true)) {
12001     case Ovl_Overload:
12002       return false;
12003 
12004     case Ovl_NonFunction:
12005       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12006       break;
12007 
12008     // We found a decl with the exact signature.
12009     case Ovl_Match:
12010       // If we're in a record, we want to hide the target, so we
12011       // return true (without a diagnostic) to tell the caller not to
12012       // build a shadow decl.
12013       if (CurContext->isRecord())
12014         return true;
12015 
12016       // If we're not in a record, this is an error.
12017       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12018       break;
12019     }
12020 
12021     Diag(Target->getLocation(), diag::note_using_decl_target);
12022     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
12023     BUD->setInvalidDecl();
12024     return true;
12025   }
12026 
12027   // Target is not a function.
12028 
12029   if (isa<TagDecl>(Target)) {
12030     // No conflict between a tag and a non-tag.
12031     if (!Tag) return false;
12032 
12033     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12034     Diag(Target->getLocation(), diag::note_using_decl_target);
12035     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
12036     BUD->setInvalidDecl();
12037     return true;
12038   }
12039 
12040   // No conflict between a tag and a non-tag.
12041   if (!NonTag) return false;
12042 
12043   Diag(BUD->getLocation(), diag::err_using_decl_conflict);
12044   Diag(Target->getLocation(), diag::note_using_decl_target);
12045   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
12046   BUD->setInvalidDecl();
12047   return true;
12048 }
12049 
12050 /// Determine whether a direct base class is a virtual base class.
12051 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
12052   if (!Derived->getNumVBases())
12053     return false;
12054   for (auto &B : Derived->bases())
12055     if (B.getType()->getAsCXXRecordDecl() == Base)
12056       return B.isVirtual();
12057   llvm_unreachable("not a direct base class");
12058 }
12059 
12060 /// Builds a shadow declaration corresponding to a 'using' declaration.
12061 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
12062                                             NamedDecl *Orig,
12063                                             UsingShadowDecl *PrevDecl) {
12064   // If we resolved to another shadow declaration, just coalesce them.
12065   NamedDecl *Target = Orig;
12066   if (isa<UsingShadowDecl>(Target)) {
12067     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12068     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12069   }
12070 
12071   NamedDecl *NonTemplateTarget = Target;
12072   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12073     NonTemplateTarget = TargetTD->getTemplatedDecl();
12074 
12075   UsingShadowDecl *Shadow;
12076   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12077     UsingDecl *Using = cast<UsingDecl>(BUD);
12078     bool IsVirtualBase =
12079         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12080                             Using->getQualifier()->getAsRecordDecl());
12081     Shadow = ConstructorUsingShadowDecl::Create(
12082         Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12083   } else {
12084     Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12085                                      Target->getDeclName(), BUD, Target);
12086   }
12087   BUD->addShadowDecl(Shadow);
12088 
12089   Shadow->setAccess(BUD->getAccess());
12090   if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12091     Shadow->setInvalidDecl();
12092 
12093   Shadow->setPreviousDecl(PrevDecl);
12094 
12095   if (S)
12096     PushOnScopeChains(Shadow, S);
12097   else
12098     CurContext->addDecl(Shadow);
12099 
12100 
12101   return Shadow;
12102 }
12103 
12104 /// Hides a using shadow declaration.  This is required by the current
12105 /// using-decl implementation when a resolvable using declaration in a
12106 /// class is followed by a declaration which would hide or override
12107 /// one or more of the using decl's targets; for example:
12108 ///
12109 ///   struct Base { void foo(int); };
12110 ///   struct Derived : Base {
12111 ///     using Base::foo;
12112 ///     void foo(int);
12113 ///   };
12114 ///
12115 /// The governing language is C++03 [namespace.udecl]p12:
12116 ///
12117 ///   When a using-declaration brings names from a base class into a
12118 ///   derived class scope, member functions in the derived class
12119 ///   override and/or hide member functions with the same name and
12120 ///   parameter types in a base class (rather than conflicting).
12121 ///
12122 /// There are two ways to implement this:
12123 ///   (1) optimistically create shadow decls when they're not hidden
12124 ///       by existing declarations, or
12125 ///   (2) don't create any shadow decls (or at least don't make them
12126 ///       visible) until we've fully parsed/instantiated the class.
12127 /// The problem with (1) is that we might have to retroactively remove
12128 /// a shadow decl, which requires several O(n) operations because the
12129 /// decl structures are (very reasonably) not designed for removal.
12130 /// (2) avoids this but is very fiddly and phase-dependent.
12131 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12132   if (Shadow->getDeclName().getNameKind() ==
12133         DeclarationName::CXXConversionFunctionName)
12134     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12135 
12136   // Remove it from the DeclContext...
12137   Shadow->getDeclContext()->removeDecl(Shadow);
12138 
12139   // ...and the scope, if applicable...
12140   if (S) {
12141     S->RemoveDecl(Shadow);
12142     IdResolver.RemoveDecl(Shadow);
12143   }
12144 
12145   // ...and the using decl.
12146   Shadow->getIntroducer()->removeShadowDecl(Shadow);
12147 
12148   // TODO: complain somehow if Shadow was used.  It shouldn't
12149   // be possible for this to happen, because...?
12150 }
12151 
12152 /// Find the base specifier for a base class with the given type.
12153 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12154                                                 QualType DesiredBase,
12155                                                 bool &AnyDependentBases) {
12156   // Check whether the named type is a direct base class.
12157   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12158     .getUnqualifiedType();
12159   for (auto &Base : Derived->bases()) {
12160     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12161     if (CanonicalDesiredBase == BaseType)
12162       return &Base;
12163     if (BaseType->isDependentType())
12164       AnyDependentBases = true;
12165   }
12166   return nullptr;
12167 }
12168 
12169 namespace {
12170 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12171 public:
12172   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12173                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12174       : HasTypenameKeyword(HasTypenameKeyword),
12175         IsInstantiation(IsInstantiation), OldNNS(NNS),
12176         RequireMemberOf(RequireMemberOf) {}
12177 
12178   bool ValidateCandidate(const TypoCorrection &Candidate) override {
12179     NamedDecl *ND = Candidate.getCorrectionDecl();
12180 
12181     // Keywords are not valid here.
12182     if (!ND || isa<NamespaceDecl>(ND))
12183       return false;
12184 
12185     // Completely unqualified names are invalid for a 'using' declaration.
12186     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12187       return false;
12188 
12189     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12190     // reject.
12191 
12192     if (RequireMemberOf) {
12193       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12194       if (FoundRecord && FoundRecord->isInjectedClassName()) {
12195         // No-one ever wants a using-declaration to name an injected-class-name
12196         // of a base class, unless they're declaring an inheriting constructor.
12197         ASTContext &Ctx = ND->getASTContext();
12198         if (!Ctx.getLangOpts().CPlusPlus11)
12199           return false;
12200         QualType FoundType = Ctx.getRecordType(FoundRecord);
12201 
12202         // Check that the injected-class-name is named as a member of its own
12203         // type; we don't want to suggest 'using Derived::Base;', since that
12204         // means something else.
12205         NestedNameSpecifier *Specifier =
12206             Candidate.WillReplaceSpecifier()
12207                 ? Candidate.getCorrectionSpecifier()
12208                 : OldNNS;
12209         if (!Specifier->getAsType() ||
12210             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12211           return false;
12212 
12213         // Check that this inheriting constructor declaration actually names a
12214         // direct base class of the current class.
12215         bool AnyDependentBases = false;
12216         if (!findDirectBaseWithType(RequireMemberOf,
12217                                     Ctx.getRecordType(FoundRecord),
12218                                     AnyDependentBases) &&
12219             !AnyDependentBases)
12220           return false;
12221       } else {
12222         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12223         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12224           return false;
12225 
12226         // FIXME: Check that the base class member is accessible?
12227       }
12228     } else {
12229       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12230       if (FoundRecord && FoundRecord->isInjectedClassName())
12231         return false;
12232     }
12233 
12234     if (isa<TypeDecl>(ND))
12235       return HasTypenameKeyword || !IsInstantiation;
12236 
12237     return !HasTypenameKeyword;
12238   }
12239 
12240   std::unique_ptr<CorrectionCandidateCallback> clone() override {
12241     return std::make_unique<UsingValidatorCCC>(*this);
12242   }
12243 
12244 private:
12245   bool HasTypenameKeyword;
12246   bool IsInstantiation;
12247   NestedNameSpecifier *OldNNS;
12248   CXXRecordDecl *RequireMemberOf;
12249 };
12250 } // end anonymous namespace
12251 
12252 /// Remove decls we can't actually see from a lookup being used to declare
12253 /// shadow using decls.
12254 ///
12255 /// \param S - The scope of the potential shadow decl
12256 /// \param Previous - The lookup of a potential shadow decl's name.
12257 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12258   // It is really dumb that we have to do this.
12259   LookupResult::Filter F = Previous.makeFilter();
12260   while (F.hasNext()) {
12261     NamedDecl *D = F.next();
12262     if (!isDeclInScope(D, CurContext, S))
12263       F.erase();
12264     // If we found a local extern declaration that's not ordinarily visible,
12265     // and this declaration is being added to a non-block scope, ignore it.
12266     // We're only checking for scope conflicts here, not also for violations
12267     // of the linkage rules.
12268     else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12269              !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12270       F.erase();
12271   }
12272   F.done();
12273 }
12274 
12275 /// Builds a using declaration.
12276 ///
12277 /// \param IsInstantiation - Whether this call arises from an
12278 ///   instantiation of an unresolved using declaration.  We treat
12279 ///   the lookup differently for these declarations.
12280 NamedDecl *Sema::BuildUsingDeclaration(
12281     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12282     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12283     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12284     const ParsedAttributesView &AttrList, bool IsInstantiation,
12285     bool IsUsingIfExists) {
12286   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12287   SourceLocation IdentLoc = NameInfo.getLoc();
12288   assert(IdentLoc.isValid() && "Invalid TargetName location.");
12289 
12290   // FIXME: We ignore attributes for now.
12291 
12292   // For an inheriting constructor declaration, the name of the using
12293   // declaration is the name of a constructor in this class, not in the
12294   // base class.
12295   DeclarationNameInfo UsingName = NameInfo;
12296   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12297     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12298       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12299           Context.getCanonicalType(Context.getRecordType(RD))));
12300 
12301   // Do the redeclaration lookup in the current scope.
12302   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12303                         ForVisibleRedeclaration);
12304   Previous.setHideTags(false);
12305   if (S) {
12306     LookupName(Previous, S);
12307 
12308     FilterUsingLookup(S, Previous);
12309   } else {
12310     assert(IsInstantiation && "no scope in non-instantiation");
12311     if (CurContext->isRecord())
12312       LookupQualifiedName(Previous, CurContext);
12313     else {
12314       // No redeclaration check is needed here; in non-member contexts we
12315       // diagnosed all possible conflicts with other using-declarations when
12316       // building the template:
12317       //
12318       // For a dependent non-type using declaration, the only valid case is
12319       // if we instantiate to a single enumerator. We check for conflicts
12320       // between shadow declarations we introduce, and we check in the template
12321       // definition for conflicts between a non-type using declaration and any
12322       // other declaration, which together covers all cases.
12323       //
12324       // A dependent typename using declaration will never successfully
12325       // instantiate, since it will always name a class member, so we reject
12326       // that in the template definition.
12327     }
12328   }
12329 
12330   // Check for invalid redeclarations.
12331   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12332                                   SS, IdentLoc, Previous))
12333     return nullptr;
12334 
12335   // 'using_if_exists' doesn't make sense on an inherited constructor.
12336   if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12337                              DeclarationName::CXXConstructorName) {
12338     Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12339     return nullptr;
12340   }
12341 
12342   DeclContext *LookupContext = computeDeclContext(SS);
12343   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12344   if (!LookupContext || EllipsisLoc.isValid()) {
12345     NamedDecl *D;
12346     // Dependent scope, or an unexpanded pack
12347     if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12348                                                   SS, NameInfo, IdentLoc))
12349       return nullptr;
12350 
12351     if (HasTypenameKeyword) {
12352       // FIXME: not all declaration name kinds are legal here
12353       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12354                                               UsingLoc, TypenameLoc,
12355                                               QualifierLoc,
12356                                               IdentLoc, NameInfo.getName(),
12357                                               EllipsisLoc);
12358     } else {
12359       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12360                                            QualifierLoc, NameInfo, EllipsisLoc);
12361     }
12362     D->setAccess(AS);
12363     CurContext->addDecl(D);
12364     ProcessDeclAttributeList(S, D, AttrList);
12365     return D;
12366   }
12367 
12368   auto Build = [&](bool Invalid) {
12369     UsingDecl *UD =
12370         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12371                           UsingName, HasTypenameKeyword);
12372     UD->setAccess(AS);
12373     CurContext->addDecl(UD);
12374     ProcessDeclAttributeList(S, UD, AttrList);
12375     UD->setInvalidDecl(Invalid);
12376     return UD;
12377   };
12378   auto BuildInvalid = [&]{ return Build(true); };
12379   auto BuildValid = [&]{ return Build(false); };
12380 
12381   if (RequireCompleteDeclContext(SS, LookupContext))
12382     return BuildInvalid();
12383 
12384   // Look up the target name.
12385   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12386 
12387   // Unlike most lookups, we don't always want to hide tag
12388   // declarations: tag names are visible through the using declaration
12389   // even if hidden by ordinary names, *except* in a dependent context
12390   // where they may be used by two-phase lookup.
12391   if (!IsInstantiation)
12392     R.setHideTags(false);
12393 
12394   // For the purposes of this lookup, we have a base object type
12395   // equal to that of the current context.
12396   if (CurContext->isRecord()) {
12397     R.setBaseObjectType(
12398                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12399   }
12400 
12401   LookupQualifiedName(R, LookupContext);
12402 
12403   // Validate the context, now we have a lookup
12404   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12405                               IdentLoc, &R))
12406     return nullptr;
12407 
12408   if (R.empty() && IsUsingIfExists)
12409     R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12410                                                   UsingName.getName()),
12411               AS_public);
12412 
12413   // Try to correct typos if possible. If constructor name lookup finds no
12414   // results, that means the named class has no explicit constructors, and we
12415   // suppressed declaring implicit ones (probably because it's dependent or
12416   // invalid).
12417   if (R.empty() &&
12418       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12419     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12420     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12421     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12422     auto *II = NameInfo.getName().getAsIdentifierInfo();
12423     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12424         CurContext->isStdNamespace() &&
12425         isa<TranslationUnitDecl>(LookupContext) &&
12426         getSourceManager().isInSystemHeader(UsingLoc))
12427       return nullptr;
12428     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12429                           dyn_cast<CXXRecordDecl>(CurContext));
12430     if (TypoCorrection Corrected =
12431             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12432                         CTK_ErrorRecovery)) {
12433       // We reject candidates where DroppedSpecifier == true, hence the
12434       // literal '0' below.
12435       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12436                                 << NameInfo.getName() << LookupContext << 0
12437                                 << SS.getRange());
12438 
12439       // If we picked a correction with no attached Decl we can't do anything
12440       // useful with it, bail out.
12441       NamedDecl *ND = Corrected.getCorrectionDecl();
12442       if (!ND)
12443         return BuildInvalid();
12444 
12445       // If we corrected to an inheriting constructor, handle it as one.
12446       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12447       if (RD && RD->isInjectedClassName()) {
12448         // The parent of the injected class name is the class itself.
12449         RD = cast<CXXRecordDecl>(RD->getParent());
12450 
12451         // Fix up the information we'll use to build the using declaration.
12452         if (Corrected.WillReplaceSpecifier()) {
12453           NestedNameSpecifierLocBuilder Builder;
12454           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12455                               QualifierLoc.getSourceRange());
12456           QualifierLoc = Builder.getWithLocInContext(Context);
12457         }
12458 
12459         // In this case, the name we introduce is the name of a derived class
12460         // constructor.
12461         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12462         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12463             Context.getCanonicalType(Context.getRecordType(CurClass))));
12464         UsingName.setNamedTypeInfo(nullptr);
12465         for (auto *Ctor : LookupConstructors(RD))
12466           R.addDecl(Ctor);
12467         R.resolveKind();
12468       } else {
12469         // FIXME: Pick up all the declarations if we found an overloaded
12470         // function.
12471         UsingName.setName(ND->getDeclName());
12472         R.addDecl(ND);
12473       }
12474     } else {
12475       Diag(IdentLoc, diag::err_no_member)
12476         << NameInfo.getName() << LookupContext << SS.getRange();
12477       return BuildInvalid();
12478     }
12479   }
12480 
12481   if (R.isAmbiguous())
12482     return BuildInvalid();
12483 
12484   if (HasTypenameKeyword) {
12485     // If we asked for a typename and got a non-type decl, error out.
12486     if (!R.getAsSingle<TypeDecl>() &&
12487         !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12488       Diag(IdentLoc, diag::err_using_typename_non_type);
12489       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12490         Diag((*I)->getUnderlyingDecl()->getLocation(),
12491              diag::note_using_decl_target);
12492       return BuildInvalid();
12493     }
12494   } else {
12495     // If we asked for a non-typename and we got a type, error out,
12496     // but only if this is an instantiation of an unresolved using
12497     // decl.  Otherwise just silently find the type name.
12498     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12499       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12500       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12501       return BuildInvalid();
12502     }
12503   }
12504 
12505   // C++14 [namespace.udecl]p6:
12506   // A using-declaration shall not name a namespace.
12507   if (R.getAsSingle<NamespaceDecl>()) {
12508     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12509       << SS.getRange();
12510     return BuildInvalid();
12511   }
12512 
12513   UsingDecl *UD = BuildValid();
12514 
12515   // Some additional rules apply to inheriting constructors.
12516   if (UsingName.getName().getNameKind() ==
12517         DeclarationName::CXXConstructorName) {
12518     // Suppress access diagnostics; the access check is instead performed at the
12519     // point of use for an inheriting constructor.
12520     R.suppressDiagnostics();
12521     if (CheckInheritingConstructorUsingDecl(UD))
12522       return UD;
12523   }
12524 
12525   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12526     UsingShadowDecl *PrevDecl = nullptr;
12527     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12528       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12529   }
12530 
12531   return UD;
12532 }
12533 
12534 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12535                                            SourceLocation UsingLoc,
12536                                            SourceLocation EnumLoc,
12537                                            SourceLocation NameLoc,
12538                                            EnumDecl *ED) {
12539   bool Invalid = false;
12540 
12541   if (CurContext->getRedeclContext()->isRecord()) {
12542     /// In class scope, check if this is a duplicate, for better a diagnostic.
12543     DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12544     LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12545                           ForVisibleRedeclaration);
12546 
12547     LookupName(Previous, S);
12548 
12549     for (NamedDecl *D : Previous)
12550       if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12551         if (UED->getEnumDecl() == ED) {
12552           Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12553               << SourceRange(EnumLoc, NameLoc);
12554           Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12555           Invalid = true;
12556           break;
12557         }
12558   }
12559 
12560   if (RequireCompleteEnumDecl(ED, NameLoc))
12561     Invalid = true;
12562 
12563   UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12564                                             EnumLoc, NameLoc, ED);
12565   UD->setAccess(AS);
12566   CurContext->addDecl(UD);
12567 
12568   if (Invalid) {
12569     UD->setInvalidDecl();
12570     return UD;
12571   }
12572 
12573   // Create the shadow decls for each enumerator
12574   for (EnumConstantDecl *EC : ED->enumerators()) {
12575     UsingShadowDecl *PrevDecl = nullptr;
12576     DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12577     LookupResult Previous(*this, DNI, LookupOrdinaryName,
12578                           ForVisibleRedeclaration);
12579     LookupName(Previous, S);
12580     FilterUsingLookup(S, Previous);
12581 
12582     if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12583       BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12584   }
12585 
12586   return UD;
12587 }
12588 
12589 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12590                                     ArrayRef<NamedDecl *> Expansions) {
12591   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12592          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12593          isa<UsingPackDecl>(InstantiatedFrom));
12594 
12595   auto *UPD =
12596       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12597   UPD->setAccess(InstantiatedFrom->getAccess());
12598   CurContext->addDecl(UPD);
12599   return UPD;
12600 }
12601 
12602 /// Additional checks for a using declaration referring to a constructor name.
12603 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12604   assert(!UD->hasTypename() && "expecting a constructor name");
12605 
12606   const Type *SourceType = UD->getQualifier()->getAsType();
12607   assert(SourceType &&
12608          "Using decl naming constructor doesn't have type in scope spec.");
12609   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12610 
12611   // Check whether the named type is a direct base class.
12612   bool AnyDependentBases = false;
12613   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12614                                       AnyDependentBases);
12615   if (!Base && !AnyDependentBases) {
12616     Diag(UD->getUsingLoc(),
12617          diag::err_using_decl_constructor_not_in_direct_base)
12618       << UD->getNameInfo().getSourceRange()
12619       << QualType(SourceType, 0) << TargetClass;
12620     UD->setInvalidDecl();
12621     return true;
12622   }
12623 
12624   if (Base)
12625     Base->setInheritConstructors();
12626 
12627   return false;
12628 }
12629 
12630 /// Checks that the given using declaration is not an invalid
12631 /// redeclaration.  Note that this is checking only for the using decl
12632 /// itself, not for any ill-formedness among the UsingShadowDecls.
12633 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12634                                        bool HasTypenameKeyword,
12635                                        const CXXScopeSpec &SS,
12636                                        SourceLocation NameLoc,
12637                                        const LookupResult &Prev) {
12638   NestedNameSpecifier *Qual = SS.getScopeRep();
12639 
12640   // C++03 [namespace.udecl]p8:
12641   // C++0x [namespace.udecl]p10:
12642   //   A using-declaration is a declaration and can therefore be used
12643   //   repeatedly where (and only where) multiple declarations are
12644   //   allowed.
12645   //
12646   // That's in non-member contexts.
12647   if (!CurContext->getRedeclContext()->isRecord()) {
12648     // A dependent qualifier outside a class can only ever resolve to an
12649     // enumeration type. Therefore it conflicts with any other non-type
12650     // declaration in the same scope.
12651     // FIXME: How should we check for dependent type-type conflicts at block
12652     // scope?
12653     if (Qual->isDependent() && !HasTypenameKeyword) {
12654       for (auto *D : Prev) {
12655         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12656           bool OldCouldBeEnumerator =
12657               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12658           Diag(NameLoc,
12659                OldCouldBeEnumerator ? diag::err_redefinition
12660                                     : diag::err_redefinition_different_kind)
12661               << Prev.getLookupName();
12662           Diag(D->getLocation(), diag::note_previous_definition);
12663           return true;
12664         }
12665       }
12666     }
12667     return false;
12668   }
12669 
12670   const NestedNameSpecifier *CNNS =
12671       Context.getCanonicalNestedNameSpecifier(Qual);
12672   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12673     NamedDecl *D = *I;
12674 
12675     bool DTypename;
12676     NestedNameSpecifier *DQual;
12677     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12678       DTypename = UD->hasTypename();
12679       DQual = UD->getQualifier();
12680     } else if (UnresolvedUsingValueDecl *UD
12681                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12682       DTypename = false;
12683       DQual = UD->getQualifier();
12684     } else if (UnresolvedUsingTypenameDecl *UD
12685                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12686       DTypename = true;
12687       DQual = UD->getQualifier();
12688     } else continue;
12689 
12690     // using decls differ if one says 'typename' and the other doesn't.
12691     // FIXME: non-dependent using decls?
12692     if (HasTypenameKeyword != DTypename) continue;
12693 
12694     // using decls differ if they name different scopes (but note that
12695     // template instantiation can cause this check to trigger when it
12696     // didn't before instantiation).
12697     if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12698       continue;
12699 
12700     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12701     Diag(D->getLocation(), diag::note_using_decl) << 1;
12702     return true;
12703   }
12704 
12705   return false;
12706 }
12707 
12708 /// Checks that the given nested-name qualifier used in a using decl
12709 /// in the current context is appropriately related to the current
12710 /// scope.  If an error is found, diagnoses it and returns true.
12711 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12712 /// result of that lookup. UD is likewise nullptr, except when we have an
12713 /// already-populated UsingDecl whose shadow decls contain the same information
12714 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12715 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12716                                    const CXXScopeSpec &SS,
12717                                    const DeclarationNameInfo &NameInfo,
12718                                    SourceLocation NameLoc,
12719                                    const LookupResult *R, const UsingDecl *UD) {
12720   DeclContext *NamedContext = computeDeclContext(SS);
12721   assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
12722          "resolvable context must have exactly one set of decls");
12723 
12724   // C++ 20 permits using an enumerator that does not have a class-hierarchy
12725   // relationship.
12726   bool Cxx20Enumerator = false;
12727   if (NamedContext) {
12728     EnumConstantDecl *EC = nullptr;
12729     if (R)
12730       EC = R->getAsSingle<EnumConstantDecl>();
12731     else if (UD && UD->shadow_size() == 1)
12732       EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12733     if (EC)
12734       Cxx20Enumerator = getLangOpts().CPlusPlus20;
12735 
12736     if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12737       // C++14 [namespace.udecl]p7:
12738       // A using-declaration shall not name a scoped enumerator.
12739       // C++20 p1099 permits enumerators.
12740       if (EC && R && ED->isScoped())
12741         Diag(SS.getBeginLoc(),
12742              getLangOpts().CPlusPlus20
12743                  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12744                  : diag::ext_using_decl_scoped_enumerator)
12745             << SS.getRange();
12746 
12747       // We want to consider the scope of the enumerator
12748       NamedContext = ED->getDeclContext();
12749     }
12750   }
12751 
12752   if (!CurContext->isRecord()) {
12753     // C++03 [namespace.udecl]p3:
12754     // C++0x [namespace.udecl]p8:
12755     //   A using-declaration for a class member shall be a member-declaration.
12756     // C++20 [namespace.udecl]p7
12757     //   ... other than an enumerator ...
12758 
12759     // If we weren't able to compute a valid scope, it might validly be a
12760     // dependent class or enumeration scope. If we have a 'typename' keyword,
12761     // the scope must resolve to a class type.
12762     if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12763                      : !HasTypename)
12764       return false; // OK
12765 
12766     Diag(NameLoc,
12767          Cxx20Enumerator
12768              ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12769              : diag::err_using_decl_can_not_refer_to_class_member)
12770         << SS.getRange();
12771 
12772     if (Cxx20Enumerator)
12773       return false; // OK
12774 
12775     auto *RD = NamedContext
12776                    ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12777                    : nullptr;
12778     if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12779       // See if there's a helpful fixit
12780 
12781       if (!R) {
12782         // We will have already diagnosed the problem on the template
12783         // definition,  Maybe we should do so again?
12784       } else if (R->getAsSingle<TypeDecl>()) {
12785         if (getLangOpts().CPlusPlus11) {
12786           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12787           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12788             << 0 // alias declaration
12789             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12790                                           NameInfo.getName().getAsString() +
12791                                               " = ");
12792         } else {
12793           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12794           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12795           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12796             << 1 // typedef declaration
12797             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12798             << FixItHint::CreateInsertion(
12799                    InsertLoc, " " + NameInfo.getName().getAsString());
12800         }
12801       } else if (R->getAsSingle<VarDecl>()) {
12802         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12803         // repeating the type of the static data member here.
12804         FixItHint FixIt;
12805         if (getLangOpts().CPlusPlus11) {
12806           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12807           FixIt = FixItHint::CreateReplacement(
12808               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12809         }
12810 
12811         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12812           << 2 // reference declaration
12813           << FixIt;
12814       } else if (R->getAsSingle<EnumConstantDecl>()) {
12815         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12816         // repeating the type of the enumeration here, and we can't do so if
12817         // the type is anonymous.
12818         FixItHint FixIt;
12819         if (getLangOpts().CPlusPlus11) {
12820           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12821           FixIt = FixItHint::CreateReplacement(
12822               UsingLoc,
12823               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12824         }
12825 
12826         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12827           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12828           << FixIt;
12829       }
12830     }
12831 
12832     return true; // Fail
12833   }
12834 
12835   // If the named context is dependent, we can't decide much.
12836   if (!NamedContext) {
12837     // FIXME: in C++0x, we can diagnose if we can prove that the
12838     // nested-name-specifier does not refer to a base class, which is
12839     // still possible in some cases.
12840 
12841     // Otherwise we have to conservatively report that things might be
12842     // okay.
12843     return false;
12844   }
12845 
12846   // The current scope is a record.
12847   if (!NamedContext->isRecord()) {
12848     // Ideally this would point at the last name in the specifier,
12849     // but we don't have that level of source info.
12850     Diag(SS.getBeginLoc(),
12851          Cxx20Enumerator
12852              ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12853              : diag::err_using_decl_nested_name_specifier_is_not_class)
12854         << SS.getScopeRep() << SS.getRange();
12855 
12856     if (Cxx20Enumerator)
12857       return false; // OK
12858 
12859     return true;
12860   }
12861 
12862   if (!NamedContext->isDependentContext() &&
12863       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12864     return true;
12865 
12866   if (getLangOpts().CPlusPlus11) {
12867     // C++11 [namespace.udecl]p3:
12868     //   In a using-declaration used as a member-declaration, the
12869     //   nested-name-specifier shall name a base class of the class
12870     //   being defined.
12871 
12872     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12873                                  cast<CXXRecordDecl>(NamedContext))) {
12874 
12875       if (Cxx20Enumerator) {
12876         Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12877             << SS.getRange();
12878         return false;
12879       }
12880 
12881       if (CurContext == NamedContext) {
12882         Diag(SS.getBeginLoc(),
12883              diag::err_using_decl_nested_name_specifier_is_current_class)
12884             << SS.getRange();
12885         return !getLangOpts().CPlusPlus20;
12886       }
12887 
12888       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12889         Diag(SS.getBeginLoc(),
12890              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12891             << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12892             << SS.getRange();
12893       }
12894       return true;
12895     }
12896 
12897     return false;
12898   }
12899 
12900   // C++03 [namespace.udecl]p4:
12901   //   A using-declaration used as a member-declaration shall refer
12902   //   to a member of a base class of the class being defined [etc.].
12903 
12904   // Salient point: SS doesn't have to name a base class as long as
12905   // lookup only finds members from base classes.  Therefore we can
12906   // diagnose here only if we can prove that that can't happen,
12907   // i.e. if the class hierarchies provably don't intersect.
12908 
12909   // TODO: it would be nice if "definitely valid" results were cached
12910   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12911   // need to be repeated.
12912 
12913   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12914   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12915     Bases.insert(Base);
12916     return true;
12917   };
12918 
12919   // Collect all bases. Return false if we find a dependent base.
12920   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12921     return false;
12922 
12923   // Returns true if the base is dependent or is one of the accumulated base
12924   // classes.
12925   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12926     return !Bases.count(Base);
12927   };
12928 
12929   // Return false if the class has a dependent base or if it or one
12930   // of its bases is present in the base set of the current context.
12931   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12932       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12933     return false;
12934 
12935   Diag(SS.getRange().getBegin(),
12936        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12937     << SS.getScopeRep()
12938     << cast<CXXRecordDecl>(CurContext)
12939     << SS.getRange();
12940 
12941   return true;
12942 }
12943 
12944 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12945                                   MultiTemplateParamsArg TemplateParamLists,
12946                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12947                                   const ParsedAttributesView &AttrList,
12948                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12949   // Skip up to the relevant declaration scope.
12950   while (S->isTemplateParamScope())
12951     S = S->getParent();
12952   assert((S->getFlags() & Scope::DeclScope) &&
12953          "got alias-declaration outside of declaration scope");
12954 
12955   if (Type.isInvalid())
12956     return nullptr;
12957 
12958   bool Invalid = false;
12959   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12960   TypeSourceInfo *TInfo = nullptr;
12961   GetTypeFromParser(Type.get(), &TInfo);
12962 
12963   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12964     return nullptr;
12965 
12966   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12967                                       UPPC_DeclarationType)) {
12968     Invalid = true;
12969     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12970                                              TInfo->getTypeLoc().getBeginLoc());
12971   }
12972 
12973   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12974                         TemplateParamLists.size()
12975                             ? forRedeclarationInCurContext()
12976                             : ForVisibleRedeclaration);
12977   LookupName(Previous, S);
12978 
12979   // Warn about shadowing the name of a template parameter.
12980   if (Previous.isSingleResult() &&
12981       Previous.getFoundDecl()->isTemplateParameter()) {
12982     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12983     Previous.clear();
12984   }
12985 
12986   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12987          "name in alias declaration must be an identifier");
12988   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12989                                                Name.StartLocation,
12990                                                Name.Identifier, TInfo);
12991 
12992   NewTD->setAccess(AS);
12993 
12994   if (Invalid)
12995     NewTD->setInvalidDecl();
12996 
12997   ProcessDeclAttributeList(S, NewTD, AttrList);
12998   AddPragmaAttributes(S, NewTD);
12999 
13000   CheckTypedefForVariablyModifiedType(S, NewTD);
13001   Invalid |= NewTD->isInvalidDecl();
13002 
13003   bool Redeclaration = false;
13004 
13005   NamedDecl *NewND;
13006   if (TemplateParamLists.size()) {
13007     TypeAliasTemplateDecl *OldDecl = nullptr;
13008     TemplateParameterList *OldTemplateParams = nullptr;
13009 
13010     if (TemplateParamLists.size() != 1) {
13011       Diag(UsingLoc, diag::err_alias_template_extra_headers)
13012         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13013          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13014     }
13015     TemplateParameterList *TemplateParams = TemplateParamLists[0];
13016 
13017     // Check that we can declare a template here.
13018     if (CheckTemplateDeclScope(S, TemplateParams))
13019       return nullptr;
13020 
13021     // Only consider previous declarations in the same scope.
13022     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
13023                          /*ExplicitInstantiationOrSpecialization*/false);
13024     if (!Previous.empty()) {
13025       Redeclaration = true;
13026 
13027       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13028       if (!OldDecl && !Invalid) {
13029         Diag(UsingLoc, diag::err_redefinition_different_kind)
13030           << Name.Identifier;
13031 
13032         NamedDecl *OldD = Previous.getRepresentativeDecl();
13033         if (OldD->getLocation().isValid())
13034           Diag(OldD->getLocation(), diag::note_previous_definition);
13035 
13036         Invalid = true;
13037       }
13038 
13039       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13040         if (TemplateParameterListsAreEqual(TemplateParams,
13041                                            OldDecl->getTemplateParameters(),
13042                                            /*Complain=*/true,
13043                                            TPL_TemplateMatch))
13044           OldTemplateParams =
13045               OldDecl->getMostRecentDecl()->getTemplateParameters();
13046         else
13047           Invalid = true;
13048 
13049         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13050         if (!Invalid &&
13051             !Context.hasSameType(OldTD->getUnderlyingType(),
13052                                  NewTD->getUnderlyingType())) {
13053           // FIXME: The C++0x standard does not clearly say this is ill-formed,
13054           // but we can't reasonably accept it.
13055           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
13056             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13057           if (OldTD->getLocation().isValid())
13058             Diag(OldTD->getLocation(), diag::note_previous_definition);
13059           Invalid = true;
13060         }
13061       }
13062     }
13063 
13064     // Merge any previous default template arguments into our parameters,
13065     // and check the parameter list.
13066     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13067                                    TPC_TypeAliasTemplate))
13068       return nullptr;
13069 
13070     TypeAliasTemplateDecl *NewDecl =
13071       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13072                                     Name.Identifier, TemplateParams,
13073                                     NewTD);
13074     NewTD->setDescribedAliasTemplate(NewDecl);
13075 
13076     NewDecl->setAccess(AS);
13077 
13078     if (Invalid)
13079       NewDecl->setInvalidDecl();
13080     else if (OldDecl) {
13081       NewDecl->setPreviousDecl(OldDecl);
13082       CheckRedeclarationInModule(NewDecl, OldDecl);
13083     }
13084 
13085     NewND = NewDecl;
13086   } else {
13087     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13088       setTagNameForLinkagePurposes(TD, NewTD);
13089       handleTagNumbering(TD, S);
13090     }
13091     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13092     NewND = NewTD;
13093   }
13094 
13095   PushOnScopeChains(NewND, S);
13096   ActOnDocumentableDecl(NewND);
13097   return NewND;
13098 }
13099 
13100 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13101                                    SourceLocation AliasLoc,
13102                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
13103                                    SourceLocation IdentLoc,
13104                                    IdentifierInfo *Ident) {
13105 
13106   // Lookup the namespace name.
13107   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13108   LookupParsedName(R, S, &SS);
13109 
13110   if (R.isAmbiguous())
13111     return nullptr;
13112 
13113   if (R.empty()) {
13114     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13115       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13116       return nullptr;
13117     }
13118   }
13119   assert(!R.isAmbiguous() && !R.empty());
13120   NamedDecl *ND = R.getRepresentativeDecl();
13121 
13122   // Check if we have a previous declaration with the same name.
13123   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13124                      ForVisibleRedeclaration);
13125   LookupName(PrevR, S);
13126 
13127   // Check we're not shadowing a template parameter.
13128   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13129     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13130     PrevR.clear();
13131   }
13132 
13133   // Filter out any other lookup result from an enclosing scope.
13134   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13135                        /*AllowInlineNamespace*/false);
13136 
13137   // Find the previous declaration and check that we can redeclare it.
13138   NamespaceAliasDecl *Prev = nullptr;
13139   if (PrevR.isSingleResult()) {
13140     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13141     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13142       // We already have an alias with the same name that points to the same
13143       // namespace; check that it matches.
13144       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13145         Prev = AD;
13146       } else if (isVisible(PrevDecl)) {
13147         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13148           << Alias;
13149         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13150           << AD->getNamespace();
13151         return nullptr;
13152       }
13153     } else if (isVisible(PrevDecl)) {
13154       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13155                             ? diag::err_redefinition
13156                             : diag::err_redefinition_different_kind;
13157       Diag(AliasLoc, DiagID) << Alias;
13158       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13159       return nullptr;
13160     }
13161   }
13162 
13163   // The use of a nested name specifier may trigger deprecation warnings.
13164   DiagnoseUseOfDecl(ND, IdentLoc);
13165 
13166   NamespaceAliasDecl *AliasDecl =
13167     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13168                                Alias, SS.getWithLocInContext(Context),
13169                                IdentLoc, ND);
13170   if (Prev)
13171     AliasDecl->setPreviousDecl(Prev);
13172 
13173   PushOnScopeChains(AliasDecl, S);
13174   return AliasDecl;
13175 }
13176 
13177 namespace {
13178 struct SpecialMemberExceptionSpecInfo
13179     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13180   SourceLocation Loc;
13181   Sema::ImplicitExceptionSpecification ExceptSpec;
13182 
13183   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13184                                  Sema::CXXSpecialMember CSM,
13185                                  Sema::InheritedConstructorInfo *ICI,
13186                                  SourceLocation Loc)
13187       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13188 
13189   bool visitBase(CXXBaseSpecifier *Base);
13190   bool visitField(FieldDecl *FD);
13191 
13192   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13193                            unsigned Quals);
13194 
13195   void visitSubobjectCall(Subobject Subobj,
13196                           Sema::SpecialMemberOverloadResult SMOR);
13197 };
13198 }
13199 
13200 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13201   auto *RT = Base->getType()->getAs<RecordType>();
13202   if (!RT)
13203     return false;
13204 
13205   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13206   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13207   if (auto *BaseCtor = SMOR.getMethod()) {
13208     visitSubobjectCall(Base, BaseCtor);
13209     return false;
13210   }
13211 
13212   visitClassSubobject(BaseClass, Base, 0);
13213   return false;
13214 }
13215 
13216 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13217   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13218     Expr *E = FD->getInClassInitializer();
13219     if (!E)
13220       // FIXME: It's a little wasteful to build and throw away a
13221       // CXXDefaultInitExpr here.
13222       // FIXME: We should have a single context note pointing at Loc, and
13223       // this location should be MD->getLocation() instead, since that's
13224       // the location where we actually use the default init expression.
13225       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13226     if (E)
13227       ExceptSpec.CalledExpr(E);
13228   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13229                             ->getAs<RecordType>()) {
13230     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13231                         FD->getType().getCVRQualifiers());
13232   }
13233   return false;
13234 }
13235 
13236 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13237                                                          Subobject Subobj,
13238                                                          unsigned Quals) {
13239   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13240   bool IsMutable = Field && Field->isMutable();
13241   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13242 }
13243 
13244 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13245     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13246   // Note, if lookup fails, it doesn't matter what exception specification we
13247   // choose because the special member will be deleted.
13248   if (CXXMethodDecl *MD = SMOR.getMethod())
13249     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13250 }
13251 
13252 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13253   llvm::APSInt Result;
13254   ExprResult Converted = CheckConvertedConstantExpression(
13255       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13256   ExplicitSpec.setExpr(Converted.get());
13257   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13258     ExplicitSpec.setKind(Result.getBoolValue()
13259                              ? ExplicitSpecKind::ResolvedTrue
13260                              : ExplicitSpecKind::ResolvedFalse);
13261     return true;
13262   }
13263   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13264   return false;
13265 }
13266 
13267 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13268   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13269   if (!ExplicitExpr->isTypeDependent())
13270     tryResolveExplicitSpecifier(ES);
13271   return ES;
13272 }
13273 
13274 static Sema::ImplicitExceptionSpecification
13275 ComputeDefaultedSpecialMemberExceptionSpec(
13276     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13277     Sema::InheritedConstructorInfo *ICI) {
13278   ComputingExceptionSpec CES(S, MD, Loc);
13279 
13280   CXXRecordDecl *ClassDecl = MD->getParent();
13281 
13282   // C++ [except.spec]p14:
13283   //   An implicitly declared special member function (Clause 12) shall have an
13284   //   exception-specification. [...]
13285   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13286   if (ClassDecl->isInvalidDecl())
13287     return Info.ExceptSpec;
13288 
13289   // FIXME: If this diagnostic fires, we're probably missing a check for
13290   // attempting to resolve an exception specification before it's known
13291   // at a higher level.
13292   if (S.RequireCompleteType(MD->getLocation(),
13293                             S.Context.getRecordType(ClassDecl),
13294                             diag::err_exception_spec_incomplete_type))
13295     return Info.ExceptSpec;
13296 
13297   // C++1z [except.spec]p7:
13298   //   [Look for exceptions thrown by] a constructor selected [...] to
13299   //   initialize a potentially constructed subobject,
13300   // C++1z [except.spec]p8:
13301   //   The exception specification for an implicitly-declared destructor, or a
13302   //   destructor without a noexcept-specifier, is potentially-throwing if and
13303   //   only if any of the destructors for any of its potentially constructed
13304   //   subojects is potentially throwing.
13305   // FIXME: We respect the first rule but ignore the "potentially constructed"
13306   // in the second rule to resolve a core issue (no number yet) that would have
13307   // us reject:
13308   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13309   //   struct B : A {};
13310   //   struct C : B { void f(); };
13311   // ... due to giving B::~B() a non-throwing exception specification.
13312   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13313                                 : Info.VisitAllBases);
13314 
13315   return Info.ExceptSpec;
13316 }
13317 
13318 namespace {
13319 /// RAII object to register a special member as being currently declared.
13320 struct DeclaringSpecialMember {
13321   Sema &S;
13322   Sema::SpecialMemberDecl D;
13323   Sema::ContextRAII SavedContext;
13324   bool WasAlreadyBeingDeclared;
13325 
13326   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13327       : S(S), D(RD, CSM), SavedContext(S, RD) {
13328     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13329     if (WasAlreadyBeingDeclared)
13330       // This almost never happens, but if it does, ensure that our cache
13331       // doesn't contain a stale result.
13332       S.SpecialMemberCache.clear();
13333     else {
13334       // Register a note to be produced if we encounter an error while
13335       // declaring the special member.
13336       Sema::CodeSynthesisContext Ctx;
13337       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13338       // FIXME: We don't have a location to use here. Using the class's
13339       // location maintains the fiction that we declare all special members
13340       // with the class, but (1) it's not clear that lying about that helps our
13341       // users understand what's going on, and (2) there may be outer contexts
13342       // on the stack (some of which are relevant) and printing them exposes
13343       // our lies.
13344       Ctx.PointOfInstantiation = RD->getLocation();
13345       Ctx.Entity = RD;
13346       Ctx.SpecialMember = CSM;
13347       S.pushCodeSynthesisContext(Ctx);
13348     }
13349   }
13350   ~DeclaringSpecialMember() {
13351     if (!WasAlreadyBeingDeclared) {
13352       S.SpecialMembersBeingDeclared.erase(D);
13353       S.popCodeSynthesisContext();
13354     }
13355   }
13356 
13357   /// Are we already trying to declare this special member?
13358   bool isAlreadyBeingDeclared() const {
13359     return WasAlreadyBeingDeclared;
13360   }
13361 };
13362 }
13363 
13364 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13365   // Look up any existing declarations, but don't trigger declaration of all
13366   // implicit special members with this name.
13367   DeclarationName Name = FD->getDeclName();
13368   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13369                  ForExternalRedeclaration);
13370   for (auto *D : FD->getParent()->lookup(Name))
13371     if (auto *Acceptable = R.getAcceptableDecl(D))
13372       R.addDecl(Acceptable);
13373   R.resolveKind();
13374   R.suppressDiagnostics();
13375 
13376   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/ false,
13377                            FD->isThisDeclarationADefinition());
13378 }
13379 
13380 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13381                                           QualType ResultTy,
13382                                           ArrayRef<QualType> Args) {
13383   // Build an exception specification pointing back at this constructor.
13384   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13385 
13386   LangAS AS = getDefaultCXXMethodAddrSpace();
13387   if (AS != LangAS::Default) {
13388     EPI.TypeQuals.addAddressSpace(AS);
13389   }
13390 
13391   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13392   SpecialMem->setType(QT);
13393 
13394   // During template instantiation of implicit special member functions we need
13395   // a reliable TypeSourceInfo for the function prototype in order to allow
13396   // functions to be substituted.
13397   if (inTemplateInstantiation() &&
13398       cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13399     TypeSourceInfo *TSI =
13400         Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13401     SpecialMem->setTypeSourceInfo(TSI);
13402   }
13403 }
13404 
13405 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13406                                                      CXXRecordDecl *ClassDecl) {
13407   // C++ [class.ctor]p5:
13408   //   A default constructor for a class X is a constructor of class X
13409   //   that can be called without an argument. If there is no
13410   //   user-declared constructor for class X, a default constructor is
13411   //   implicitly declared. An implicitly-declared default constructor
13412   //   is an inline public member of its class.
13413   assert(ClassDecl->needsImplicitDefaultConstructor() &&
13414          "Should not build implicit default constructor!");
13415 
13416   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13417   if (DSM.isAlreadyBeingDeclared())
13418     return nullptr;
13419 
13420   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13421                                                      CXXDefaultConstructor,
13422                                                      false);
13423 
13424   // Create the actual constructor declaration.
13425   CanQualType ClassType
13426     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13427   SourceLocation ClassLoc = ClassDecl->getLocation();
13428   DeclarationName Name
13429     = Context.DeclarationNames.getCXXConstructorName(ClassType);
13430   DeclarationNameInfo NameInfo(Name, ClassLoc);
13431   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13432       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13433       /*TInfo=*/nullptr, ExplicitSpecifier(),
13434       getCurFPFeatures().isFPConstrained(),
13435       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13436       Constexpr ? ConstexprSpecKind::Constexpr
13437                 : ConstexprSpecKind::Unspecified);
13438   DefaultCon->setAccess(AS_public);
13439   DefaultCon->setDefaulted();
13440 
13441   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13442 
13443   if (getLangOpts().CUDA)
13444     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13445                                             DefaultCon,
13446                                             /* ConstRHS */ false,
13447                                             /* Diagnose */ false);
13448 
13449   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13450   // constructors is easy to compute.
13451   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13452 
13453   // Note that we have declared this constructor.
13454   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13455 
13456   Scope *S = getScopeForContext(ClassDecl);
13457   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13458 
13459   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13460     SetDeclDeleted(DefaultCon, ClassLoc);
13461 
13462   if (S)
13463     PushOnScopeChains(DefaultCon, S, false);
13464   ClassDecl->addDecl(DefaultCon);
13465 
13466   return DefaultCon;
13467 }
13468 
13469 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13470                                             CXXConstructorDecl *Constructor) {
13471   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13472           !Constructor->doesThisDeclarationHaveABody() &&
13473           !Constructor->isDeleted()) &&
13474     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13475   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13476     return;
13477 
13478   CXXRecordDecl *ClassDecl = Constructor->getParent();
13479   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13480 
13481   SynthesizedFunctionScope Scope(*this, Constructor);
13482 
13483   // The exception specification is needed because we are defining the
13484   // function.
13485   ResolveExceptionSpec(CurrentLocation,
13486                        Constructor->getType()->castAs<FunctionProtoType>());
13487   MarkVTableUsed(CurrentLocation, ClassDecl);
13488 
13489   // Add a context note for diagnostics produced after this point.
13490   Scope.addContextNote(CurrentLocation);
13491 
13492   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13493     Constructor->setInvalidDecl();
13494     return;
13495   }
13496 
13497   SourceLocation Loc = Constructor->getEndLoc().isValid()
13498                            ? Constructor->getEndLoc()
13499                            : Constructor->getLocation();
13500   Constructor->setBody(new (Context) CompoundStmt(Loc));
13501   Constructor->markUsed(Context);
13502 
13503   if (ASTMutationListener *L = getASTMutationListener()) {
13504     L->CompletedImplicitDefinition(Constructor);
13505   }
13506 
13507   DiagnoseUninitializedFields(*this, Constructor);
13508 }
13509 
13510 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13511   // Perform any delayed checks on exception specifications.
13512   CheckDelayedMemberExceptionSpecs();
13513 }
13514 
13515 /// Find or create the fake constructor we synthesize to model constructing an
13516 /// object of a derived class via a constructor of a base class.
13517 CXXConstructorDecl *
13518 Sema::findInheritingConstructor(SourceLocation Loc,
13519                                 CXXConstructorDecl *BaseCtor,
13520                                 ConstructorUsingShadowDecl *Shadow) {
13521   CXXRecordDecl *Derived = Shadow->getParent();
13522   SourceLocation UsingLoc = Shadow->getLocation();
13523 
13524   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13525   // For now we use the name of the base class constructor as a member of the
13526   // derived class to indicate a (fake) inherited constructor name.
13527   DeclarationName Name = BaseCtor->getDeclName();
13528 
13529   // Check to see if we already have a fake constructor for this inherited
13530   // constructor call.
13531   for (NamedDecl *Ctor : Derived->lookup(Name))
13532     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13533                                ->getInheritedConstructor()
13534                                .getConstructor(),
13535                            BaseCtor))
13536       return cast<CXXConstructorDecl>(Ctor);
13537 
13538   DeclarationNameInfo NameInfo(Name, UsingLoc);
13539   TypeSourceInfo *TInfo =
13540       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13541   FunctionProtoTypeLoc ProtoLoc =
13542       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13543 
13544   // Check the inherited constructor is valid and find the list of base classes
13545   // from which it was inherited.
13546   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13547 
13548   bool Constexpr =
13549       BaseCtor->isConstexpr() &&
13550       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13551                                         false, BaseCtor, &ICI);
13552 
13553   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13554       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13555       BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13556       /*isInline=*/true,
13557       /*isImplicitlyDeclared=*/true,
13558       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13559       InheritedConstructor(Shadow, BaseCtor),
13560       BaseCtor->getTrailingRequiresClause());
13561   if (Shadow->isInvalidDecl())
13562     DerivedCtor->setInvalidDecl();
13563 
13564   // Build an unevaluated exception specification for this fake constructor.
13565   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13566   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13567   EPI.ExceptionSpec.Type = EST_Unevaluated;
13568   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13569   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13570                                                FPT->getParamTypes(), EPI));
13571 
13572   // Build the parameter declarations.
13573   SmallVector<ParmVarDecl *, 16> ParamDecls;
13574   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13575     TypeSourceInfo *TInfo =
13576         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13577     ParmVarDecl *PD = ParmVarDecl::Create(
13578         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13579         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13580     PD->setScopeInfo(0, I);
13581     PD->setImplicit();
13582     // Ensure attributes are propagated onto parameters (this matters for
13583     // format, pass_object_size, ...).
13584     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13585     ParamDecls.push_back(PD);
13586     ProtoLoc.setParam(I, PD);
13587   }
13588 
13589   // Set up the new constructor.
13590   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13591   DerivedCtor->setAccess(BaseCtor->getAccess());
13592   DerivedCtor->setParams(ParamDecls);
13593   Derived->addDecl(DerivedCtor);
13594 
13595   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13596     SetDeclDeleted(DerivedCtor, UsingLoc);
13597 
13598   return DerivedCtor;
13599 }
13600 
13601 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13602   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13603                                Ctor->getInheritedConstructor().getShadowDecl());
13604   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13605                             /*Diagnose*/true);
13606 }
13607 
13608 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13609                                        CXXConstructorDecl *Constructor) {
13610   CXXRecordDecl *ClassDecl = Constructor->getParent();
13611   assert(Constructor->getInheritedConstructor() &&
13612          !Constructor->doesThisDeclarationHaveABody() &&
13613          !Constructor->isDeleted());
13614   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13615     return;
13616 
13617   // Initializations are performed "as if by a defaulted default constructor",
13618   // so enter the appropriate scope.
13619   SynthesizedFunctionScope Scope(*this, Constructor);
13620 
13621   // The exception specification is needed because we are defining the
13622   // function.
13623   ResolveExceptionSpec(CurrentLocation,
13624                        Constructor->getType()->castAs<FunctionProtoType>());
13625   MarkVTableUsed(CurrentLocation, ClassDecl);
13626 
13627   // Add a context note for diagnostics produced after this point.
13628   Scope.addContextNote(CurrentLocation);
13629 
13630   ConstructorUsingShadowDecl *Shadow =
13631       Constructor->getInheritedConstructor().getShadowDecl();
13632   CXXConstructorDecl *InheritedCtor =
13633       Constructor->getInheritedConstructor().getConstructor();
13634 
13635   // [class.inhctor.init]p1:
13636   //   initialization proceeds as if a defaulted default constructor is used to
13637   //   initialize the D object and each base class subobject from which the
13638   //   constructor was inherited
13639 
13640   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13641   CXXRecordDecl *RD = Shadow->getParent();
13642   SourceLocation InitLoc = Shadow->getLocation();
13643 
13644   // Build explicit initializers for all base classes from which the
13645   // constructor was inherited.
13646   SmallVector<CXXCtorInitializer*, 8> Inits;
13647   for (bool VBase : {false, true}) {
13648     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13649       if (B.isVirtual() != VBase)
13650         continue;
13651 
13652       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13653       if (!BaseRD)
13654         continue;
13655 
13656       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13657       if (!BaseCtor.first)
13658         continue;
13659 
13660       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13661       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13662           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13663 
13664       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13665       Inits.push_back(new (Context) CXXCtorInitializer(
13666           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13667           SourceLocation()));
13668     }
13669   }
13670 
13671   // We now proceed as if for a defaulted default constructor, with the relevant
13672   // initializers replaced.
13673 
13674   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13675     Constructor->setInvalidDecl();
13676     return;
13677   }
13678 
13679   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13680   Constructor->markUsed(Context);
13681 
13682   if (ASTMutationListener *L = getASTMutationListener()) {
13683     L->CompletedImplicitDefinition(Constructor);
13684   }
13685 
13686   DiagnoseUninitializedFields(*this, Constructor);
13687 }
13688 
13689 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13690   // C++ [class.dtor]p2:
13691   //   If a class has no user-declared destructor, a destructor is
13692   //   declared implicitly. An implicitly-declared destructor is an
13693   //   inline public member of its class.
13694   assert(ClassDecl->needsImplicitDestructor());
13695 
13696   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13697   if (DSM.isAlreadyBeingDeclared())
13698     return nullptr;
13699 
13700   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13701                                                      CXXDestructor,
13702                                                      false);
13703 
13704   // Create the actual destructor declaration.
13705   CanQualType ClassType
13706     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13707   SourceLocation ClassLoc = ClassDecl->getLocation();
13708   DeclarationName Name
13709     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13710   DeclarationNameInfo NameInfo(Name, ClassLoc);
13711   CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
13712       Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13713       getCurFPFeatures().isFPConstrained(),
13714       /*isInline=*/true,
13715       /*isImplicitlyDeclared=*/true,
13716       Constexpr ? ConstexprSpecKind::Constexpr
13717                 : ConstexprSpecKind::Unspecified);
13718   Destructor->setAccess(AS_public);
13719   Destructor->setDefaulted();
13720 
13721   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13722 
13723   if (getLangOpts().CUDA)
13724     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13725                                             Destructor,
13726                                             /* ConstRHS */ false,
13727                                             /* Diagnose */ false);
13728 
13729   // We don't need to use SpecialMemberIsTrivial here; triviality for
13730   // destructors is easy to compute.
13731   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13732   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13733                                 ClassDecl->hasTrivialDestructorForCall());
13734 
13735   // Note that we have declared this destructor.
13736   ++getASTContext().NumImplicitDestructorsDeclared;
13737 
13738   Scope *S = getScopeForContext(ClassDecl);
13739   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13740 
13741   // We can't check whether an implicit destructor is deleted before we complete
13742   // the definition of the class, because its validity depends on the alignment
13743   // of the class. We'll check this from ActOnFields once the class is complete.
13744   if (ClassDecl->isCompleteDefinition() &&
13745       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13746     SetDeclDeleted(Destructor, ClassLoc);
13747 
13748   // Introduce this destructor into its scope.
13749   if (S)
13750     PushOnScopeChains(Destructor, S, false);
13751   ClassDecl->addDecl(Destructor);
13752 
13753   return Destructor;
13754 }
13755 
13756 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13757                                     CXXDestructorDecl *Destructor) {
13758   assert((Destructor->isDefaulted() &&
13759           !Destructor->doesThisDeclarationHaveABody() &&
13760           !Destructor->isDeleted()) &&
13761          "DefineImplicitDestructor - call it for implicit default dtor");
13762   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13763     return;
13764 
13765   CXXRecordDecl *ClassDecl = Destructor->getParent();
13766   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13767 
13768   SynthesizedFunctionScope Scope(*this, Destructor);
13769 
13770   // The exception specification is needed because we are defining the
13771   // function.
13772   ResolveExceptionSpec(CurrentLocation,
13773                        Destructor->getType()->castAs<FunctionProtoType>());
13774   MarkVTableUsed(CurrentLocation, ClassDecl);
13775 
13776   // Add a context note for diagnostics produced after this point.
13777   Scope.addContextNote(CurrentLocation);
13778 
13779   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13780                                          Destructor->getParent());
13781 
13782   if (CheckDestructor(Destructor)) {
13783     Destructor->setInvalidDecl();
13784     return;
13785   }
13786 
13787   SourceLocation Loc = Destructor->getEndLoc().isValid()
13788                            ? Destructor->getEndLoc()
13789                            : Destructor->getLocation();
13790   Destructor->setBody(new (Context) CompoundStmt(Loc));
13791   Destructor->markUsed(Context);
13792 
13793   if (ASTMutationListener *L = getASTMutationListener()) {
13794     L->CompletedImplicitDefinition(Destructor);
13795   }
13796 }
13797 
13798 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13799                                           CXXDestructorDecl *Destructor) {
13800   if (Destructor->isInvalidDecl())
13801     return;
13802 
13803   CXXRecordDecl *ClassDecl = Destructor->getParent();
13804   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13805          "implicit complete dtors unneeded outside MS ABI");
13806   assert(ClassDecl->getNumVBases() > 0 &&
13807          "complete dtor only exists for classes with vbases");
13808 
13809   SynthesizedFunctionScope Scope(*this, Destructor);
13810 
13811   // Add a context note for diagnostics produced after this point.
13812   Scope.addContextNote(CurrentLocation);
13813 
13814   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13815 }
13816 
13817 /// Perform any semantic analysis which needs to be delayed until all
13818 /// pending class member declarations have been parsed.
13819 void Sema::ActOnFinishCXXMemberDecls() {
13820   // If the context is an invalid C++ class, just suppress these checks.
13821   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13822     if (Record->isInvalidDecl()) {
13823       DelayedOverridingExceptionSpecChecks.clear();
13824       DelayedEquivalentExceptionSpecChecks.clear();
13825       return;
13826     }
13827     checkForMultipleExportedDefaultConstructors(*this, Record);
13828   }
13829 }
13830 
13831 void Sema::ActOnFinishCXXNonNestedClass() {
13832   referenceDLLExportedClassMethods();
13833 
13834   if (!DelayedDllExportMemberFunctions.empty()) {
13835     SmallVector<CXXMethodDecl*, 4> WorkList;
13836     std::swap(DelayedDllExportMemberFunctions, WorkList);
13837     for (CXXMethodDecl *M : WorkList) {
13838       DefineDefaultedFunction(*this, M, M->getLocation());
13839 
13840       // Pass the method to the consumer to get emitted. This is not necessary
13841       // for explicit instantiation definitions, as they will get emitted
13842       // anyway.
13843       if (M->getParent()->getTemplateSpecializationKind() !=
13844           TSK_ExplicitInstantiationDefinition)
13845         ActOnFinishInlineFunctionDef(M);
13846     }
13847   }
13848 }
13849 
13850 void Sema::referenceDLLExportedClassMethods() {
13851   if (!DelayedDllExportClasses.empty()) {
13852     // Calling ReferenceDllExportedMembers might cause the current function to
13853     // be called again, so use a local copy of DelayedDllExportClasses.
13854     SmallVector<CXXRecordDecl *, 4> WorkList;
13855     std::swap(DelayedDllExportClasses, WorkList);
13856     for (CXXRecordDecl *Class : WorkList)
13857       ReferenceDllExportedMembers(*this, Class);
13858   }
13859 }
13860 
13861 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13862   assert(getLangOpts().CPlusPlus11 &&
13863          "adjusting dtor exception specs was introduced in c++11");
13864 
13865   if (Destructor->isDependentContext())
13866     return;
13867 
13868   // C++11 [class.dtor]p3:
13869   //   A declaration of a destructor that does not have an exception-
13870   //   specification is implicitly considered to have the same exception-
13871   //   specification as an implicit declaration.
13872   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13873   if (DtorType->hasExceptionSpec())
13874     return;
13875 
13876   // Replace the destructor's type, building off the existing one. Fortunately,
13877   // the only thing of interest in the destructor type is its extended info.
13878   // The return and arguments are fixed.
13879   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13880   EPI.ExceptionSpec.Type = EST_Unevaluated;
13881   EPI.ExceptionSpec.SourceDecl = Destructor;
13882   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13883 
13884   // FIXME: If the destructor has a body that could throw, and the newly created
13885   // spec doesn't allow exceptions, we should emit a warning, because this
13886   // change in behavior can break conforming C++03 programs at runtime.
13887   // However, we don't have a body or an exception specification yet, so it
13888   // needs to be done somewhere else.
13889 }
13890 
13891 namespace {
13892 /// An abstract base class for all helper classes used in building the
13893 //  copy/move operators. These classes serve as factory functions and help us
13894 //  avoid using the same Expr* in the AST twice.
13895 class ExprBuilder {
13896   ExprBuilder(const ExprBuilder&) = delete;
13897   ExprBuilder &operator=(const ExprBuilder&) = delete;
13898 
13899 protected:
13900   static Expr *assertNotNull(Expr *E) {
13901     assert(E && "Expression construction must not fail.");
13902     return E;
13903   }
13904 
13905 public:
13906   ExprBuilder() {}
13907   virtual ~ExprBuilder() {}
13908 
13909   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13910 };
13911 
13912 class RefBuilder: public ExprBuilder {
13913   VarDecl *Var;
13914   QualType VarType;
13915 
13916 public:
13917   Expr *build(Sema &S, SourceLocation Loc) const override {
13918     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13919   }
13920 
13921   RefBuilder(VarDecl *Var, QualType VarType)
13922       : Var(Var), VarType(VarType) {}
13923 };
13924 
13925 class ThisBuilder: public ExprBuilder {
13926 public:
13927   Expr *build(Sema &S, SourceLocation Loc) const override {
13928     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13929   }
13930 };
13931 
13932 class CastBuilder: public ExprBuilder {
13933   const ExprBuilder &Builder;
13934   QualType Type;
13935   ExprValueKind Kind;
13936   const CXXCastPath &Path;
13937 
13938 public:
13939   Expr *build(Sema &S, SourceLocation Loc) const override {
13940     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13941                                              CK_UncheckedDerivedToBase, Kind,
13942                                              &Path).get());
13943   }
13944 
13945   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13946               const CXXCastPath &Path)
13947       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13948 };
13949 
13950 class DerefBuilder: public ExprBuilder {
13951   const ExprBuilder &Builder;
13952 
13953 public:
13954   Expr *build(Sema &S, SourceLocation Loc) const override {
13955     return assertNotNull(
13956         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13957   }
13958 
13959   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13960 };
13961 
13962 class MemberBuilder: public ExprBuilder {
13963   const ExprBuilder &Builder;
13964   QualType Type;
13965   CXXScopeSpec SS;
13966   bool IsArrow;
13967   LookupResult &MemberLookup;
13968 
13969 public:
13970   Expr *build(Sema &S, SourceLocation Loc) const override {
13971     return assertNotNull(S.BuildMemberReferenceExpr(
13972         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13973         nullptr, MemberLookup, nullptr, nullptr).get());
13974   }
13975 
13976   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13977                 LookupResult &MemberLookup)
13978       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13979         MemberLookup(MemberLookup) {}
13980 };
13981 
13982 class MoveCastBuilder: public ExprBuilder {
13983   const ExprBuilder &Builder;
13984 
13985 public:
13986   Expr *build(Sema &S, SourceLocation Loc) const override {
13987     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13988   }
13989 
13990   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13991 };
13992 
13993 class LvalueConvBuilder: public ExprBuilder {
13994   const ExprBuilder &Builder;
13995 
13996 public:
13997   Expr *build(Sema &S, SourceLocation Loc) const override {
13998     return assertNotNull(
13999         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
14000   }
14001 
14002   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14003 };
14004 
14005 class SubscriptBuilder: public ExprBuilder {
14006   const ExprBuilder &Base;
14007   const ExprBuilder &Index;
14008 
14009 public:
14010   Expr *build(Sema &S, SourceLocation Loc) const override {
14011     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
14012         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
14013   }
14014 
14015   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14016       : Base(Base), Index(Index) {}
14017 };
14018 
14019 } // end anonymous namespace
14020 
14021 /// When generating a defaulted copy or move assignment operator, if a field
14022 /// should be copied with __builtin_memcpy rather than via explicit assignments,
14023 /// do so. This optimization only applies for arrays of scalars, and for arrays
14024 /// of class type where the selected copy/move-assignment operator is trivial.
14025 static StmtResult
14026 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14027                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
14028   // Compute the size of the memory buffer to be copied.
14029   QualType SizeType = S.Context.getSizeType();
14030   llvm::APInt Size(S.Context.getTypeSize(SizeType),
14031                    S.Context.getTypeSizeInChars(T).getQuantity());
14032 
14033   // Take the address of the field references for "from" and "to". We
14034   // directly construct UnaryOperators here because semantic analysis
14035   // does not permit us to take the address of an xvalue.
14036   Expr *From = FromB.build(S, Loc);
14037   From = UnaryOperator::Create(
14038       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
14039       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14040   Expr *To = ToB.build(S, Loc);
14041   To = UnaryOperator::Create(
14042       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
14043       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
14044 
14045   const Type *E = T->getBaseElementTypeUnsafe();
14046   bool NeedsCollectableMemCpy =
14047       E->isRecordType() &&
14048       E->castAs<RecordType>()->getDecl()->hasObjectMember();
14049 
14050   // Create a reference to the __builtin_objc_memmove_collectable function
14051   StringRef MemCpyName = NeedsCollectableMemCpy ?
14052     "__builtin_objc_memmove_collectable" :
14053     "__builtin_memcpy";
14054   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
14055                  Sema::LookupOrdinaryName);
14056   S.LookupName(R, S.TUScope, true);
14057 
14058   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14059   if (!MemCpy)
14060     // Something went horribly wrong earlier, and we will have complained
14061     // about it.
14062     return StmtError();
14063 
14064   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
14065                                             VK_PRValue, Loc, nullptr);
14066   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14067 
14068   Expr *CallArgs[] = {
14069     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14070   };
14071   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14072                                     Loc, CallArgs, Loc);
14073 
14074   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14075   return Call.getAs<Stmt>();
14076 }
14077 
14078 /// Builds a statement that copies/moves the given entity from \p From to
14079 /// \c To.
14080 ///
14081 /// This routine is used to copy/move the members of a class with an
14082 /// implicitly-declared copy/move assignment operator. When the entities being
14083 /// copied are arrays, this routine builds for loops to copy them.
14084 ///
14085 /// \param S The Sema object used for type-checking.
14086 ///
14087 /// \param Loc The location where the implicit copy/move is being generated.
14088 ///
14089 /// \param T The type of the expressions being copied/moved. Both expressions
14090 /// must have this type.
14091 ///
14092 /// \param To The expression we are copying/moving to.
14093 ///
14094 /// \param From The expression we are copying/moving from.
14095 ///
14096 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14097 /// Otherwise, it's a non-static member subobject.
14098 ///
14099 /// \param Copying Whether we're copying or moving.
14100 ///
14101 /// \param Depth Internal parameter recording the depth of the recursion.
14102 ///
14103 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14104 /// if a memcpy should be used instead.
14105 static StmtResult
14106 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14107                                  const ExprBuilder &To, const ExprBuilder &From,
14108                                  bool CopyingBaseSubobject, bool Copying,
14109                                  unsigned Depth = 0) {
14110   // C++11 [class.copy]p28:
14111   //   Each subobject is assigned in the manner appropriate to its type:
14112   //
14113   //     - if the subobject is of class type, as if by a call to operator= with
14114   //       the subobject as the object expression and the corresponding
14115   //       subobject of x as a single function argument (as if by explicit
14116   //       qualification; that is, ignoring any possible virtual overriding
14117   //       functions in more derived classes);
14118   //
14119   // C++03 [class.copy]p13:
14120   //     - if the subobject is of class type, the copy assignment operator for
14121   //       the class is used (as if by explicit qualification; that is,
14122   //       ignoring any possible virtual overriding functions in more derived
14123   //       classes);
14124   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14125     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14126 
14127     // Look for operator=.
14128     DeclarationName Name
14129       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14130     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14131     S.LookupQualifiedName(OpLookup, ClassDecl, false);
14132 
14133     // Prior to C++11, filter out any result that isn't a copy/move-assignment
14134     // operator.
14135     if (!S.getLangOpts().CPlusPlus11) {
14136       LookupResult::Filter F = OpLookup.makeFilter();
14137       while (F.hasNext()) {
14138         NamedDecl *D = F.next();
14139         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14140           if (Method->isCopyAssignmentOperator() ||
14141               (!Copying && Method->isMoveAssignmentOperator()))
14142             continue;
14143 
14144         F.erase();
14145       }
14146       F.done();
14147     }
14148 
14149     // Suppress the protected check (C++ [class.protected]) for each of the
14150     // assignment operators we found. This strange dance is required when
14151     // we're assigning via a base classes's copy-assignment operator. To
14152     // ensure that we're getting the right base class subobject (without
14153     // ambiguities), we need to cast "this" to that subobject type; to
14154     // ensure that we don't go through the virtual call mechanism, we need
14155     // to qualify the operator= name with the base class (see below). However,
14156     // this means that if the base class has a protected copy assignment
14157     // operator, the protected member access check will fail. So, we
14158     // rewrite "protected" access to "public" access in this case, since we
14159     // know by construction that we're calling from a derived class.
14160     if (CopyingBaseSubobject) {
14161       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14162            L != LEnd; ++L) {
14163         if (L.getAccess() == AS_protected)
14164           L.setAccess(AS_public);
14165       }
14166     }
14167 
14168     // Create the nested-name-specifier that will be used to qualify the
14169     // reference to operator=; this is required to suppress the virtual
14170     // call mechanism.
14171     CXXScopeSpec SS;
14172     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14173     SS.MakeTrivial(S.Context,
14174                    NestedNameSpecifier::Create(S.Context, nullptr, false,
14175                                                CanonicalT),
14176                    Loc);
14177 
14178     // Create the reference to operator=.
14179     ExprResult OpEqualRef
14180       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14181                                    SS, /*TemplateKWLoc=*/SourceLocation(),
14182                                    /*FirstQualifierInScope=*/nullptr,
14183                                    OpLookup,
14184                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
14185                                    /*SuppressQualifierCheck=*/true);
14186     if (OpEqualRef.isInvalid())
14187       return StmtError();
14188 
14189     // Build the call to the assignment operator.
14190 
14191     Expr *FromInst = From.build(S, Loc);
14192     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14193                                                   OpEqualRef.getAs<Expr>(),
14194                                                   Loc, FromInst, Loc);
14195     if (Call.isInvalid())
14196       return StmtError();
14197 
14198     // If we built a call to a trivial 'operator=' while copying an array,
14199     // bail out. We'll replace the whole shebang with a memcpy.
14200     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14201     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14202       return StmtResult((Stmt*)nullptr);
14203 
14204     // Convert to an expression-statement, and clean up any produced
14205     // temporaries.
14206     return S.ActOnExprStmt(Call);
14207   }
14208 
14209   //     - if the subobject is of scalar type, the built-in assignment
14210   //       operator is used.
14211   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14212   if (!ArrayTy) {
14213     ExprResult Assignment = S.CreateBuiltinBinOp(
14214         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14215     if (Assignment.isInvalid())
14216       return StmtError();
14217     return S.ActOnExprStmt(Assignment);
14218   }
14219 
14220   //     - if the subobject is an array, each element is assigned, in the
14221   //       manner appropriate to the element type;
14222 
14223   // Construct a loop over the array bounds, e.g.,
14224   //
14225   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14226   //
14227   // that will copy each of the array elements.
14228   QualType SizeType = S.Context.getSizeType();
14229 
14230   // Create the iteration variable.
14231   IdentifierInfo *IterationVarName = nullptr;
14232   {
14233     SmallString<8> Str;
14234     llvm::raw_svector_ostream OS(Str);
14235     OS << "__i" << Depth;
14236     IterationVarName = &S.Context.Idents.get(OS.str());
14237   }
14238   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14239                                           IterationVarName, SizeType,
14240                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14241                                           SC_None);
14242 
14243   // Initialize the iteration variable to zero.
14244   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14245   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14246 
14247   // Creates a reference to the iteration variable.
14248   RefBuilder IterationVarRef(IterationVar, SizeType);
14249   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14250 
14251   // Create the DeclStmt that holds the iteration variable.
14252   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14253 
14254   // Subscript the "from" and "to" expressions with the iteration variable.
14255   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14256   MoveCastBuilder FromIndexMove(FromIndexCopy);
14257   const ExprBuilder *FromIndex;
14258   if (Copying)
14259     FromIndex = &FromIndexCopy;
14260   else
14261     FromIndex = &FromIndexMove;
14262 
14263   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14264 
14265   // Build the copy/move for an individual element of the array.
14266   StmtResult Copy =
14267     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14268                                      ToIndex, *FromIndex, CopyingBaseSubobject,
14269                                      Copying, Depth + 1);
14270   // Bail out if copying fails or if we determined that we should use memcpy.
14271   if (Copy.isInvalid() || !Copy.get())
14272     return Copy;
14273 
14274   // Create the comparison against the array bound.
14275   llvm::APInt Upper
14276     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14277   Expr *Comparison = BinaryOperator::Create(
14278       S.Context, IterationVarRefRVal.build(S, Loc),
14279       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14280       S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14281       S.CurFPFeatureOverrides());
14282 
14283   // Create the pre-increment of the iteration variable. We can determine
14284   // whether the increment will overflow based on the value of the array
14285   // bound.
14286   Expr *Increment = UnaryOperator::Create(
14287       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14288       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14289 
14290   // Construct the loop that copies all elements of this array.
14291   return S.ActOnForStmt(
14292       Loc, Loc, InitStmt,
14293       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14294       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14295 }
14296 
14297 static StmtResult
14298 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14299                       const ExprBuilder &To, const ExprBuilder &From,
14300                       bool CopyingBaseSubobject, bool Copying) {
14301   // Maybe we should use a memcpy?
14302   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14303       T.isTriviallyCopyableType(S.Context))
14304     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14305 
14306   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14307                                                      CopyingBaseSubobject,
14308                                                      Copying, 0));
14309 
14310   // If we ended up picking a trivial assignment operator for an array of a
14311   // non-trivially-copyable class type, just emit a memcpy.
14312   if (!Result.isInvalid() && !Result.get())
14313     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14314 
14315   return Result;
14316 }
14317 
14318 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14319   // Note: The following rules are largely analoguous to the copy
14320   // constructor rules. Note that virtual bases are not taken into account
14321   // for determining the argument type of the operator. Note also that
14322   // operators taking an object instead of a reference are allowed.
14323   assert(ClassDecl->needsImplicitCopyAssignment());
14324 
14325   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14326   if (DSM.isAlreadyBeingDeclared())
14327     return nullptr;
14328 
14329   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14330   LangAS AS = getDefaultCXXMethodAddrSpace();
14331   if (AS != LangAS::Default)
14332     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14333   QualType RetType = Context.getLValueReferenceType(ArgType);
14334   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14335   if (Const)
14336     ArgType = ArgType.withConst();
14337 
14338   ArgType = Context.getLValueReferenceType(ArgType);
14339 
14340   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14341                                                      CXXCopyAssignment,
14342                                                      Const);
14343 
14344   //   An implicitly-declared copy assignment operator is an inline public
14345   //   member of its class.
14346   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14347   SourceLocation ClassLoc = ClassDecl->getLocation();
14348   DeclarationNameInfo NameInfo(Name, ClassLoc);
14349   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14350       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14351       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14352       getCurFPFeatures().isFPConstrained(),
14353       /*isInline=*/true,
14354       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14355       SourceLocation());
14356   CopyAssignment->setAccess(AS_public);
14357   CopyAssignment->setDefaulted();
14358   CopyAssignment->setImplicit();
14359 
14360   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14361 
14362   if (getLangOpts().CUDA)
14363     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14364                                             CopyAssignment,
14365                                             /* ConstRHS */ Const,
14366                                             /* Diagnose */ false);
14367 
14368   // Add the parameter to the operator.
14369   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14370                                                ClassLoc, ClassLoc,
14371                                                /*Id=*/nullptr, ArgType,
14372                                                /*TInfo=*/nullptr, SC_None,
14373                                                nullptr);
14374   CopyAssignment->setParams(FromParam);
14375 
14376   CopyAssignment->setTrivial(
14377     ClassDecl->needsOverloadResolutionForCopyAssignment()
14378       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14379       : ClassDecl->hasTrivialCopyAssignment());
14380 
14381   // Note that we have added this copy-assignment operator.
14382   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14383 
14384   Scope *S = getScopeForContext(ClassDecl);
14385   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14386 
14387   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14388     ClassDecl->setImplicitCopyAssignmentIsDeleted();
14389     SetDeclDeleted(CopyAssignment, ClassLoc);
14390   }
14391 
14392   if (S)
14393     PushOnScopeChains(CopyAssignment, S, false);
14394   ClassDecl->addDecl(CopyAssignment);
14395 
14396   return CopyAssignment;
14397 }
14398 
14399 /// Diagnose an implicit copy operation for a class which is odr-used, but
14400 /// which is deprecated because the class has a user-declared copy constructor,
14401 /// copy assignment operator, or destructor.
14402 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14403   assert(CopyOp->isImplicit());
14404 
14405   CXXRecordDecl *RD = CopyOp->getParent();
14406   CXXMethodDecl *UserDeclaredOperation = nullptr;
14407 
14408   // In Microsoft mode, assignment operations don't affect constructors and
14409   // vice versa.
14410   if (RD->hasUserDeclaredDestructor()) {
14411     UserDeclaredOperation = RD->getDestructor();
14412   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14413              RD->hasUserDeclaredCopyConstructor() &&
14414              !S.getLangOpts().MSVCCompat) {
14415     // Find any user-declared copy constructor.
14416     for (auto *I : RD->ctors()) {
14417       if (I->isCopyConstructor()) {
14418         UserDeclaredOperation = I;
14419         break;
14420       }
14421     }
14422     assert(UserDeclaredOperation);
14423   } else if (isa<CXXConstructorDecl>(CopyOp) &&
14424              RD->hasUserDeclaredCopyAssignment() &&
14425              !S.getLangOpts().MSVCCompat) {
14426     // Find any user-declared move assignment operator.
14427     for (auto *I : RD->methods()) {
14428       if (I->isCopyAssignmentOperator()) {
14429         UserDeclaredOperation = I;
14430         break;
14431       }
14432     }
14433     assert(UserDeclaredOperation);
14434   }
14435 
14436   if (UserDeclaredOperation) {
14437     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14438     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14439     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14440     unsigned DiagID =
14441         (UDOIsUserProvided && UDOIsDestructor)
14442             ? diag::warn_deprecated_copy_with_user_provided_dtor
14443         : (UDOIsUserProvided && !UDOIsDestructor)
14444             ? diag::warn_deprecated_copy_with_user_provided_copy
14445         : (!UDOIsUserProvided && UDOIsDestructor)
14446             ? diag::warn_deprecated_copy_with_dtor
14447             : diag::warn_deprecated_copy;
14448     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14449         << RD << IsCopyAssignment;
14450   }
14451 }
14452 
14453 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14454                                         CXXMethodDecl *CopyAssignOperator) {
14455   assert((CopyAssignOperator->isDefaulted() &&
14456           CopyAssignOperator->isOverloadedOperator() &&
14457           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14458           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14459           !CopyAssignOperator->isDeleted()) &&
14460          "DefineImplicitCopyAssignment called for wrong function");
14461   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14462     return;
14463 
14464   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14465   if (ClassDecl->isInvalidDecl()) {
14466     CopyAssignOperator->setInvalidDecl();
14467     return;
14468   }
14469 
14470   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14471 
14472   // The exception specification is needed because we are defining the
14473   // function.
14474   ResolveExceptionSpec(CurrentLocation,
14475                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14476 
14477   // Add a context note for diagnostics produced after this point.
14478   Scope.addContextNote(CurrentLocation);
14479 
14480   // C++11 [class.copy]p18:
14481   //   The [definition of an implicitly declared copy assignment operator] is
14482   //   deprecated if the class has a user-declared copy constructor or a
14483   //   user-declared destructor.
14484   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14485     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14486 
14487   // C++0x [class.copy]p30:
14488   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14489   //   for a non-union class X performs memberwise copy assignment of its
14490   //   subobjects. The direct base classes of X are assigned first, in the
14491   //   order of their declaration in the base-specifier-list, and then the
14492   //   immediate non-static data members of X are assigned, in the order in
14493   //   which they were declared in the class definition.
14494 
14495   // The statements that form the synthesized function body.
14496   SmallVector<Stmt*, 8> Statements;
14497 
14498   // The parameter for the "other" object, which we are copying from.
14499   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14500   Qualifiers OtherQuals = Other->getType().getQualifiers();
14501   QualType OtherRefType = Other->getType();
14502   if (const LValueReferenceType *OtherRef
14503                                 = OtherRefType->getAs<LValueReferenceType>()) {
14504     OtherRefType = OtherRef->getPointeeType();
14505     OtherQuals = OtherRefType.getQualifiers();
14506   }
14507 
14508   // Our location for everything implicitly-generated.
14509   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14510                            ? CopyAssignOperator->getEndLoc()
14511                            : CopyAssignOperator->getLocation();
14512 
14513   // Builds a DeclRefExpr for the "other" object.
14514   RefBuilder OtherRef(Other, OtherRefType);
14515 
14516   // Builds the "this" pointer.
14517   ThisBuilder This;
14518 
14519   // Assign base classes.
14520   bool Invalid = false;
14521   for (auto &Base : ClassDecl->bases()) {
14522     // Form the assignment:
14523     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14524     QualType BaseType = Base.getType().getUnqualifiedType();
14525     if (!BaseType->isRecordType()) {
14526       Invalid = true;
14527       continue;
14528     }
14529 
14530     CXXCastPath BasePath;
14531     BasePath.push_back(&Base);
14532 
14533     // Construct the "from" expression, which is an implicit cast to the
14534     // appropriately-qualified base type.
14535     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14536                      VK_LValue, BasePath);
14537 
14538     // Dereference "this".
14539     DerefBuilder DerefThis(This);
14540     CastBuilder To(DerefThis,
14541                    Context.getQualifiedType(
14542                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14543                    VK_LValue, BasePath);
14544 
14545     // Build the copy.
14546     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14547                                             To, From,
14548                                             /*CopyingBaseSubobject=*/true,
14549                                             /*Copying=*/true);
14550     if (Copy.isInvalid()) {
14551       CopyAssignOperator->setInvalidDecl();
14552       return;
14553     }
14554 
14555     // Success! Record the copy.
14556     Statements.push_back(Copy.getAs<Expr>());
14557   }
14558 
14559   // Assign non-static members.
14560   for (auto *Field : ClassDecl->fields()) {
14561     // FIXME: We should form some kind of AST representation for the implied
14562     // memcpy in a union copy operation.
14563     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14564       continue;
14565 
14566     if (Field->isInvalidDecl()) {
14567       Invalid = true;
14568       continue;
14569     }
14570 
14571     // Check for members of reference type; we can't copy those.
14572     if (Field->getType()->isReferenceType()) {
14573       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14574         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14575       Diag(Field->getLocation(), diag::note_declared_at);
14576       Invalid = true;
14577       continue;
14578     }
14579 
14580     // Check for members of const-qualified, non-class type.
14581     QualType BaseType = Context.getBaseElementType(Field->getType());
14582     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14583       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14584         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14585       Diag(Field->getLocation(), diag::note_declared_at);
14586       Invalid = true;
14587       continue;
14588     }
14589 
14590     // Suppress assigning zero-width bitfields.
14591     if (Field->isZeroLengthBitField(Context))
14592       continue;
14593 
14594     QualType FieldType = Field->getType().getNonReferenceType();
14595     if (FieldType->isIncompleteArrayType()) {
14596       assert(ClassDecl->hasFlexibleArrayMember() &&
14597              "Incomplete array type is not valid");
14598       continue;
14599     }
14600 
14601     // Build references to the field in the object we're copying from and to.
14602     CXXScopeSpec SS; // Intentionally empty
14603     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14604                               LookupMemberName);
14605     MemberLookup.addDecl(Field);
14606     MemberLookup.resolveKind();
14607 
14608     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14609 
14610     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14611 
14612     // Build the copy of this field.
14613     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14614                                             To, From,
14615                                             /*CopyingBaseSubobject=*/false,
14616                                             /*Copying=*/true);
14617     if (Copy.isInvalid()) {
14618       CopyAssignOperator->setInvalidDecl();
14619       return;
14620     }
14621 
14622     // Success! Record the copy.
14623     Statements.push_back(Copy.getAs<Stmt>());
14624   }
14625 
14626   if (!Invalid) {
14627     // Add a "return *this;"
14628     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14629 
14630     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14631     if (Return.isInvalid())
14632       Invalid = true;
14633     else
14634       Statements.push_back(Return.getAs<Stmt>());
14635   }
14636 
14637   if (Invalid) {
14638     CopyAssignOperator->setInvalidDecl();
14639     return;
14640   }
14641 
14642   StmtResult Body;
14643   {
14644     CompoundScopeRAII CompoundScope(*this);
14645     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14646                              /*isStmtExpr=*/false);
14647     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14648   }
14649   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14650   CopyAssignOperator->markUsed(Context);
14651 
14652   if (ASTMutationListener *L = getASTMutationListener()) {
14653     L->CompletedImplicitDefinition(CopyAssignOperator);
14654   }
14655 }
14656 
14657 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14658   assert(ClassDecl->needsImplicitMoveAssignment());
14659 
14660   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14661   if (DSM.isAlreadyBeingDeclared())
14662     return nullptr;
14663 
14664   // Note: The following rules are largely analoguous to the move
14665   // constructor rules.
14666 
14667   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14668   LangAS AS = getDefaultCXXMethodAddrSpace();
14669   if (AS != LangAS::Default)
14670     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14671   QualType RetType = Context.getLValueReferenceType(ArgType);
14672   ArgType = Context.getRValueReferenceType(ArgType);
14673 
14674   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14675                                                      CXXMoveAssignment,
14676                                                      false);
14677 
14678   //   An implicitly-declared move assignment operator is an inline public
14679   //   member of its class.
14680   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14681   SourceLocation ClassLoc = ClassDecl->getLocation();
14682   DeclarationNameInfo NameInfo(Name, ClassLoc);
14683   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14684       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14685       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14686       getCurFPFeatures().isFPConstrained(),
14687       /*isInline=*/true,
14688       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14689       SourceLocation());
14690   MoveAssignment->setAccess(AS_public);
14691   MoveAssignment->setDefaulted();
14692   MoveAssignment->setImplicit();
14693 
14694   setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14695 
14696   if (getLangOpts().CUDA)
14697     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14698                                             MoveAssignment,
14699                                             /* ConstRHS */ false,
14700                                             /* Diagnose */ false);
14701 
14702   // Add the parameter to the operator.
14703   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14704                                                ClassLoc, ClassLoc,
14705                                                /*Id=*/nullptr, ArgType,
14706                                                /*TInfo=*/nullptr, SC_None,
14707                                                nullptr);
14708   MoveAssignment->setParams(FromParam);
14709 
14710   MoveAssignment->setTrivial(
14711     ClassDecl->needsOverloadResolutionForMoveAssignment()
14712       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14713       : ClassDecl->hasTrivialMoveAssignment());
14714 
14715   // Note that we have added this copy-assignment operator.
14716   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14717 
14718   Scope *S = getScopeForContext(ClassDecl);
14719   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14720 
14721   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14722     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14723     SetDeclDeleted(MoveAssignment, ClassLoc);
14724   }
14725 
14726   if (S)
14727     PushOnScopeChains(MoveAssignment, S, false);
14728   ClassDecl->addDecl(MoveAssignment);
14729 
14730   return MoveAssignment;
14731 }
14732 
14733 /// Check if we're implicitly defining a move assignment operator for a class
14734 /// with virtual bases. Such a move assignment might move-assign the virtual
14735 /// base multiple times.
14736 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14737                                                SourceLocation CurrentLocation) {
14738   assert(!Class->isDependentContext() && "should not define dependent move");
14739 
14740   // Only a virtual base could get implicitly move-assigned multiple times.
14741   // Only a non-trivial move assignment can observe this. We only want to
14742   // diagnose if we implicitly define an assignment operator that assigns
14743   // two base classes, both of which move-assign the same virtual base.
14744   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14745       Class->getNumBases() < 2)
14746     return;
14747 
14748   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14749   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14750   VBaseMap VBases;
14751 
14752   for (auto &BI : Class->bases()) {
14753     Worklist.push_back(&BI);
14754     while (!Worklist.empty()) {
14755       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14756       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14757 
14758       // If the base has no non-trivial move assignment operators,
14759       // we don't care about moves from it.
14760       if (!Base->hasNonTrivialMoveAssignment())
14761         continue;
14762 
14763       // If there's nothing virtual here, skip it.
14764       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14765         continue;
14766 
14767       // If we're not actually going to call a move assignment for this base,
14768       // or the selected move assignment is trivial, skip it.
14769       Sema::SpecialMemberOverloadResult SMOR =
14770         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14771                               /*ConstArg*/false, /*VolatileArg*/false,
14772                               /*RValueThis*/true, /*ConstThis*/false,
14773                               /*VolatileThis*/false);
14774       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14775           !SMOR.getMethod()->isMoveAssignmentOperator())
14776         continue;
14777 
14778       if (BaseSpec->isVirtual()) {
14779         // We're going to move-assign this virtual base, and its move
14780         // assignment operator is not trivial. If this can happen for
14781         // multiple distinct direct bases of Class, diagnose it. (If it
14782         // only happens in one base, we'll diagnose it when synthesizing
14783         // that base class's move assignment operator.)
14784         CXXBaseSpecifier *&Existing =
14785             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14786                 .first->second;
14787         if (Existing && Existing != &BI) {
14788           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14789             << Class << Base;
14790           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14791               << (Base->getCanonicalDecl() ==
14792                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14793               << Base << Existing->getType() << Existing->getSourceRange();
14794           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14795               << (Base->getCanonicalDecl() ==
14796                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14797               << Base << BI.getType() << BaseSpec->getSourceRange();
14798 
14799           // Only diagnose each vbase once.
14800           Existing = nullptr;
14801         }
14802       } else {
14803         // Only walk over bases that have defaulted move assignment operators.
14804         // We assume that any user-provided move assignment operator handles
14805         // the multiple-moves-of-vbase case itself somehow.
14806         if (!SMOR.getMethod()->isDefaulted())
14807           continue;
14808 
14809         // We're going to move the base classes of Base. Add them to the list.
14810         llvm::append_range(Worklist, llvm::make_pointer_range(Base->bases()));
14811       }
14812     }
14813   }
14814 }
14815 
14816 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14817                                         CXXMethodDecl *MoveAssignOperator) {
14818   assert((MoveAssignOperator->isDefaulted() &&
14819           MoveAssignOperator->isOverloadedOperator() &&
14820           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14821           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14822           !MoveAssignOperator->isDeleted()) &&
14823          "DefineImplicitMoveAssignment called for wrong function");
14824   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14825     return;
14826 
14827   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14828   if (ClassDecl->isInvalidDecl()) {
14829     MoveAssignOperator->setInvalidDecl();
14830     return;
14831   }
14832 
14833   // C++0x [class.copy]p28:
14834   //   The implicitly-defined or move assignment operator for a non-union class
14835   //   X performs memberwise move assignment of its subobjects. The direct base
14836   //   classes of X are assigned first, in the order of their declaration in the
14837   //   base-specifier-list, and then the immediate non-static data members of X
14838   //   are assigned, in the order in which they were declared in the class
14839   //   definition.
14840 
14841   // Issue a warning if our implicit move assignment operator will move
14842   // from a virtual base more than once.
14843   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14844 
14845   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14846 
14847   // The exception specification is needed because we are defining the
14848   // function.
14849   ResolveExceptionSpec(CurrentLocation,
14850                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14851 
14852   // Add a context note for diagnostics produced after this point.
14853   Scope.addContextNote(CurrentLocation);
14854 
14855   // The statements that form the synthesized function body.
14856   SmallVector<Stmt*, 8> Statements;
14857 
14858   // The parameter for the "other" object, which we are move from.
14859   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14860   QualType OtherRefType =
14861       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14862 
14863   // Our location for everything implicitly-generated.
14864   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14865                            ? MoveAssignOperator->getEndLoc()
14866                            : MoveAssignOperator->getLocation();
14867 
14868   // Builds a reference to the "other" object.
14869   RefBuilder OtherRef(Other, OtherRefType);
14870   // Cast to rvalue.
14871   MoveCastBuilder MoveOther(OtherRef);
14872 
14873   // Builds the "this" pointer.
14874   ThisBuilder This;
14875 
14876   // Assign base classes.
14877   bool Invalid = false;
14878   for (auto &Base : ClassDecl->bases()) {
14879     // C++11 [class.copy]p28:
14880     //   It is unspecified whether subobjects representing virtual base classes
14881     //   are assigned more than once by the implicitly-defined copy assignment
14882     //   operator.
14883     // FIXME: Do not assign to a vbase that will be assigned by some other base
14884     // class. For a move-assignment, this can result in the vbase being moved
14885     // multiple times.
14886 
14887     // Form the assignment:
14888     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14889     QualType BaseType = Base.getType().getUnqualifiedType();
14890     if (!BaseType->isRecordType()) {
14891       Invalid = true;
14892       continue;
14893     }
14894 
14895     CXXCastPath BasePath;
14896     BasePath.push_back(&Base);
14897 
14898     // Construct the "from" expression, which is an implicit cast to the
14899     // appropriately-qualified base type.
14900     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14901 
14902     // Dereference "this".
14903     DerefBuilder DerefThis(This);
14904 
14905     // Implicitly cast "this" to the appropriately-qualified base type.
14906     CastBuilder To(DerefThis,
14907                    Context.getQualifiedType(
14908                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14909                    VK_LValue, BasePath);
14910 
14911     // Build the move.
14912     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14913                                             To, From,
14914                                             /*CopyingBaseSubobject=*/true,
14915                                             /*Copying=*/false);
14916     if (Move.isInvalid()) {
14917       MoveAssignOperator->setInvalidDecl();
14918       return;
14919     }
14920 
14921     // Success! Record the move.
14922     Statements.push_back(Move.getAs<Expr>());
14923   }
14924 
14925   // Assign non-static members.
14926   for (auto *Field : ClassDecl->fields()) {
14927     // FIXME: We should form some kind of AST representation for the implied
14928     // memcpy in a union copy operation.
14929     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14930       continue;
14931 
14932     if (Field->isInvalidDecl()) {
14933       Invalid = true;
14934       continue;
14935     }
14936 
14937     // Check for members of reference type; we can't move those.
14938     if (Field->getType()->isReferenceType()) {
14939       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14940         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14941       Diag(Field->getLocation(), diag::note_declared_at);
14942       Invalid = true;
14943       continue;
14944     }
14945 
14946     // Check for members of const-qualified, non-class type.
14947     QualType BaseType = Context.getBaseElementType(Field->getType());
14948     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14949       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14950         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14951       Diag(Field->getLocation(), diag::note_declared_at);
14952       Invalid = true;
14953       continue;
14954     }
14955 
14956     // Suppress assigning zero-width bitfields.
14957     if (Field->isZeroLengthBitField(Context))
14958       continue;
14959 
14960     QualType FieldType = Field->getType().getNonReferenceType();
14961     if (FieldType->isIncompleteArrayType()) {
14962       assert(ClassDecl->hasFlexibleArrayMember() &&
14963              "Incomplete array type is not valid");
14964       continue;
14965     }
14966 
14967     // Build references to the field in the object we're copying from and to.
14968     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14969                               LookupMemberName);
14970     MemberLookup.addDecl(Field);
14971     MemberLookup.resolveKind();
14972     MemberBuilder From(MoveOther, OtherRefType,
14973                        /*IsArrow=*/false, MemberLookup);
14974     MemberBuilder To(This, getCurrentThisType(),
14975                      /*IsArrow=*/true, MemberLookup);
14976 
14977     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14978         "Member reference with rvalue base must be rvalue except for reference "
14979         "members, which aren't allowed for move assignment.");
14980 
14981     // Build the move of this field.
14982     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14983                                             To, From,
14984                                             /*CopyingBaseSubobject=*/false,
14985                                             /*Copying=*/false);
14986     if (Move.isInvalid()) {
14987       MoveAssignOperator->setInvalidDecl();
14988       return;
14989     }
14990 
14991     // Success! Record the copy.
14992     Statements.push_back(Move.getAs<Stmt>());
14993   }
14994 
14995   if (!Invalid) {
14996     // Add a "return *this;"
14997     ExprResult ThisObj =
14998         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14999 
15000     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
15001     if (Return.isInvalid())
15002       Invalid = true;
15003     else
15004       Statements.push_back(Return.getAs<Stmt>());
15005   }
15006 
15007   if (Invalid) {
15008     MoveAssignOperator->setInvalidDecl();
15009     return;
15010   }
15011 
15012   StmtResult Body;
15013   {
15014     CompoundScopeRAII CompoundScope(*this);
15015     Body = ActOnCompoundStmt(Loc, Loc, Statements,
15016                              /*isStmtExpr=*/false);
15017     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15018   }
15019   MoveAssignOperator->setBody(Body.getAs<Stmt>());
15020   MoveAssignOperator->markUsed(Context);
15021 
15022   if (ASTMutationListener *L = getASTMutationListener()) {
15023     L->CompletedImplicitDefinition(MoveAssignOperator);
15024   }
15025 }
15026 
15027 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15028                                                     CXXRecordDecl *ClassDecl) {
15029   // C++ [class.copy]p4:
15030   //   If the class definition does not explicitly declare a copy
15031   //   constructor, one is declared implicitly.
15032   assert(ClassDecl->needsImplicitCopyConstructor());
15033 
15034   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
15035   if (DSM.isAlreadyBeingDeclared())
15036     return nullptr;
15037 
15038   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15039   QualType ArgType = ClassType;
15040   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15041   if (Const)
15042     ArgType = ArgType.withConst();
15043 
15044   LangAS AS = getDefaultCXXMethodAddrSpace();
15045   if (AS != LangAS::Default)
15046     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
15047 
15048   ArgType = Context.getLValueReferenceType(ArgType);
15049 
15050   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15051                                                      CXXCopyConstructor,
15052                                                      Const);
15053 
15054   DeclarationName Name
15055     = Context.DeclarationNames.getCXXConstructorName(
15056                                            Context.getCanonicalType(ClassType));
15057   SourceLocation ClassLoc = ClassDecl->getLocation();
15058   DeclarationNameInfo NameInfo(Name, ClassLoc);
15059 
15060   //   An implicitly-declared copy constructor is an inline public
15061   //   member of its class.
15062   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15063       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15064       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15065       /*isInline=*/true,
15066       /*isImplicitlyDeclared=*/true,
15067       Constexpr ? ConstexprSpecKind::Constexpr
15068                 : ConstexprSpecKind::Unspecified);
15069   CopyConstructor->setAccess(AS_public);
15070   CopyConstructor->setDefaulted();
15071 
15072   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15073 
15074   if (getLangOpts().CUDA)
15075     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15076                                             CopyConstructor,
15077                                             /* ConstRHS */ Const,
15078                                             /* Diagnose */ false);
15079 
15080   // During template instantiation of special member functions we need a
15081   // reliable TypeSourceInfo for the parameter types in order to allow functions
15082   // to be substituted.
15083   TypeSourceInfo *TSI = nullptr;
15084   if (inTemplateInstantiation() && ClassDecl->isLambda())
15085     TSI = Context.getTrivialTypeSourceInfo(ArgType);
15086 
15087   // Add the parameter to the constructor.
15088   ParmVarDecl *FromParam =
15089       ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15090                           /*IdentifierInfo=*/nullptr, ArgType,
15091                           /*TInfo=*/TSI, SC_None, nullptr);
15092   CopyConstructor->setParams(FromParam);
15093 
15094   CopyConstructor->setTrivial(
15095       ClassDecl->needsOverloadResolutionForCopyConstructor()
15096           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15097           : ClassDecl->hasTrivialCopyConstructor());
15098 
15099   CopyConstructor->setTrivialForCall(
15100       ClassDecl->hasAttr<TrivialABIAttr>() ||
15101       (ClassDecl->needsOverloadResolutionForCopyConstructor()
15102            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15103              TAH_ConsiderTrivialABI)
15104            : ClassDecl->hasTrivialCopyConstructorForCall()));
15105 
15106   // Note that we have declared this constructor.
15107   ++getASTContext().NumImplicitCopyConstructorsDeclared;
15108 
15109   Scope *S = getScopeForContext(ClassDecl);
15110   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15111 
15112   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15113     ClassDecl->setImplicitCopyConstructorIsDeleted();
15114     SetDeclDeleted(CopyConstructor, ClassLoc);
15115   }
15116 
15117   if (S)
15118     PushOnScopeChains(CopyConstructor, S, false);
15119   ClassDecl->addDecl(CopyConstructor);
15120 
15121   return CopyConstructor;
15122 }
15123 
15124 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15125                                          CXXConstructorDecl *CopyConstructor) {
15126   assert((CopyConstructor->isDefaulted() &&
15127           CopyConstructor->isCopyConstructor() &&
15128           !CopyConstructor->doesThisDeclarationHaveABody() &&
15129           !CopyConstructor->isDeleted()) &&
15130          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15131   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15132     return;
15133 
15134   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15135   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15136 
15137   SynthesizedFunctionScope Scope(*this, CopyConstructor);
15138 
15139   // The exception specification is needed because we are defining the
15140   // function.
15141   ResolveExceptionSpec(CurrentLocation,
15142                        CopyConstructor->getType()->castAs<FunctionProtoType>());
15143   MarkVTableUsed(CurrentLocation, ClassDecl);
15144 
15145   // Add a context note for diagnostics produced after this point.
15146   Scope.addContextNote(CurrentLocation);
15147 
15148   // C++11 [class.copy]p7:
15149   //   The [definition of an implicitly declared copy constructor] is
15150   //   deprecated if the class has a user-declared copy assignment operator
15151   //   or a user-declared destructor.
15152   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15153     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15154 
15155   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15156     CopyConstructor->setInvalidDecl();
15157   }  else {
15158     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15159                              ? CopyConstructor->getEndLoc()
15160                              : CopyConstructor->getLocation();
15161     Sema::CompoundScopeRAII CompoundScope(*this);
15162     CopyConstructor->setBody(
15163         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
15164     CopyConstructor->markUsed(Context);
15165   }
15166 
15167   if (ASTMutationListener *L = getASTMutationListener()) {
15168     L->CompletedImplicitDefinition(CopyConstructor);
15169   }
15170 }
15171 
15172 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15173                                                     CXXRecordDecl *ClassDecl) {
15174   assert(ClassDecl->needsImplicitMoveConstructor());
15175 
15176   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15177   if (DSM.isAlreadyBeingDeclared())
15178     return nullptr;
15179 
15180   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15181 
15182   QualType ArgType = ClassType;
15183   LangAS AS = getDefaultCXXMethodAddrSpace();
15184   if (AS != LangAS::Default)
15185     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15186   ArgType = Context.getRValueReferenceType(ArgType);
15187 
15188   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15189                                                      CXXMoveConstructor,
15190                                                      false);
15191 
15192   DeclarationName Name
15193     = Context.DeclarationNames.getCXXConstructorName(
15194                                            Context.getCanonicalType(ClassType));
15195   SourceLocation ClassLoc = ClassDecl->getLocation();
15196   DeclarationNameInfo NameInfo(Name, ClassLoc);
15197 
15198   // C++11 [class.copy]p11:
15199   //   An implicitly-declared copy/move constructor is an inline public
15200   //   member of its class.
15201   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15202       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15203       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15204       /*isInline=*/true,
15205       /*isImplicitlyDeclared=*/true,
15206       Constexpr ? ConstexprSpecKind::Constexpr
15207                 : ConstexprSpecKind::Unspecified);
15208   MoveConstructor->setAccess(AS_public);
15209   MoveConstructor->setDefaulted();
15210 
15211   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15212 
15213   if (getLangOpts().CUDA)
15214     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15215                                             MoveConstructor,
15216                                             /* ConstRHS */ false,
15217                                             /* Diagnose */ false);
15218 
15219   // Add the parameter to the constructor.
15220   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15221                                                ClassLoc, ClassLoc,
15222                                                /*IdentifierInfo=*/nullptr,
15223                                                ArgType, /*TInfo=*/nullptr,
15224                                                SC_None, nullptr);
15225   MoveConstructor->setParams(FromParam);
15226 
15227   MoveConstructor->setTrivial(
15228       ClassDecl->needsOverloadResolutionForMoveConstructor()
15229           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15230           : ClassDecl->hasTrivialMoveConstructor());
15231 
15232   MoveConstructor->setTrivialForCall(
15233       ClassDecl->hasAttr<TrivialABIAttr>() ||
15234       (ClassDecl->needsOverloadResolutionForMoveConstructor()
15235            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15236                                     TAH_ConsiderTrivialABI)
15237            : ClassDecl->hasTrivialMoveConstructorForCall()));
15238 
15239   // Note that we have declared this constructor.
15240   ++getASTContext().NumImplicitMoveConstructorsDeclared;
15241 
15242   Scope *S = getScopeForContext(ClassDecl);
15243   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15244 
15245   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15246     ClassDecl->setImplicitMoveConstructorIsDeleted();
15247     SetDeclDeleted(MoveConstructor, ClassLoc);
15248   }
15249 
15250   if (S)
15251     PushOnScopeChains(MoveConstructor, S, false);
15252   ClassDecl->addDecl(MoveConstructor);
15253 
15254   return MoveConstructor;
15255 }
15256 
15257 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15258                                          CXXConstructorDecl *MoveConstructor) {
15259   assert((MoveConstructor->isDefaulted() &&
15260           MoveConstructor->isMoveConstructor() &&
15261           !MoveConstructor->doesThisDeclarationHaveABody() &&
15262           !MoveConstructor->isDeleted()) &&
15263          "DefineImplicitMoveConstructor - call it for implicit move ctor");
15264   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15265     return;
15266 
15267   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15268   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15269 
15270   SynthesizedFunctionScope Scope(*this, MoveConstructor);
15271 
15272   // The exception specification is needed because we are defining the
15273   // function.
15274   ResolveExceptionSpec(CurrentLocation,
15275                        MoveConstructor->getType()->castAs<FunctionProtoType>());
15276   MarkVTableUsed(CurrentLocation, ClassDecl);
15277 
15278   // Add a context note for diagnostics produced after this point.
15279   Scope.addContextNote(CurrentLocation);
15280 
15281   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15282     MoveConstructor->setInvalidDecl();
15283   } else {
15284     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15285                              ? MoveConstructor->getEndLoc()
15286                              : MoveConstructor->getLocation();
15287     Sema::CompoundScopeRAII CompoundScope(*this);
15288     MoveConstructor->setBody(ActOnCompoundStmt(
15289         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
15290     MoveConstructor->markUsed(Context);
15291   }
15292 
15293   if (ASTMutationListener *L = getASTMutationListener()) {
15294     L->CompletedImplicitDefinition(MoveConstructor);
15295   }
15296 }
15297 
15298 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15299   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15300 }
15301 
15302 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15303                             SourceLocation CurrentLocation,
15304                             CXXConversionDecl *Conv) {
15305   SynthesizedFunctionScope Scope(*this, Conv);
15306   assert(!Conv->getReturnType()->isUndeducedType());
15307 
15308   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15309   CallingConv CC =
15310       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15311 
15312   CXXRecordDecl *Lambda = Conv->getParent();
15313   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15314   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
15315 
15316   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15317     CallOp = InstantiateFunctionDeclaration(
15318         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15319     if (!CallOp)
15320       return;
15321 
15322     Invoker = InstantiateFunctionDeclaration(
15323         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15324     if (!Invoker)
15325       return;
15326   }
15327 
15328   if (CallOp->isInvalidDecl())
15329     return;
15330 
15331   // Mark the call operator referenced (and add to pending instantiations
15332   // if necessary).
15333   // For both the conversion and static-invoker template specializations
15334   // we construct their body's in this function, so no need to add them
15335   // to the PendingInstantiations.
15336   MarkFunctionReferenced(CurrentLocation, CallOp);
15337 
15338   // Fill in the __invoke function with a dummy implementation. IR generation
15339   // will fill in the actual details. Update its type in case it contained
15340   // an 'auto'.
15341   Invoker->markUsed(Context);
15342   Invoker->setReferenced();
15343   Invoker->setType(Conv->getReturnType()->getPointeeType());
15344   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15345 
15346   // Construct the body of the conversion function { return __invoke; }.
15347   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
15348                                        VK_LValue, Conv->getLocation());
15349   assert(FunctionRef && "Can't refer to __invoke function?");
15350   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15351   Conv->setBody(CompoundStmt::Create(Context, Return, FPOptionsOverride(),
15352                                      Conv->getLocation(), Conv->getLocation()));
15353   Conv->markUsed(Context);
15354   Conv->setReferenced();
15355 
15356   if (ASTMutationListener *L = getASTMutationListener()) {
15357     L->CompletedImplicitDefinition(Conv);
15358     L->CompletedImplicitDefinition(Invoker);
15359   }
15360 }
15361 
15362 
15363 
15364 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15365        SourceLocation CurrentLocation,
15366        CXXConversionDecl *Conv)
15367 {
15368   assert(!Conv->getParent()->isGenericLambda());
15369 
15370   SynthesizedFunctionScope Scope(*this, Conv);
15371 
15372   // Copy-initialize the lambda object as needed to capture it.
15373   Expr *This = ActOnCXXThis(CurrentLocation).get();
15374   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15375 
15376   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15377                                                         Conv->getLocation(),
15378                                                         Conv, DerefThis);
15379 
15380   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15381   // behavior.  Note that only the general conversion function does this
15382   // (since it's unusable otherwise); in the case where we inline the
15383   // block literal, it has block literal lifetime semantics.
15384   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15385     BuildBlock = ImplicitCastExpr::Create(
15386         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15387         BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15388 
15389   if (BuildBlock.isInvalid()) {
15390     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15391     Conv->setInvalidDecl();
15392     return;
15393   }
15394 
15395   // Create the return statement that returns the block from the conversion
15396   // function.
15397   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15398   if (Return.isInvalid()) {
15399     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15400     Conv->setInvalidDecl();
15401     return;
15402   }
15403 
15404   // Set the body of the conversion function.
15405   Stmt *ReturnS = Return.get();
15406   Conv->setBody(CompoundStmt::Create(Context, ReturnS, FPOptionsOverride(),
15407                                      Conv->getLocation(), Conv->getLocation()));
15408   Conv->markUsed(Context);
15409 
15410   // We're done; notify the mutation listener, if any.
15411   if (ASTMutationListener *L = getASTMutationListener()) {
15412     L->CompletedImplicitDefinition(Conv);
15413   }
15414 }
15415 
15416 /// Determine whether the given list arguments contains exactly one
15417 /// "real" (non-default) argument.
15418 static bool hasOneRealArgument(MultiExprArg Args) {
15419   switch (Args.size()) {
15420   case 0:
15421     return false;
15422 
15423   default:
15424     if (!Args[1]->isDefaultArgument())
15425       return false;
15426 
15427     LLVM_FALLTHROUGH;
15428   case 1:
15429     return !Args[0]->isDefaultArgument();
15430   }
15431 
15432   return false;
15433 }
15434 
15435 ExprResult
15436 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15437                             NamedDecl *FoundDecl,
15438                             CXXConstructorDecl *Constructor,
15439                             MultiExprArg ExprArgs,
15440                             bool HadMultipleCandidates,
15441                             bool IsListInitialization,
15442                             bool IsStdInitListInitialization,
15443                             bool RequiresZeroInit,
15444                             unsigned ConstructKind,
15445                             SourceRange ParenRange) {
15446   bool Elidable = false;
15447 
15448   // C++0x [class.copy]p34:
15449   //   When certain criteria are met, an implementation is allowed to
15450   //   omit the copy/move construction of a class object, even if the
15451   //   copy/move constructor and/or destructor for the object have
15452   //   side effects. [...]
15453   //     - when a temporary class object that has not been bound to a
15454   //       reference (12.2) would be copied/moved to a class object
15455   //       with the same cv-unqualified type, the copy/move operation
15456   //       can be omitted by constructing the temporary object
15457   //       directly into the target of the omitted copy/move
15458   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15459       // FIXME: Converting constructors should also be accepted.
15460       // But to fix this, the logic that digs down into a CXXConstructExpr
15461       // to find the source object needs to handle it.
15462       // Right now it assumes the source object is passed directly as the
15463       // first argument.
15464       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15465     Expr *SubExpr = ExprArgs[0];
15466     // FIXME: Per above, this is also incorrect if we want to accept
15467     //        converting constructors, as isTemporaryObject will
15468     //        reject temporaries with different type from the
15469     //        CXXRecord itself.
15470     Elidable = SubExpr->isTemporaryObject(
15471         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15472   }
15473 
15474   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15475                                FoundDecl, Constructor,
15476                                Elidable, ExprArgs, HadMultipleCandidates,
15477                                IsListInitialization,
15478                                IsStdInitListInitialization, RequiresZeroInit,
15479                                ConstructKind, ParenRange);
15480 }
15481 
15482 ExprResult
15483 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15484                             NamedDecl *FoundDecl,
15485                             CXXConstructorDecl *Constructor,
15486                             bool Elidable,
15487                             MultiExprArg ExprArgs,
15488                             bool HadMultipleCandidates,
15489                             bool IsListInitialization,
15490                             bool IsStdInitListInitialization,
15491                             bool RequiresZeroInit,
15492                             unsigned ConstructKind,
15493                             SourceRange ParenRange) {
15494   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15495     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15496     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15497       return ExprError();
15498   }
15499 
15500   return BuildCXXConstructExpr(
15501       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15502       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15503       RequiresZeroInit, ConstructKind, ParenRange);
15504 }
15505 
15506 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15507 /// including handling of its default argument expressions.
15508 ExprResult
15509 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15510                             CXXConstructorDecl *Constructor,
15511                             bool Elidable,
15512                             MultiExprArg ExprArgs,
15513                             bool HadMultipleCandidates,
15514                             bool IsListInitialization,
15515                             bool IsStdInitListInitialization,
15516                             bool RequiresZeroInit,
15517                             unsigned ConstructKind,
15518                             SourceRange ParenRange) {
15519   assert(declaresSameEntity(
15520              Constructor->getParent(),
15521              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15522          "given constructor for wrong type");
15523   MarkFunctionReferenced(ConstructLoc, Constructor);
15524   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15525     return ExprError();
15526   if (getLangOpts().SYCLIsDevice &&
15527       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15528     return ExprError();
15529 
15530   return CheckForImmediateInvocation(
15531       CXXConstructExpr::Create(
15532           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15533           HadMultipleCandidates, IsListInitialization,
15534           IsStdInitListInitialization, RequiresZeroInit,
15535           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15536           ParenRange),
15537       Constructor);
15538 }
15539 
15540 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15541   assert(Field->hasInClassInitializer());
15542 
15543   // If we already have the in-class initializer nothing needs to be done.
15544   if (Field->getInClassInitializer())
15545     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15546 
15547   // If we might have already tried and failed to instantiate, don't try again.
15548   if (Field->isInvalidDecl())
15549     return ExprError();
15550 
15551   // Maybe we haven't instantiated the in-class initializer. Go check the
15552   // pattern FieldDecl to see if it has one.
15553   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15554 
15555   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15556     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15557     DeclContext::lookup_result Lookup =
15558         ClassPattern->lookup(Field->getDeclName());
15559 
15560     FieldDecl *Pattern = nullptr;
15561     for (auto L : Lookup) {
15562       if (isa<FieldDecl>(L)) {
15563         Pattern = cast<FieldDecl>(L);
15564         break;
15565       }
15566     }
15567     assert(Pattern && "We must have set the Pattern!");
15568 
15569     if (!Pattern->hasInClassInitializer() ||
15570         InstantiateInClassInitializer(Loc, Field, Pattern,
15571                                       getTemplateInstantiationArgs(Field))) {
15572       // Don't diagnose this again.
15573       Field->setInvalidDecl();
15574       return ExprError();
15575     }
15576     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15577   }
15578 
15579   // DR1351:
15580   //   If the brace-or-equal-initializer of a non-static data member
15581   //   invokes a defaulted default constructor of its class or of an
15582   //   enclosing class in a potentially evaluated subexpression, the
15583   //   program is ill-formed.
15584   //
15585   // This resolution is unworkable: the exception specification of the
15586   // default constructor can be needed in an unevaluated context, in
15587   // particular, in the operand of a noexcept-expression, and we can be
15588   // unable to compute an exception specification for an enclosed class.
15589   //
15590   // Any attempt to resolve the exception specification of a defaulted default
15591   // constructor before the initializer is lexically complete will ultimately
15592   // come here at which point we can diagnose it.
15593   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15594   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15595       << OutermostClass << Field;
15596   Diag(Field->getEndLoc(),
15597        diag::note_default_member_initializer_not_yet_parsed);
15598   // Recover by marking the field invalid, unless we're in a SFINAE context.
15599   if (!isSFINAEContext())
15600     Field->setInvalidDecl();
15601   return ExprError();
15602 }
15603 
15604 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15605   if (VD->isInvalidDecl()) return;
15606   // If initializing the variable failed, don't also diagnose problems with
15607   // the destructor, they're likely related.
15608   if (VD->getInit() && VD->getInit()->containsErrors())
15609     return;
15610 
15611   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15612   if (ClassDecl->isInvalidDecl()) return;
15613   if (ClassDecl->hasIrrelevantDestructor()) return;
15614   if (ClassDecl->isDependentContext()) return;
15615 
15616   if (VD->isNoDestroy(getASTContext()))
15617     return;
15618 
15619   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15620 
15621   // If this is an array, we'll require the destructor during initialization, so
15622   // we can skip over this. We still want to emit exit-time destructor warnings
15623   // though.
15624   if (!VD->getType()->isArrayType()) {
15625     MarkFunctionReferenced(VD->getLocation(), Destructor);
15626     CheckDestructorAccess(VD->getLocation(), Destructor,
15627                           PDiag(diag::err_access_dtor_var)
15628                               << VD->getDeclName() << VD->getType());
15629     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15630   }
15631 
15632   if (Destructor->isTrivial()) return;
15633 
15634   // If the destructor is constexpr, check whether the variable has constant
15635   // destruction now.
15636   if (Destructor->isConstexpr()) {
15637     bool HasConstantInit = false;
15638     if (VD->getInit() && !VD->getInit()->isValueDependent())
15639       HasConstantInit = VD->evaluateValue();
15640     SmallVector<PartialDiagnosticAt, 8> Notes;
15641     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15642         HasConstantInit) {
15643       Diag(VD->getLocation(),
15644            diag::err_constexpr_var_requires_const_destruction) << VD;
15645       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15646         Diag(Notes[I].first, Notes[I].second);
15647     }
15648   }
15649 
15650   if (!VD->hasGlobalStorage()) return;
15651 
15652   // Emit warning for non-trivial dtor in global scope (a real global,
15653   // class-static, function-static).
15654   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15655 
15656   // TODO: this should be re-enabled for static locals by !CXAAtExit
15657   if (!VD->isStaticLocal())
15658     Diag(VD->getLocation(), diag::warn_global_destructor);
15659 }
15660 
15661 /// Given a constructor and the set of arguments provided for the
15662 /// constructor, convert the arguments and add any required default arguments
15663 /// to form a proper call to this constructor.
15664 ///
15665 /// \returns true if an error occurred, false otherwise.
15666 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15667                                    QualType DeclInitType, MultiExprArg ArgsPtr,
15668                                    SourceLocation Loc,
15669                                    SmallVectorImpl<Expr *> &ConvertedArgs,
15670                                    bool AllowExplicit,
15671                                    bool IsListInitialization) {
15672   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15673   unsigned NumArgs = ArgsPtr.size();
15674   Expr **Args = ArgsPtr.data();
15675 
15676   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15677   unsigned NumParams = Proto->getNumParams();
15678 
15679   // If too few arguments are available, we'll fill in the rest with defaults.
15680   if (NumArgs < NumParams)
15681     ConvertedArgs.reserve(NumParams);
15682   else
15683     ConvertedArgs.reserve(NumArgs);
15684 
15685   VariadicCallType CallType =
15686     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15687   SmallVector<Expr *, 8> AllArgs;
15688   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15689                                         Proto, 0,
15690                                         llvm::makeArrayRef(Args, NumArgs),
15691                                         AllArgs,
15692                                         CallType, AllowExplicit,
15693                                         IsListInitialization);
15694   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15695 
15696   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15697 
15698   CheckConstructorCall(Constructor, DeclInitType,
15699                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15700                        Proto, Loc);
15701 
15702   return Invalid;
15703 }
15704 
15705 static inline bool
15706 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15707                                        const FunctionDecl *FnDecl) {
15708   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15709   if (isa<NamespaceDecl>(DC)) {
15710     return SemaRef.Diag(FnDecl->getLocation(),
15711                         diag::err_operator_new_delete_declared_in_namespace)
15712       << FnDecl->getDeclName();
15713   }
15714 
15715   if (isa<TranslationUnitDecl>(DC) &&
15716       FnDecl->getStorageClass() == SC_Static) {
15717     return SemaRef.Diag(FnDecl->getLocation(),
15718                         diag::err_operator_new_delete_declared_static)
15719       << FnDecl->getDeclName();
15720   }
15721 
15722   return false;
15723 }
15724 
15725 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15726                                              const PointerType *PtrTy) {
15727   auto &Ctx = SemaRef.Context;
15728   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15729   PtrQuals.removeAddressSpace();
15730   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15731       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15732 }
15733 
15734 static inline bool
15735 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15736                             CanQualType ExpectedResultType,
15737                             CanQualType ExpectedFirstParamType,
15738                             unsigned DependentParamTypeDiag,
15739                             unsigned InvalidParamTypeDiag) {
15740   QualType ResultType =
15741       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15742 
15743   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15744     // The operator is valid on any address space for OpenCL.
15745     // Drop address space from actual and expected result types.
15746     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15747       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15748 
15749     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15750       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15751   }
15752 
15753   // Check that the result type is what we expect.
15754   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15755     // Reject even if the type is dependent; an operator delete function is
15756     // required to have a non-dependent result type.
15757     return SemaRef.Diag(
15758                FnDecl->getLocation(),
15759                ResultType->isDependentType()
15760                    ? diag::err_operator_new_delete_dependent_result_type
15761                    : diag::err_operator_new_delete_invalid_result_type)
15762            << FnDecl->getDeclName() << ExpectedResultType;
15763   }
15764 
15765   // A function template must have at least 2 parameters.
15766   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15767     return SemaRef.Diag(FnDecl->getLocation(),
15768                       diag::err_operator_new_delete_template_too_few_parameters)
15769         << FnDecl->getDeclName();
15770 
15771   // The function decl must have at least 1 parameter.
15772   if (FnDecl->getNumParams() == 0)
15773     return SemaRef.Diag(FnDecl->getLocation(),
15774                         diag::err_operator_new_delete_too_few_parameters)
15775       << FnDecl->getDeclName();
15776 
15777   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15778   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15779     // The operator is valid on any address space for OpenCL.
15780     // Drop address space from actual and expected first parameter types.
15781     if (const auto *PtrTy =
15782             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15783       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15784 
15785     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15786       ExpectedFirstParamType =
15787           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15788   }
15789 
15790   // Check that the first parameter type is what we expect.
15791   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15792       ExpectedFirstParamType) {
15793     // The first parameter type is not allowed to be dependent. As a tentative
15794     // DR resolution, we allow a dependent parameter type if it is the right
15795     // type anyway, to allow destroying operator delete in class templates.
15796     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15797                                                    ? DependentParamTypeDiag
15798                                                    : InvalidParamTypeDiag)
15799            << FnDecl->getDeclName() << ExpectedFirstParamType;
15800   }
15801 
15802   return false;
15803 }
15804 
15805 static bool
15806 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15807   // C++ [basic.stc.dynamic.allocation]p1:
15808   //   A program is ill-formed if an allocation function is declared in a
15809   //   namespace scope other than global scope or declared static in global
15810   //   scope.
15811   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15812     return true;
15813 
15814   CanQualType SizeTy =
15815     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15816 
15817   // C++ [basic.stc.dynamic.allocation]p1:
15818   //  The return type shall be void*. The first parameter shall have type
15819   //  std::size_t.
15820   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15821                                   SizeTy,
15822                                   diag::err_operator_new_dependent_param_type,
15823                                   diag::err_operator_new_param_type))
15824     return true;
15825 
15826   // C++ [basic.stc.dynamic.allocation]p1:
15827   //  The first parameter shall not have an associated default argument.
15828   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15829     return SemaRef.Diag(FnDecl->getLocation(),
15830                         diag::err_operator_new_default_arg)
15831       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15832 
15833   return false;
15834 }
15835 
15836 static bool
15837 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15838   // C++ [basic.stc.dynamic.deallocation]p1:
15839   //   A program is ill-formed if deallocation functions are declared in a
15840   //   namespace scope other than global scope or declared static in global
15841   //   scope.
15842   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15843     return true;
15844 
15845   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15846 
15847   // C++ P0722:
15848   //   Within a class C, the first parameter of a destroying operator delete
15849   //   shall be of type C *. The first parameter of any other deallocation
15850   //   function shall be of type void *.
15851   CanQualType ExpectedFirstParamType =
15852       MD && MD->isDestroyingOperatorDelete()
15853           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15854                 SemaRef.Context.getRecordType(MD->getParent())))
15855           : SemaRef.Context.VoidPtrTy;
15856 
15857   // C++ [basic.stc.dynamic.deallocation]p2:
15858   //   Each deallocation function shall return void
15859   if (CheckOperatorNewDeleteTypes(
15860           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15861           diag::err_operator_delete_dependent_param_type,
15862           diag::err_operator_delete_param_type))
15863     return true;
15864 
15865   // C++ P0722:
15866   //   A destroying operator delete shall be a usual deallocation function.
15867   if (MD && !MD->getParent()->isDependentContext() &&
15868       MD->isDestroyingOperatorDelete() &&
15869       !SemaRef.isUsualDeallocationFunction(MD)) {
15870     SemaRef.Diag(MD->getLocation(),
15871                  diag::err_destroying_operator_delete_not_usual);
15872     return true;
15873   }
15874 
15875   return false;
15876 }
15877 
15878 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15879 /// of this overloaded operator is well-formed. If so, returns false;
15880 /// otherwise, emits appropriate diagnostics and returns true.
15881 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15882   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15883          "Expected an overloaded operator declaration");
15884 
15885   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15886 
15887   // C++ [over.oper]p5:
15888   //   The allocation and deallocation functions, operator new,
15889   //   operator new[], operator delete and operator delete[], are
15890   //   described completely in 3.7.3. The attributes and restrictions
15891   //   found in the rest of this subclause do not apply to them unless
15892   //   explicitly stated in 3.7.3.
15893   if (Op == OO_Delete || Op == OO_Array_Delete)
15894     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15895 
15896   if (Op == OO_New || Op == OO_Array_New)
15897     return CheckOperatorNewDeclaration(*this, FnDecl);
15898 
15899   // C++ [over.oper]p6:
15900   //   An operator function shall either be a non-static member
15901   //   function or be a non-member function and have at least one
15902   //   parameter whose type is a class, a reference to a class, an
15903   //   enumeration, or a reference to an enumeration.
15904   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15905     if (MethodDecl->isStatic())
15906       return Diag(FnDecl->getLocation(),
15907                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15908   } else {
15909     bool ClassOrEnumParam = false;
15910     for (auto Param : FnDecl->parameters()) {
15911       QualType ParamType = Param->getType().getNonReferenceType();
15912       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15913           ParamType->isEnumeralType()) {
15914         ClassOrEnumParam = true;
15915         break;
15916       }
15917     }
15918 
15919     if (!ClassOrEnumParam)
15920       return Diag(FnDecl->getLocation(),
15921                   diag::err_operator_overload_needs_class_or_enum)
15922         << FnDecl->getDeclName();
15923   }
15924 
15925   // C++ [over.oper]p8:
15926   //   An operator function cannot have default arguments (8.3.6),
15927   //   except where explicitly stated below.
15928   //
15929   // Only the function-call operator (C++ [over.call]p1) and the subscript
15930   // operator (CWG2507) allow default arguments.
15931   if (Op != OO_Call) {
15932     ParmVarDecl *FirstDefaultedParam = nullptr;
15933     for (auto Param : FnDecl->parameters()) {
15934       if (Param->hasDefaultArg()) {
15935         FirstDefaultedParam = Param;
15936         break;
15937       }
15938     }
15939     if (FirstDefaultedParam) {
15940       if (Op == OO_Subscript) {
15941         Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15942                                         ? diag::ext_subscript_overload
15943                                         : diag::error_subscript_overload)
15944             << FnDecl->getDeclName() << 1
15945             << FirstDefaultedParam->getDefaultArgRange();
15946       } else {
15947         return Diag(FirstDefaultedParam->getLocation(),
15948                     diag::err_operator_overload_default_arg)
15949                << FnDecl->getDeclName()
15950                << FirstDefaultedParam->getDefaultArgRange();
15951       }
15952     }
15953   }
15954 
15955   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15956     { false, false, false }
15957 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15958     , { Unary, Binary, MemberOnly }
15959 #include "clang/Basic/OperatorKinds.def"
15960   };
15961 
15962   bool CanBeUnaryOperator = OperatorUses[Op][0];
15963   bool CanBeBinaryOperator = OperatorUses[Op][1];
15964   bool MustBeMemberOperator = OperatorUses[Op][2];
15965 
15966   // C++ [over.oper]p8:
15967   //   [...] Operator functions cannot have more or fewer parameters
15968   //   than the number required for the corresponding operator, as
15969   //   described in the rest of this subclause.
15970   unsigned NumParams = FnDecl->getNumParams()
15971                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15972   if (Op != OO_Call && Op != OO_Subscript &&
15973       ((NumParams == 1 && !CanBeUnaryOperator) ||
15974        (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
15975        (NumParams > 2))) {
15976     // We have the wrong number of parameters.
15977     unsigned ErrorKind;
15978     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15979       ErrorKind = 2;  // 2 -> unary or binary.
15980     } else if (CanBeUnaryOperator) {
15981       ErrorKind = 0;  // 0 -> unary
15982     } else {
15983       assert(CanBeBinaryOperator &&
15984              "All non-call overloaded operators are unary or binary!");
15985       ErrorKind = 1;  // 1 -> binary
15986     }
15987     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15988       << FnDecl->getDeclName() << NumParams << ErrorKind;
15989   }
15990 
15991   if (Op == OO_Subscript && NumParams != 2) {
15992     Diag(FnDecl->getLocation(), LangOpts.CPlusPlus2b
15993                                     ? diag::ext_subscript_overload
15994                                     : diag::error_subscript_overload)
15995         << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
15996   }
15997 
15998   // Overloaded operators other than operator() and operator[] cannot be
15999   // variadic.
16000   if (Op != OO_Call &&
16001       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
16002     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
16003            << FnDecl->getDeclName();
16004   }
16005 
16006   // Some operators must be non-static member functions.
16007   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
16008     return Diag(FnDecl->getLocation(),
16009                 diag::err_operator_overload_must_be_member)
16010       << FnDecl->getDeclName();
16011   }
16012 
16013   // C++ [over.inc]p1:
16014   //   The user-defined function called operator++ implements the
16015   //   prefix and postfix ++ operator. If this function is a member
16016   //   function with no parameters, or a non-member function with one
16017   //   parameter of class or enumeration type, it defines the prefix
16018   //   increment operator ++ for objects of that type. If the function
16019   //   is a member function with one parameter (which shall be of type
16020   //   int) or a non-member function with two parameters (the second
16021   //   of which shall be of type int), it defines the postfix
16022   //   increment operator ++ for objects of that type.
16023   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
16024     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
16025     QualType ParamType = LastParam->getType();
16026 
16027     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
16028         !ParamType->isDependentType())
16029       return Diag(LastParam->getLocation(),
16030                   diag::err_operator_overload_post_incdec_must_be_int)
16031         << LastParam->getType() << (Op == OO_MinusMinus);
16032   }
16033 
16034   return false;
16035 }
16036 
16037 static bool
16038 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
16039                                           FunctionTemplateDecl *TpDecl) {
16040   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
16041 
16042   // Must have one or two template parameters.
16043   if (TemplateParams->size() == 1) {
16044     NonTypeTemplateParmDecl *PmDecl =
16045         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
16046 
16047     // The template parameter must be a char parameter pack.
16048     if (PmDecl && PmDecl->isTemplateParameterPack() &&
16049         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
16050       return false;
16051 
16052     // C++20 [over.literal]p5:
16053     //   A string literal operator template is a literal operator template
16054     //   whose template-parameter-list comprises a single non-type
16055     //   template-parameter of class type.
16056     //
16057     // As a DR resolution, we also allow placeholders for deduced class
16058     // template specializations.
16059     if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
16060         !PmDecl->isTemplateParameterPack() &&
16061         (PmDecl->getType()->isRecordType() ||
16062          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
16063       return false;
16064   } else if (TemplateParams->size() == 2) {
16065     TemplateTypeParmDecl *PmType =
16066         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
16067     NonTypeTemplateParmDecl *PmArgs =
16068         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
16069 
16070     // The second template parameter must be a parameter pack with the
16071     // first template parameter as its type.
16072     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
16073         PmArgs->isTemplateParameterPack()) {
16074       const TemplateTypeParmType *TArgs =
16075           PmArgs->getType()->getAs<TemplateTypeParmType>();
16076       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
16077           TArgs->getIndex() == PmType->getIndex()) {
16078         if (!SemaRef.inTemplateInstantiation())
16079           SemaRef.Diag(TpDecl->getLocation(),
16080                        diag::ext_string_literal_operator_template);
16081         return false;
16082       }
16083     }
16084   }
16085 
16086   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16087                diag::err_literal_operator_template)
16088       << TpDecl->getTemplateParameters()->getSourceRange();
16089   return true;
16090 }
16091 
16092 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16093 /// of this literal operator function is well-formed. If so, returns
16094 /// false; otherwise, emits appropriate diagnostics and returns true.
16095 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16096   if (isa<CXXMethodDecl>(FnDecl)) {
16097     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16098       << FnDecl->getDeclName();
16099     return true;
16100   }
16101 
16102   if (FnDecl->isExternC()) {
16103     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16104     if (const LinkageSpecDecl *LSD =
16105             FnDecl->getDeclContext()->getExternCContext())
16106       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16107     return true;
16108   }
16109 
16110   // This might be the definition of a literal operator template.
16111   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16112 
16113   // This might be a specialization of a literal operator template.
16114   if (!TpDecl)
16115     TpDecl = FnDecl->getPrimaryTemplate();
16116 
16117   // template <char...> type operator "" name() and
16118   // template <class T, T...> type operator "" name() are the only valid
16119   // template signatures, and the only valid signatures with no parameters.
16120   //
16121   // C++20 also allows template <SomeClass T> type operator "" name().
16122   if (TpDecl) {
16123     if (FnDecl->param_size() != 0) {
16124       Diag(FnDecl->getLocation(),
16125            diag::err_literal_operator_template_with_params);
16126       return true;
16127     }
16128 
16129     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16130       return true;
16131 
16132   } else if (FnDecl->param_size() == 1) {
16133     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16134 
16135     QualType ParamType = Param->getType().getUnqualifiedType();
16136 
16137     // Only unsigned long long int, long double, any character type, and const
16138     // char * are allowed as the only parameters.
16139     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16140         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16141         Context.hasSameType(ParamType, Context.CharTy) ||
16142         Context.hasSameType(ParamType, Context.WideCharTy) ||
16143         Context.hasSameType(ParamType, Context.Char8Ty) ||
16144         Context.hasSameType(ParamType, Context.Char16Ty) ||
16145         Context.hasSameType(ParamType, Context.Char32Ty)) {
16146     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16147       QualType InnerType = Ptr->getPointeeType();
16148 
16149       // Pointer parameter must be a const char *.
16150       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16151                                 Context.CharTy) &&
16152             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16153         Diag(Param->getSourceRange().getBegin(),
16154              diag::err_literal_operator_param)
16155             << ParamType << "'const char *'" << Param->getSourceRange();
16156         return true;
16157       }
16158 
16159     } else if (ParamType->isRealFloatingType()) {
16160       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16161           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16162       return true;
16163 
16164     } else if (ParamType->isIntegerType()) {
16165       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16166           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16167       return true;
16168 
16169     } else {
16170       Diag(Param->getSourceRange().getBegin(),
16171            diag::err_literal_operator_invalid_param)
16172           << ParamType << Param->getSourceRange();
16173       return true;
16174     }
16175 
16176   } else if (FnDecl->param_size() == 2) {
16177     FunctionDecl::param_iterator Param = FnDecl->param_begin();
16178 
16179     // First, verify that the first parameter is correct.
16180 
16181     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16182 
16183     // Two parameter function must have a pointer to const as a
16184     // first parameter; let's strip those qualifiers.
16185     const PointerType *PT = FirstParamType->getAs<PointerType>();
16186 
16187     if (!PT) {
16188       Diag((*Param)->getSourceRange().getBegin(),
16189            diag::err_literal_operator_param)
16190           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16191       return true;
16192     }
16193 
16194     QualType PointeeType = PT->getPointeeType();
16195     // First parameter must be const
16196     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16197       Diag((*Param)->getSourceRange().getBegin(),
16198            diag::err_literal_operator_param)
16199           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16200       return true;
16201     }
16202 
16203     QualType InnerType = PointeeType.getUnqualifiedType();
16204     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16205     // const char32_t* are allowed as the first parameter to a two-parameter
16206     // function
16207     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16208           Context.hasSameType(InnerType, Context.WideCharTy) ||
16209           Context.hasSameType(InnerType, Context.Char8Ty) ||
16210           Context.hasSameType(InnerType, Context.Char16Ty) ||
16211           Context.hasSameType(InnerType, Context.Char32Ty))) {
16212       Diag((*Param)->getSourceRange().getBegin(),
16213            diag::err_literal_operator_param)
16214           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16215       return true;
16216     }
16217 
16218     // Move on to the second and final parameter.
16219     ++Param;
16220 
16221     // The second parameter must be a std::size_t.
16222     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16223     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16224       Diag((*Param)->getSourceRange().getBegin(),
16225            diag::err_literal_operator_param)
16226           << SecondParamType << Context.getSizeType()
16227           << (*Param)->getSourceRange();
16228       return true;
16229     }
16230   } else {
16231     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16232     return true;
16233   }
16234 
16235   // Parameters are good.
16236 
16237   // A parameter-declaration-clause containing a default argument is not
16238   // equivalent to any of the permitted forms.
16239   for (auto Param : FnDecl->parameters()) {
16240     if (Param->hasDefaultArg()) {
16241       Diag(Param->getDefaultArgRange().getBegin(),
16242            diag::err_literal_operator_default_argument)
16243         << Param->getDefaultArgRange();
16244       break;
16245     }
16246   }
16247 
16248   StringRef LiteralName
16249     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16250   if (LiteralName[0] != '_' &&
16251       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16252     // C++11 [usrlit.suffix]p1:
16253     //   Literal suffix identifiers that do not start with an underscore
16254     //   are reserved for future standardization.
16255     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16256       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16257   }
16258 
16259   return false;
16260 }
16261 
16262 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16263 /// linkage specification, including the language and (if present)
16264 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16265 /// language string literal. LBraceLoc, if valid, provides the location of
16266 /// the '{' brace. Otherwise, this linkage specification does not
16267 /// have any braces.
16268 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16269                                            Expr *LangStr,
16270                                            SourceLocation LBraceLoc) {
16271   StringLiteral *Lit = cast<StringLiteral>(LangStr);
16272   if (!Lit->isOrdinary()) {
16273     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16274       << LangStr->getSourceRange();
16275     return nullptr;
16276   }
16277 
16278   StringRef Lang = Lit->getString();
16279   LinkageSpecDecl::LanguageIDs Language;
16280   if (Lang == "C")
16281     Language = LinkageSpecDecl::lang_c;
16282   else if (Lang == "C++")
16283     Language = LinkageSpecDecl::lang_cxx;
16284   else {
16285     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16286       << LangStr->getSourceRange();
16287     return nullptr;
16288   }
16289 
16290   // FIXME: Add all the various semantics of linkage specifications
16291 
16292   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16293                                                LangStr->getExprLoc(), Language,
16294                                                LBraceLoc.isValid());
16295 
16296   /// C++ [module.unit]p7.2.3
16297   /// - Otherwise, if the declaration
16298   ///   - ...
16299   ///   - ...
16300   ///   - appears within a linkage-specification,
16301   ///   it is attached to the global module.
16302   ///
16303   /// If the declaration is already in global module fragment, we don't
16304   /// need to attach it again.
16305   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16306     Module *GlobalModule =
16307         PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
16308     /// According to [module.reach]p3.2,
16309     /// The declaration in global module fragment is reachable if it is not
16310     /// discarded. And the discarded declaration should be deleted. So it
16311     /// doesn't matter mark the declaration in global module fragment as
16312     /// reachable here.
16313     D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
16314     D->setLocalOwningModule(GlobalModule);
16315   }
16316 
16317   CurContext->addDecl(D);
16318   PushDeclContext(S, D);
16319   return D;
16320 }
16321 
16322 /// ActOnFinishLinkageSpecification - Complete the definition of
16323 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16324 /// valid, it's the position of the closing '}' brace in a linkage
16325 /// specification that uses braces.
16326 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16327                                             Decl *LinkageSpec,
16328                                             SourceLocation RBraceLoc) {
16329   if (RBraceLoc.isValid()) {
16330     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16331     LSDecl->setRBraceLoc(RBraceLoc);
16332   }
16333 
16334   // If the current module doesn't has Parent, it implies that the
16335   // LinkageSpec isn't in the module created by itself. So we don't
16336   // need to pop it.
16337   if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16338       getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
16339     PopGlobalModuleFragment();
16340 
16341   PopDeclContext();
16342   return LinkageSpec;
16343 }
16344 
16345 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16346                                   const ParsedAttributesView &AttrList,
16347                                   SourceLocation SemiLoc) {
16348   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16349   // Attribute declarations appertain to empty declaration so we handle
16350   // them here.
16351   ProcessDeclAttributeList(S, ED, AttrList);
16352 
16353   CurContext->addDecl(ED);
16354   return ED;
16355 }
16356 
16357 /// Perform semantic analysis for the variable declaration that
16358 /// occurs within a C++ catch clause, returning the newly-created
16359 /// variable.
16360 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16361                                          TypeSourceInfo *TInfo,
16362                                          SourceLocation StartLoc,
16363                                          SourceLocation Loc,
16364                                          IdentifierInfo *Name) {
16365   bool Invalid = false;
16366   QualType ExDeclType = TInfo->getType();
16367 
16368   // Arrays and functions decay.
16369   if (ExDeclType->isArrayType())
16370     ExDeclType = Context.getArrayDecayedType(ExDeclType);
16371   else if (ExDeclType->isFunctionType())
16372     ExDeclType = Context.getPointerType(ExDeclType);
16373 
16374   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16375   // The exception-declaration shall not denote a pointer or reference to an
16376   // incomplete type, other than [cv] void*.
16377   // N2844 forbids rvalue references.
16378   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16379     Diag(Loc, diag::err_catch_rvalue_ref);
16380     Invalid = true;
16381   }
16382 
16383   if (ExDeclType->isVariablyModifiedType()) {
16384     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16385     Invalid = true;
16386   }
16387 
16388   QualType BaseType = ExDeclType;
16389   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16390   unsigned DK = diag::err_catch_incomplete;
16391   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16392     BaseType = Ptr->getPointeeType();
16393     Mode = 1;
16394     DK = diag::err_catch_incomplete_ptr;
16395   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16396     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16397     BaseType = Ref->getPointeeType();
16398     Mode = 2;
16399     DK = diag::err_catch_incomplete_ref;
16400   }
16401   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16402       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16403     Invalid = true;
16404 
16405   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16406     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16407     Invalid = true;
16408   }
16409 
16410   if (!Invalid && !ExDeclType->isDependentType() &&
16411       RequireNonAbstractType(Loc, ExDeclType,
16412                              diag::err_abstract_type_in_decl,
16413                              AbstractVariableType))
16414     Invalid = true;
16415 
16416   // Only the non-fragile NeXT runtime currently supports C++ catches
16417   // of ObjC types, and no runtime supports catching ObjC types by value.
16418   if (!Invalid && getLangOpts().ObjC) {
16419     QualType T = ExDeclType;
16420     if (const ReferenceType *RT = T->getAs<ReferenceType>())
16421       T = RT->getPointeeType();
16422 
16423     if (T->isObjCObjectType()) {
16424       Diag(Loc, diag::err_objc_object_catch);
16425       Invalid = true;
16426     } else if (T->isObjCObjectPointerType()) {
16427       // FIXME: should this be a test for macosx-fragile specifically?
16428       if (getLangOpts().ObjCRuntime.isFragile())
16429         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16430     }
16431   }
16432 
16433   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16434                                     ExDeclType, TInfo, SC_None);
16435   ExDecl->setExceptionVariable(true);
16436 
16437   // In ARC, infer 'retaining' for variables of retainable type.
16438   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16439     Invalid = true;
16440 
16441   if (!Invalid && !ExDeclType->isDependentType()) {
16442     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16443       // Insulate this from anything else we might currently be parsing.
16444       EnterExpressionEvaluationContext scope(
16445           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16446 
16447       // C++ [except.handle]p16:
16448       //   The object declared in an exception-declaration or, if the
16449       //   exception-declaration does not specify a name, a temporary (12.2) is
16450       //   copy-initialized (8.5) from the exception object. [...]
16451       //   The object is destroyed when the handler exits, after the destruction
16452       //   of any automatic objects initialized within the handler.
16453       //
16454       // We just pretend to initialize the object with itself, then make sure
16455       // it can be destroyed later.
16456       QualType initType = Context.getExceptionObjectType(ExDeclType);
16457 
16458       InitializedEntity entity =
16459         InitializedEntity::InitializeVariable(ExDecl);
16460       InitializationKind initKind =
16461         InitializationKind::CreateCopy(Loc, SourceLocation());
16462 
16463       Expr *opaqueValue =
16464         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16465       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16466       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16467       if (result.isInvalid())
16468         Invalid = true;
16469       else {
16470         // If the constructor used was non-trivial, set this as the
16471         // "initializer".
16472         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16473         if (!construct->getConstructor()->isTrivial()) {
16474           Expr *init = MaybeCreateExprWithCleanups(construct);
16475           ExDecl->setInit(init);
16476         }
16477 
16478         // And make sure it's destructable.
16479         FinalizeVarWithDestructor(ExDecl, recordType);
16480       }
16481     }
16482   }
16483 
16484   if (Invalid)
16485     ExDecl->setInvalidDecl();
16486 
16487   return ExDecl;
16488 }
16489 
16490 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16491 /// handler.
16492 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16493   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16494   bool Invalid = D.isInvalidType();
16495 
16496   // Check for unexpanded parameter packs.
16497   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16498                                       UPPC_ExceptionType)) {
16499     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16500                                              D.getIdentifierLoc());
16501     Invalid = true;
16502   }
16503 
16504   IdentifierInfo *II = D.getIdentifier();
16505   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16506                                              LookupOrdinaryName,
16507                                              ForVisibleRedeclaration)) {
16508     // The scope should be freshly made just for us. There is just no way
16509     // it contains any previous declaration, except for function parameters in
16510     // a function-try-block's catch statement.
16511     assert(!S->isDeclScope(PrevDecl));
16512     if (isDeclInScope(PrevDecl, CurContext, S)) {
16513       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16514         << D.getIdentifier();
16515       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16516       Invalid = true;
16517     } else if (PrevDecl->isTemplateParameter())
16518       // Maybe we will complain about the shadowed template parameter.
16519       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16520   }
16521 
16522   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16523     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16524       << D.getCXXScopeSpec().getRange();
16525     Invalid = true;
16526   }
16527 
16528   VarDecl *ExDecl = BuildExceptionDeclaration(
16529       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16530   if (Invalid)
16531     ExDecl->setInvalidDecl();
16532 
16533   // Add the exception declaration into this scope.
16534   if (II)
16535     PushOnScopeChains(ExDecl, S);
16536   else
16537     CurContext->addDecl(ExDecl);
16538 
16539   ProcessDeclAttributes(S, ExDecl, D);
16540   return ExDecl;
16541 }
16542 
16543 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16544                                          Expr *AssertExpr,
16545                                          Expr *AssertMessageExpr,
16546                                          SourceLocation RParenLoc) {
16547   StringLiteral *AssertMessage =
16548       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16549 
16550   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16551     return nullptr;
16552 
16553   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16554                                       AssertMessage, RParenLoc, false);
16555 }
16556 
16557 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16558                                          Expr *AssertExpr,
16559                                          StringLiteral *AssertMessage,
16560                                          SourceLocation RParenLoc,
16561                                          bool Failed) {
16562   assert(AssertExpr != nullptr && "Expected non-null condition");
16563   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16564       !Failed) {
16565     // In a static_assert-declaration, the constant-expression shall be a
16566     // constant expression that can be contextually converted to bool.
16567     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16568     if (Converted.isInvalid())
16569       Failed = true;
16570 
16571     ExprResult FullAssertExpr =
16572         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16573                             /*DiscardedValue*/ false,
16574                             /*IsConstexpr*/ true);
16575     if (FullAssertExpr.isInvalid())
16576       Failed = true;
16577     else
16578       AssertExpr = FullAssertExpr.get();
16579 
16580     llvm::APSInt Cond;
16581     if (!Failed && VerifyIntegerConstantExpression(
16582                        AssertExpr, &Cond,
16583                        diag::err_static_assert_expression_is_not_constant)
16584                        .isInvalid())
16585       Failed = true;
16586 
16587     if (!Failed && !Cond) {
16588       SmallString<256> MsgBuffer;
16589       llvm::raw_svector_ostream Msg(MsgBuffer);
16590       if (AssertMessage) {
16591         const auto *MsgStr = cast<StringLiteral>(AssertMessage);
16592         if (MsgStr->isOrdinary())
16593           Msg << MsgStr->getString();
16594         else
16595           MsgStr->printPretty(Msg, nullptr, getPrintingPolicy());
16596       }
16597 
16598       Expr *InnerCond = nullptr;
16599       std::string InnerCondDescription;
16600       std::tie(InnerCond, InnerCondDescription) =
16601         findFailedBooleanCondition(Converted.get());
16602       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16603         // Drill down into concept specialization expressions to see why they
16604         // weren't satisfied.
16605         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16606           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16607         ConstraintSatisfaction Satisfaction;
16608         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16609           DiagnoseUnsatisfiedConstraint(Satisfaction);
16610       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16611                            && !isa<IntegerLiteral>(InnerCond)) {
16612         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16613           << InnerCondDescription << !AssertMessage
16614           << Msg.str() << InnerCond->getSourceRange();
16615       } else {
16616         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16617           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16618       }
16619       Failed = true;
16620     }
16621   } else {
16622     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16623                                                     /*DiscardedValue*/false,
16624                                                     /*IsConstexpr*/true);
16625     if (FullAssertExpr.isInvalid())
16626       Failed = true;
16627     else
16628       AssertExpr = FullAssertExpr.get();
16629   }
16630 
16631   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16632                                         AssertExpr, AssertMessage, RParenLoc,
16633                                         Failed);
16634 
16635   CurContext->addDecl(Decl);
16636   return Decl;
16637 }
16638 
16639 /// Perform semantic analysis of the given friend type declaration.
16640 ///
16641 /// \returns A friend declaration that.
16642 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16643                                       SourceLocation FriendLoc,
16644                                       TypeSourceInfo *TSInfo) {
16645   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16646 
16647   QualType T = TSInfo->getType();
16648   SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
16649 
16650   // C++03 [class.friend]p2:
16651   //   An elaborated-type-specifier shall be used in a friend declaration
16652   //   for a class.*
16653   //
16654   //   * The class-key of the elaborated-type-specifier is required.
16655   if (!CodeSynthesisContexts.empty()) {
16656     // Do not complain about the form of friend template types during any kind
16657     // of code synthesis. For template instantiation, we will have complained
16658     // when the template was defined.
16659   } else {
16660     if (!T->isElaboratedTypeSpecifier()) {
16661       // If we evaluated the type to a record type, suggest putting
16662       // a tag in front.
16663       if (const RecordType *RT = T->getAs<RecordType>()) {
16664         RecordDecl *RD = RT->getDecl();
16665 
16666         SmallString<16> InsertionText(" ");
16667         InsertionText += RD->getKindName();
16668 
16669         Diag(TypeRange.getBegin(),
16670              getLangOpts().CPlusPlus11 ?
16671                diag::warn_cxx98_compat_unelaborated_friend_type :
16672                diag::ext_unelaborated_friend_type)
16673           << (unsigned) RD->getTagKind()
16674           << T
16675           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16676                                         InsertionText);
16677       } else {
16678         Diag(FriendLoc,
16679              getLangOpts().CPlusPlus11 ?
16680                diag::warn_cxx98_compat_nonclass_type_friend :
16681                diag::ext_nonclass_type_friend)
16682           << T
16683           << TypeRange;
16684       }
16685     } else if (T->getAs<EnumType>()) {
16686       Diag(FriendLoc,
16687            getLangOpts().CPlusPlus11 ?
16688              diag::warn_cxx98_compat_enum_friend :
16689              diag::ext_enum_friend)
16690         << T
16691         << TypeRange;
16692     }
16693 
16694     // C++11 [class.friend]p3:
16695     //   A friend declaration that does not declare a function shall have one
16696     //   of the following forms:
16697     //     friend elaborated-type-specifier ;
16698     //     friend simple-type-specifier ;
16699     //     friend typename-specifier ;
16700     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16701       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16702   }
16703 
16704   //   If the type specifier in a friend declaration designates a (possibly
16705   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16706   //   the friend declaration is ignored.
16707   return FriendDecl::Create(Context, CurContext,
16708                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16709                             FriendLoc);
16710 }
16711 
16712 /// Handle a friend tag declaration where the scope specifier was
16713 /// templated.
16714 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16715                                     unsigned TagSpec, SourceLocation TagLoc,
16716                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16717                                     SourceLocation NameLoc,
16718                                     const ParsedAttributesView &Attr,
16719                                     MultiTemplateParamsArg TempParamLists) {
16720   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16721 
16722   bool IsMemberSpecialization = false;
16723   bool Invalid = false;
16724 
16725   if (TemplateParameterList *TemplateParams =
16726           MatchTemplateParametersToScopeSpecifier(
16727               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16728               IsMemberSpecialization, Invalid)) {
16729     if (TemplateParams->size() > 0) {
16730       // This is a declaration of a class template.
16731       if (Invalid)
16732         return nullptr;
16733 
16734       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16735                                 NameLoc, Attr, TemplateParams, AS_public,
16736                                 /*ModulePrivateLoc=*/SourceLocation(),
16737                                 FriendLoc, TempParamLists.size() - 1,
16738                                 TempParamLists.data()).get();
16739     } else {
16740       // The "template<>" header is extraneous.
16741       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16742         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16743       IsMemberSpecialization = true;
16744     }
16745   }
16746 
16747   if (Invalid) return nullptr;
16748 
16749   bool isAllExplicitSpecializations = true;
16750   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16751     if (TempParamLists[I]->size()) {
16752       isAllExplicitSpecializations = false;
16753       break;
16754     }
16755   }
16756 
16757   // FIXME: don't ignore attributes.
16758 
16759   // If it's explicit specializations all the way down, just forget
16760   // about the template header and build an appropriate non-templated
16761   // friend.  TODO: for source fidelity, remember the headers.
16762   if (isAllExplicitSpecializations) {
16763     if (SS.isEmpty()) {
16764       bool Owned = false;
16765       bool IsDependent = false;
16766       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16767                       Attr, AS_public,
16768                       /*ModulePrivateLoc=*/SourceLocation(),
16769                       MultiTemplateParamsArg(), Owned, IsDependent,
16770                       /*ScopedEnumKWLoc=*/SourceLocation(),
16771                       /*ScopedEnumUsesClassTag=*/false,
16772                       /*UnderlyingType=*/TypeResult(),
16773                       /*IsTypeSpecifier=*/false,
16774                       /*IsTemplateParamOrArg=*/false);
16775     }
16776 
16777     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16778     ElaboratedTypeKeyword Keyword
16779       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16780     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16781                                    *Name, NameLoc);
16782     if (T.isNull())
16783       return nullptr;
16784 
16785     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16786     if (isa<DependentNameType>(T)) {
16787       DependentNameTypeLoc TL =
16788           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16789       TL.setElaboratedKeywordLoc(TagLoc);
16790       TL.setQualifierLoc(QualifierLoc);
16791       TL.setNameLoc(NameLoc);
16792     } else {
16793       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16794       TL.setElaboratedKeywordLoc(TagLoc);
16795       TL.setQualifierLoc(QualifierLoc);
16796       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16797     }
16798 
16799     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16800                                             TSI, FriendLoc, TempParamLists);
16801     Friend->setAccess(AS_public);
16802     CurContext->addDecl(Friend);
16803     return Friend;
16804   }
16805 
16806   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16807 
16808 
16809 
16810   // Handle the case of a templated-scope friend class.  e.g.
16811   //   template <class T> class A<T>::B;
16812   // FIXME: we don't support these right now.
16813   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16814     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16815   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16816   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16817   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16818   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16819   TL.setElaboratedKeywordLoc(TagLoc);
16820   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16821   TL.setNameLoc(NameLoc);
16822 
16823   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16824                                           TSI, FriendLoc, TempParamLists);
16825   Friend->setAccess(AS_public);
16826   Friend->setUnsupportedFriend(true);
16827   CurContext->addDecl(Friend);
16828   return Friend;
16829 }
16830 
16831 /// Handle a friend type declaration.  This works in tandem with
16832 /// ActOnTag.
16833 ///
16834 /// Notes on friend class templates:
16835 ///
16836 /// We generally treat friend class declarations as if they were
16837 /// declaring a class.  So, for example, the elaborated type specifier
16838 /// in a friend declaration is required to obey the restrictions of a
16839 /// class-head (i.e. no typedefs in the scope chain), template
16840 /// parameters are required to match up with simple template-ids, &c.
16841 /// However, unlike when declaring a template specialization, it's
16842 /// okay to refer to a template specialization without an empty
16843 /// template parameter declaration, e.g.
16844 ///   friend class A<T>::B<unsigned>;
16845 /// We permit this as a special case; if there are any template
16846 /// parameters present at all, require proper matching, i.e.
16847 ///   template <> template \<class T> friend class A<int>::B;
16848 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16849                                 MultiTemplateParamsArg TempParams) {
16850   SourceLocation Loc = DS.getBeginLoc();
16851 
16852   assert(DS.isFriendSpecified());
16853   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16854 
16855   // C++ [class.friend]p3:
16856   // A friend declaration that does not declare a function shall have one of
16857   // the following forms:
16858   //     friend elaborated-type-specifier ;
16859   //     friend simple-type-specifier ;
16860   //     friend typename-specifier ;
16861   //
16862   // Any declaration with a type qualifier does not have that form. (It's
16863   // legal to specify a qualified type as a friend, you just can't write the
16864   // keywords.)
16865   if (DS.getTypeQualifiers()) {
16866     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16867       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16868     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16869       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16870     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16871       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16872     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16873       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16874     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16875       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16876   }
16877 
16878   // Try to convert the decl specifier to a type.  This works for
16879   // friend templates because ActOnTag never produces a ClassTemplateDecl
16880   // for a TUK_Friend.
16881   Declarator TheDeclarator(DS, ParsedAttributesView::none(),
16882                            DeclaratorContext::Member);
16883   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16884   QualType T = TSI->getType();
16885   if (TheDeclarator.isInvalidType())
16886     return nullptr;
16887 
16888   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16889     return nullptr;
16890 
16891   // This is definitely an error in C++98.  It's probably meant to
16892   // be forbidden in C++0x, too, but the specification is just
16893   // poorly written.
16894   //
16895   // The problem is with declarations like the following:
16896   //   template <T> friend A<T>::foo;
16897   // where deciding whether a class C is a friend or not now hinges
16898   // on whether there exists an instantiation of A that causes
16899   // 'foo' to equal C.  There are restrictions on class-heads
16900   // (which we declare (by fiat) elaborated friend declarations to
16901   // be) that makes this tractable.
16902   //
16903   // FIXME: handle "template <> friend class A<T>;", which
16904   // is possibly well-formed?  Who even knows?
16905   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16906     Diag(Loc, diag::err_tagless_friend_type_template)
16907       << DS.getSourceRange();
16908     return nullptr;
16909   }
16910 
16911   // C++98 [class.friend]p1: A friend of a class is a function
16912   //   or class that is not a member of the class . . .
16913   // This is fixed in DR77, which just barely didn't make the C++03
16914   // deadline.  It's also a very silly restriction that seriously
16915   // affects inner classes and which nobody else seems to implement;
16916   // thus we never diagnose it, not even in -pedantic.
16917   //
16918   // But note that we could warn about it: it's always useless to
16919   // friend one of your own members (it's not, however, worthless to
16920   // friend a member of an arbitrary specialization of your template).
16921 
16922   Decl *D;
16923   if (!TempParams.empty())
16924     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16925                                    TempParams,
16926                                    TSI,
16927                                    DS.getFriendSpecLoc());
16928   else
16929     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16930 
16931   if (!D)
16932     return nullptr;
16933 
16934   D->setAccess(AS_public);
16935   CurContext->addDecl(D);
16936 
16937   return D;
16938 }
16939 
16940 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16941                                         MultiTemplateParamsArg TemplateParams) {
16942   const DeclSpec &DS = D.getDeclSpec();
16943 
16944   assert(DS.isFriendSpecified());
16945   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16946 
16947   SourceLocation Loc = D.getIdentifierLoc();
16948   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16949 
16950   // C++ [class.friend]p1
16951   //   A friend of a class is a function or class....
16952   // Note that this sees through typedefs, which is intended.
16953   // It *doesn't* see through dependent types, which is correct
16954   // according to [temp.arg.type]p3:
16955   //   If a declaration acquires a function type through a
16956   //   type dependent on a template-parameter and this causes
16957   //   a declaration that does not use the syntactic form of a
16958   //   function declarator to have a function type, the program
16959   //   is ill-formed.
16960   if (!TInfo->getType()->isFunctionType()) {
16961     Diag(Loc, diag::err_unexpected_friend);
16962 
16963     // It might be worthwhile to try to recover by creating an
16964     // appropriate declaration.
16965     return nullptr;
16966   }
16967 
16968   // C++ [namespace.memdef]p3
16969   //  - If a friend declaration in a non-local class first declares a
16970   //    class or function, the friend class or function is a member
16971   //    of the innermost enclosing namespace.
16972   //  - The name of the friend is not found by simple name lookup
16973   //    until a matching declaration is provided in that namespace
16974   //    scope (either before or after the class declaration granting
16975   //    friendship).
16976   //  - If a friend function is called, its name may be found by the
16977   //    name lookup that considers functions from namespaces and
16978   //    classes associated with the types of the function arguments.
16979   //  - When looking for a prior declaration of a class or a function
16980   //    declared as a friend, scopes outside the innermost enclosing
16981   //    namespace scope are not considered.
16982 
16983   CXXScopeSpec &SS = D.getCXXScopeSpec();
16984   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16985   assert(NameInfo.getName());
16986 
16987   // Check for unexpanded parameter packs.
16988   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16989       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16990       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16991     return nullptr;
16992 
16993   // The context we found the declaration in, or in which we should
16994   // create the declaration.
16995   DeclContext *DC;
16996   Scope *DCScope = S;
16997   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16998                         ForExternalRedeclaration);
16999 
17000   // There are five cases here.
17001   //   - There's no scope specifier and we're in a local class. Only look
17002   //     for functions declared in the immediately-enclosing block scope.
17003   // We recover from invalid scope qualifiers as if they just weren't there.
17004   FunctionDecl *FunctionContainingLocalClass = nullptr;
17005   if ((SS.isInvalid() || !SS.isSet()) &&
17006       (FunctionContainingLocalClass =
17007            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
17008     // C++11 [class.friend]p11:
17009     //   If a friend declaration appears in a local class and the name
17010     //   specified is an unqualified name, a prior declaration is
17011     //   looked up without considering scopes that are outside the
17012     //   innermost enclosing non-class scope. For a friend function
17013     //   declaration, if there is no prior declaration, the program is
17014     //   ill-formed.
17015 
17016     // Find the innermost enclosing non-class scope. This is the block
17017     // scope containing the local class definition (or for a nested class,
17018     // the outer local class).
17019     DCScope = S->getFnParent();
17020 
17021     // Look up the function name in the scope.
17022     Previous.clear(LookupLocalFriendName);
17023     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
17024 
17025     if (!Previous.empty()) {
17026       // All possible previous declarations must have the same context:
17027       // either they were declared at block scope or they are members of
17028       // one of the enclosing local classes.
17029       DC = Previous.getRepresentativeDecl()->getDeclContext();
17030     } else {
17031       // This is ill-formed, but provide the context that we would have
17032       // declared the function in, if we were permitted to, for error recovery.
17033       DC = FunctionContainingLocalClass;
17034     }
17035     adjustContextForLocalExternDecl(DC);
17036 
17037     // C++ [class.friend]p6:
17038     //   A function can be defined in a friend declaration of a class if and
17039     //   only if the class is a non-local class (9.8), the function name is
17040     //   unqualified, and the function has namespace scope.
17041     if (D.isFunctionDefinition()) {
17042       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
17043     }
17044 
17045   //   - There's no scope specifier, in which case we just go to the
17046   //     appropriate scope and look for a function or function template
17047   //     there as appropriate.
17048   } else if (SS.isInvalid() || !SS.isSet()) {
17049     // C++11 [namespace.memdef]p3:
17050     //   If the name in a friend declaration is neither qualified nor
17051     //   a template-id and the declaration is a function or an
17052     //   elaborated-type-specifier, the lookup to determine whether
17053     //   the entity has been previously declared shall not consider
17054     //   any scopes outside the innermost enclosing namespace.
17055     bool isTemplateId =
17056         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
17057 
17058     // Find the appropriate context according to the above.
17059     DC = CurContext;
17060 
17061     // Skip class contexts.  If someone can cite chapter and verse
17062     // for this behavior, that would be nice --- it's what GCC and
17063     // EDG do, and it seems like a reasonable intent, but the spec
17064     // really only says that checks for unqualified existing
17065     // declarations should stop at the nearest enclosing namespace,
17066     // not that they should only consider the nearest enclosing
17067     // namespace.
17068     while (DC->isRecord())
17069       DC = DC->getParent();
17070 
17071     DeclContext *LookupDC = DC->getNonTransparentContext();
17072     while (true) {
17073       LookupQualifiedName(Previous, LookupDC);
17074 
17075       if (!Previous.empty()) {
17076         DC = LookupDC;
17077         break;
17078       }
17079 
17080       if (isTemplateId) {
17081         if (isa<TranslationUnitDecl>(LookupDC)) break;
17082       } else {
17083         if (LookupDC->isFileContext()) break;
17084       }
17085       LookupDC = LookupDC->getParent();
17086     }
17087 
17088     DCScope = getScopeForDeclContext(S, DC);
17089 
17090   //   - There's a non-dependent scope specifier, in which case we
17091   //     compute it and do a previous lookup there for a function
17092   //     or function template.
17093   } else if (!SS.getScopeRep()->isDependent()) {
17094     DC = computeDeclContext(SS);
17095     if (!DC) return nullptr;
17096 
17097     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17098 
17099     LookupQualifiedName(Previous, DC);
17100 
17101     // C++ [class.friend]p1: A friend of a class is a function or
17102     //   class that is not a member of the class . . .
17103     if (DC->Equals(CurContext))
17104       Diag(DS.getFriendSpecLoc(),
17105            getLangOpts().CPlusPlus11 ?
17106              diag::warn_cxx98_compat_friend_is_member :
17107              diag::err_friend_is_member);
17108 
17109     if (D.isFunctionDefinition()) {
17110       // C++ [class.friend]p6:
17111       //   A function can be defined in a friend declaration of a class if and
17112       //   only if the class is a non-local class (9.8), the function name is
17113       //   unqualified, and the function has namespace scope.
17114       //
17115       // FIXME: We should only do this if the scope specifier names the
17116       // innermost enclosing namespace; otherwise the fixit changes the
17117       // meaning of the code.
17118       SemaDiagnosticBuilder DB
17119         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17120 
17121       DB << SS.getScopeRep();
17122       if (DC->isFileContext())
17123         DB << FixItHint::CreateRemoval(SS.getRange());
17124       SS.clear();
17125     }
17126 
17127   //   - There's a scope specifier that does not match any template
17128   //     parameter lists, in which case we use some arbitrary context,
17129   //     create a method or method template, and wait for instantiation.
17130   //   - There's a scope specifier that does match some template
17131   //     parameter lists, which we don't handle right now.
17132   } else {
17133     if (D.isFunctionDefinition()) {
17134       // C++ [class.friend]p6:
17135       //   A function can be defined in a friend declaration of a class if and
17136       //   only if the class is a non-local class (9.8), the function name is
17137       //   unqualified, and the function has namespace scope.
17138       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17139         << SS.getScopeRep();
17140     }
17141 
17142     DC = CurContext;
17143     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17144   }
17145 
17146   if (!DC->isRecord()) {
17147     int DiagArg = -1;
17148     switch (D.getName().getKind()) {
17149     case UnqualifiedIdKind::IK_ConstructorTemplateId:
17150     case UnqualifiedIdKind::IK_ConstructorName:
17151       DiagArg = 0;
17152       break;
17153     case UnqualifiedIdKind::IK_DestructorName:
17154       DiagArg = 1;
17155       break;
17156     case UnqualifiedIdKind::IK_ConversionFunctionId:
17157       DiagArg = 2;
17158       break;
17159     case UnqualifiedIdKind::IK_DeductionGuideName:
17160       DiagArg = 3;
17161       break;
17162     case UnqualifiedIdKind::IK_Identifier:
17163     case UnqualifiedIdKind::IK_ImplicitSelfParam:
17164     case UnqualifiedIdKind::IK_LiteralOperatorId:
17165     case UnqualifiedIdKind::IK_OperatorFunctionId:
17166     case UnqualifiedIdKind::IK_TemplateId:
17167       break;
17168     }
17169     // This implies that it has to be an operator or function.
17170     if (DiagArg >= 0) {
17171       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17172       return nullptr;
17173     }
17174   }
17175 
17176   // FIXME: This is an egregious hack to cope with cases where the scope stack
17177   // does not contain the declaration context, i.e., in an out-of-line
17178   // definition of a class.
17179   Scope FakeDCScope(S, Scope::DeclScope, Diags);
17180   if (!DCScope) {
17181     FakeDCScope.setEntity(DC);
17182     DCScope = &FakeDCScope;
17183   }
17184 
17185   bool AddToScope = true;
17186   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17187                                           TemplateParams, AddToScope);
17188   if (!ND) return nullptr;
17189 
17190   assert(ND->getLexicalDeclContext() == CurContext);
17191 
17192   // If we performed typo correction, we might have added a scope specifier
17193   // and changed the decl context.
17194   DC = ND->getDeclContext();
17195 
17196   // Add the function declaration to the appropriate lookup tables,
17197   // adjusting the redeclarations list as necessary.  We don't
17198   // want to do this yet if the friending class is dependent.
17199   //
17200   // Also update the scope-based lookup if the target context's
17201   // lookup context is in lexical scope.
17202   if (!CurContext->isDependentContext()) {
17203     DC = DC->getRedeclContext();
17204     DC->makeDeclVisibleInContext(ND);
17205     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17206       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17207   }
17208 
17209   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17210                                        D.getIdentifierLoc(), ND,
17211                                        DS.getFriendSpecLoc());
17212   FrD->setAccess(AS_public);
17213   CurContext->addDecl(FrD);
17214 
17215   if (ND->isInvalidDecl()) {
17216     FrD->setInvalidDecl();
17217   } else {
17218     if (DC->isRecord()) CheckFriendAccess(ND);
17219 
17220     FunctionDecl *FD;
17221     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17222       FD = FTD->getTemplatedDecl();
17223     else
17224       FD = cast<FunctionDecl>(ND);
17225 
17226     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17227     // default argument expression, that declaration shall be a definition
17228     // and shall be the only declaration of the function or function
17229     // template in the translation unit.
17230     if (functionDeclHasDefaultArgument(FD)) {
17231       // We can't look at FD->getPreviousDecl() because it may not have been set
17232       // if we're in a dependent context. If the function is known to be a
17233       // redeclaration, we will have narrowed Previous down to the right decl.
17234       if (D.isRedeclaration()) {
17235         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17236         Diag(Previous.getRepresentativeDecl()->getLocation(),
17237              diag::note_previous_declaration);
17238       } else if (!D.isFunctionDefinition())
17239         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17240     }
17241 
17242     // Mark templated-scope function declarations as unsupported.
17243     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17244       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17245         << SS.getScopeRep() << SS.getRange()
17246         << cast<CXXRecordDecl>(CurContext);
17247       FrD->setUnsupportedFriend(true);
17248     }
17249   }
17250 
17251   warnOnReservedIdentifier(ND);
17252 
17253   return ND;
17254 }
17255 
17256 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17257   AdjustDeclIfTemplate(Dcl);
17258 
17259   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17260   if (!Fn) {
17261     Diag(DelLoc, diag::err_deleted_non_function);
17262     return;
17263   }
17264 
17265   // Deleted function does not have a body.
17266   Fn->setWillHaveBody(false);
17267 
17268   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17269     // Don't consider the implicit declaration we generate for explicit
17270     // specializations. FIXME: Do not generate these implicit declarations.
17271     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17272          Prev->getPreviousDecl()) &&
17273         !Prev->isDefined()) {
17274       Diag(DelLoc, diag::err_deleted_decl_not_first);
17275       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17276            Prev->isImplicit() ? diag::note_previous_implicit_declaration
17277                               : diag::note_previous_declaration);
17278       // We can't recover from this; the declaration might have already
17279       // been used.
17280       Fn->setInvalidDecl();
17281       return;
17282     }
17283 
17284     // To maintain the invariant that functions are only deleted on their first
17285     // declaration, mark the implicitly-instantiated declaration of the
17286     // explicitly-specialized function as deleted instead of marking the
17287     // instantiated redeclaration.
17288     Fn = Fn->getCanonicalDecl();
17289   }
17290 
17291   // dllimport/dllexport cannot be deleted.
17292   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17293     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17294     Fn->setInvalidDecl();
17295   }
17296 
17297   // C++11 [basic.start.main]p3:
17298   //   A program that defines main as deleted [...] is ill-formed.
17299   if (Fn->isMain())
17300     Diag(DelLoc, diag::err_deleted_main);
17301 
17302   // C++11 [dcl.fct.def.delete]p4:
17303   //  A deleted function is implicitly inline.
17304   Fn->setImplicitlyInline();
17305   Fn->setDeletedAsWritten();
17306 }
17307 
17308 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17309   if (!Dcl || Dcl->isInvalidDecl())
17310     return;
17311 
17312   auto *FD = dyn_cast<FunctionDecl>(Dcl);
17313   if (!FD) {
17314     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17315       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17316         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17317         return;
17318       }
17319     }
17320 
17321     Diag(DefaultLoc, diag::err_default_special_members)
17322         << getLangOpts().CPlusPlus20;
17323     return;
17324   }
17325 
17326   // Reject if this can't possibly be a defaultable function.
17327   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17328   if (!DefKind &&
17329       // A dependent function that doesn't locally look defaultable can
17330       // still instantiate to a defaultable function if it's a constructor
17331       // or assignment operator.
17332       (!FD->isDependentContext() ||
17333        (!isa<CXXConstructorDecl>(FD) &&
17334         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17335     Diag(DefaultLoc, diag::err_default_special_members)
17336         << getLangOpts().CPlusPlus20;
17337     return;
17338   }
17339 
17340   // Issue compatibility warning. We already warned if the operator is
17341   // 'operator<=>' when parsing the '<=>' token.
17342   if (DefKind.isComparison() &&
17343       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17344     Diag(DefaultLoc, getLangOpts().CPlusPlus20
17345                          ? diag::warn_cxx17_compat_defaulted_comparison
17346                          : diag::ext_defaulted_comparison);
17347   }
17348 
17349   FD->setDefaulted();
17350   FD->setExplicitlyDefaulted();
17351 
17352   // Defer checking functions that are defaulted in a dependent context.
17353   if (FD->isDependentContext())
17354     return;
17355 
17356   // Unset that we will have a body for this function. We might not,
17357   // if it turns out to be trivial, and we don't need this marking now
17358   // that we've marked it as defaulted.
17359   FD->setWillHaveBody(false);
17360 
17361   if (DefKind.isComparison()) {
17362     // If this comparison's defaulting occurs within the definition of its
17363     // lexical class context, we have to do the checking when complete.
17364     if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17365       if (!RD->isCompleteDefinition())
17366         return;
17367   }
17368 
17369   // If this member fn was defaulted on its first declaration, we will have
17370   // already performed the checking in CheckCompletedCXXClass. Such a
17371   // declaration doesn't trigger an implicit definition.
17372   if (isa<CXXMethodDecl>(FD)) {
17373     const FunctionDecl *Primary = FD;
17374     if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17375       // Ask the template instantiation pattern that actually had the
17376       // '= default' on it.
17377       Primary = Pattern;
17378     if (Primary->getCanonicalDecl()->isDefaulted())
17379       return;
17380   }
17381 
17382   if (DefKind.isComparison()) {
17383     if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17384       FD->setInvalidDecl();
17385     else
17386       DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17387   } else {
17388     auto *MD = cast<CXXMethodDecl>(FD);
17389 
17390     if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
17391       MD->setInvalidDecl();
17392     else
17393       DefineDefaultedFunction(*this, MD, DefaultLoc);
17394   }
17395 }
17396 
17397 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17398   for (Stmt *SubStmt : S->children()) {
17399     if (!SubStmt)
17400       continue;
17401     if (isa<ReturnStmt>(SubStmt))
17402       Self.Diag(SubStmt->getBeginLoc(),
17403                 diag::err_return_in_constructor_handler);
17404     if (!isa<Expr>(SubStmt))
17405       SearchForReturnInStmt(Self, SubStmt);
17406   }
17407 }
17408 
17409 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17410   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17411     CXXCatchStmt *Handler = TryBlock->getHandler(I);
17412     SearchForReturnInStmt(*this, Handler);
17413   }
17414 }
17415 
17416 void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc,
17417                                FnBodyKind BodyKind) {
17418   switch (BodyKind) {
17419   case FnBodyKind::Delete:
17420     SetDeclDeleted(D, Loc);
17421     break;
17422   case FnBodyKind::Default:
17423     SetDeclDefaulted(D, Loc);
17424     break;
17425   case FnBodyKind::Other:
17426     llvm_unreachable(
17427         "Parsed function body should be '= delete;' or '= default;'");
17428   }
17429 }
17430 
17431 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17432                                              const CXXMethodDecl *Old) {
17433   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17434   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17435 
17436   if (OldFT->hasExtParameterInfos()) {
17437     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17438       // A parameter of the overriding method should be annotated with noescape
17439       // if the corresponding parameter of the overridden method is annotated.
17440       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17441           !NewFT->getExtParameterInfo(I).isNoEscape()) {
17442         Diag(New->getParamDecl(I)->getLocation(),
17443              diag::warn_overriding_method_missing_noescape);
17444         Diag(Old->getParamDecl(I)->getLocation(),
17445              diag::note_overridden_marked_noescape);
17446       }
17447   }
17448 
17449   // Virtual overrides must have the same code_seg.
17450   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17451   const auto *NewCSA = New->getAttr<CodeSegAttr>();
17452   if ((NewCSA || OldCSA) &&
17453       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17454     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17455     Diag(Old->getLocation(), diag::note_previous_declaration);
17456     return true;
17457   }
17458 
17459   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17460 
17461   // If the calling conventions match, everything is fine
17462   if (NewCC == OldCC)
17463     return false;
17464 
17465   // If the calling conventions mismatch because the new function is static,
17466   // suppress the calling convention mismatch error; the error about static
17467   // function override (err_static_overrides_virtual from
17468   // Sema::CheckFunctionDeclaration) is more clear.
17469   if (New->getStorageClass() == SC_Static)
17470     return false;
17471 
17472   Diag(New->getLocation(),
17473        diag::err_conflicting_overriding_cc_attributes)
17474     << New->getDeclName() << New->getType() << Old->getType();
17475   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17476   return true;
17477 }
17478 
17479 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17480                                              const CXXMethodDecl *Old) {
17481   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17482   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17483 
17484   if (Context.hasSameType(NewTy, OldTy) ||
17485       NewTy->isDependentType() || OldTy->isDependentType())
17486     return false;
17487 
17488   // Check if the return types are covariant
17489   QualType NewClassTy, OldClassTy;
17490 
17491   /// Both types must be pointers or references to classes.
17492   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17493     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17494       NewClassTy = NewPT->getPointeeType();
17495       OldClassTy = OldPT->getPointeeType();
17496     }
17497   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17498     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17499       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17500         NewClassTy = NewRT->getPointeeType();
17501         OldClassTy = OldRT->getPointeeType();
17502       }
17503     }
17504   }
17505 
17506   // The return types aren't either both pointers or references to a class type.
17507   if (NewClassTy.isNull()) {
17508     Diag(New->getLocation(),
17509          diag::err_different_return_type_for_overriding_virtual_function)
17510         << New->getDeclName() << NewTy << OldTy
17511         << New->getReturnTypeSourceRange();
17512     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17513         << Old->getReturnTypeSourceRange();
17514 
17515     return true;
17516   }
17517 
17518   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17519     // C++14 [class.virtual]p8:
17520     //   If the class type in the covariant return type of D::f differs from
17521     //   that of B::f, the class type in the return type of D::f shall be
17522     //   complete at the point of declaration of D::f or shall be the class
17523     //   type D.
17524     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17525       if (!RT->isBeingDefined() &&
17526           RequireCompleteType(New->getLocation(), NewClassTy,
17527                               diag::err_covariant_return_incomplete,
17528                               New->getDeclName()))
17529         return true;
17530     }
17531 
17532     // Check if the new class derives from the old class.
17533     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17534       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17535           << New->getDeclName() << NewTy << OldTy
17536           << New->getReturnTypeSourceRange();
17537       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17538           << Old->getReturnTypeSourceRange();
17539       return true;
17540     }
17541 
17542     // Check if we the conversion from derived to base is valid.
17543     if (CheckDerivedToBaseConversion(
17544             NewClassTy, OldClassTy,
17545             diag::err_covariant_return_inaccessible_base,
17546             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17547             New->getLocation(), New->getReturnTypeSourceRange(),
17548             New->getDeclName(), nullptr)) {
17549       // FIXME: this note won't trigger for delayed access control
17550       // diagnostics, and it's impossible to get an undelayed error
17551       // here from access control during the original parse because
17552       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17553       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17554           << Old->getReturnTypeSourceRange();
17555       return true;
17556     }
17557   }
17558 
17559   // The qualifiers of the return types must be the same.
17560   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17561     Diag(New->getLocation(),
17562          diag::err_covariant_return_type_different_qualifications)
17563         << New->getDeclName() << NewTy << OldTy
17564         << New->getReturnTypeSourceRange();
17565     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17566         << Old->getReturnTypeSourceRange();
17567     return true;
17568   }
17569 
17570 
17571   // The new class type must have the same or less qualifiers as the old type.
17572   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17573     Diag(New->getLocation(),
17574          diag::err_covariant_return_type_class_type_more_qualified)
17575         << New->getDeclName() << NewTy << OldTy
17576         << New->getReturnTypeSourceRange();
17577     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17578         << Old->getReturnTypeSourceRange();
17579     return true;
17580   }
17581 
17582   return false;
17583 }
17584 
17585 /// Mark the given method pure.
17586 ///
17587 /// \param Method the method to be marked pure.
17588 ///
17589 /// \param InitRange the source range that covers the "0" initializer.
17590 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17591   SourceLocation EndLoc = InitRange.getEnd();
17592   if (EndLoc.isValid())
17593     Method->setRangeEnd(EndLoc);
17594 
17595   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17596     Method->setPure();
17597     return false;
17598   }
17599 
17600   if (!Method->isInvalidDecl())
17601     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17602       << Method->getDeclName() << InitRange;
17603   return true;
17604 }
17605 
17606 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17607   if (D->getFriendObjectKind())
17608     Diag(D->getLocation(), diag::err_pure_friend);
17609   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17610     CheckPureMethod(M, ZeroLoc);
17611   else
17612     Diag(D->getLocation(), diag::err_illegal_initializer);
17613 }
17614 
17615 /// Determine whether the given declaration is a global variable or
17616 /// static data member.
17617 static bool isNonlocalVariable(const Decl *D) {
17618   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17619     return Var->hasGlobalStorage();
17620 
17621   return false;
17622 }
17623 
17624 /// Invoked when we are about to parse an initializer for the declaration
17625 /// 'Dcl'.
17626 ///
17627 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17628 /// static data member of class X, names should be looked up in the scope of
17629 /// class X. If the declaration had a scope specifier, a scope will have
17630 /// been created and passed in for this purpose. Otherwise, S will be null.
17631 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17632   // If there is no declaration, there was an error parsing it.
17633   if (!D || D->isInvalidDecl())
17634     return;
17635 
17636   // We will always have a nested name specifier here, but this declaration
17637   // might not be out of line if the specifier names the current namespace:
17638   //   extern int n;
17639   //   int ::n = 0;
17640   if (S && D->isOutOfLine())
17641     EnterDeclaratorContext(S, D->getDeclContext());
17642 
17643   // If we are parsing the initializer for a static data member, push a
17644   // new expression evaluation context that is associated with this static
17645   // data member.
17646   if (isNonlocalVariable(D))
17647     PushExpressionEvaluationContext(
17648         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17649 }
17650 
17651 /// Invoked after we are finished parsing an initializer for the declaration D.
17652 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17653   // If there is no declaration, there was an error parsing it.
17654   if (!D || D->isInvalidDecl())
17655     return;
17656 
17657   if (isNonlocalVariable(D))
17658     PopExpressionEvaluationContext();
17659 
17660   if (S && D->isOutOfLine())
17661     ExitDeclaratorContext(S);
17662 }
17663 
17664 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17665 /// C++ if/switch/while/for statement.
17666 /// e.g: "if (int x = f()) {...}"
17667 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17668   // C++ 6.4p2:
17669   // The declarator shall not specify a function or an array.
17670   // The type-specifier-seq shall not contain typedef and shall not declare a
17671   // new class or enumeration.
17672   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17673          "Parser allowed 'typedef' as storage class of condition decl.");
17674 
17675   Decl *Dcl = ActOnDeclarator(S, D);
17676   if (!Dcl)
17677     return true;
17678 
17679   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17680     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17681       << D.getSourceRange();
17682     return true;
17683   }
17684 
17685   return Dcl;
17686 }
17687 
17688 void Sema::LoadExternalVTableUses() {
17689   if (!ExternalSource)
17690     return;
17691 
17692   SmallVector<ExternalVTableUse, 4> VTables;
17693   ExternalSource->ReadUsedVTables(VTables);
17694   SmallVector<VTableUse, 4> NewUses;
17695   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17696     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17697       = VTablesUsed.find(VTables[I].Record);
17698     // Even if a definition wasn't required before, it may be required now.
17699     if (Pos != VTablesUsed.end()) {
17700       if (!Pos->second && VTables[I].DefinitionRequired)
17701         Pos->second = true;
17702       continue;
17703     }
17704 
17705     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17706     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17707   }
17708 
17709   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17710 }
17711 
17712 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17713                           bool DefinitionRequired) {
17714   // Ignore any vtable uses in unevaluated operands or for classes that do
17715   // not have a vtable.
17716   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17717       CurContext->isDependentContext() || isUnevaluatedContext())
17718     return;
17719   // Do not mark as used if compiling for the device outside of the target
17720   // region.
17721   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17722       !isInOpenMPDeclareTargetContext() &&
17723       !isInOpenMPTargetExecutionDirective()) {
17724     if (!DefinitionRequired)
17725       MarkVirtualMembersReferenced(Loc, Class);
17726     return;
17727   }
17728 
17729   // Try to insert this class into the map.
17730   LoadExternalVTableUses();
17731   Class = Class->getCanonicalDecl();
17732   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17733     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17734   if (!Pos.second) {
17735     // If we already had an entry, check to see if we are promoting this vtable
17736     // to require a definition. If so, we need to reappend to the VTableUses
17737     // list, since we may have already processed the first entry.
17738     if (DefinitionRequired && !Pos.first->second) {
17739       Pos.first->second = true;
17740     } else {
17741       // Otherwise, we can early exit.
17742       return;
17743     }
17744   } else {
17745     // The Microsoft ABI requires that we perform the destructor body
17746     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17747     // the deleting destructor is emitted with the vtable, not with the
17748     // destructor definition as in the Itanium ABI.
17749     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17750       CXXDestructorDecl *DD = Class->getDestructor();
17751       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17752         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17753           // If this is an out-of-line declaration, marking it referenced will
17754           // not do anything. Manually call CheckDestructor to look up operator
17755           // delete().
17756           ContextRAII SavedContext(*this, DD);
17757           CheckDestructor(DD);
17758         } else {
17759           MarkFunctionReferenced(Loc, Class->getDestructor());
17760         }
17761       }
17762     }
17763   }
17764 
17765   // Local classes need to have their virtual members marked
17766   // immediately. For all other classes, we mark their virtual members
17767   // at the end of the translation unit.
17768   if (Class->isLocalClass())
17769     MarkVirtualMembersReferenced(Loc, Class);
17770   else
17771     VTableUses.push_back(std::make_pair(Class, Loc));
17772 }
17773 
17774 bool Sema::DefineUsedVTables() {
17775   LoadExternalVTableUses();
17776   if (VTableUses.empty())
17777     return false;
17778 
17779   // Note: The VTableUses vector could grow as a result of marking
17780   // the members of a class as "used", so we check the size each
17781   // time through the loop and prefer indices (which are stable) to
17782   // iterators (which are not).
17783   bool DefinedAnything = false;
17784   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17785     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17786     if (!Class)
17787       continue;
17788     TemplateSpecializationKind ClassTSK =
17789         Class->getTemplateSpecializationKind();
17790 
17791     SourceLocation Loc = VTableUses[I].second;
17792 
17793     bool DefineVTable = true;
17794 
17795     // If this class has a key function, but that key function is
17796     // defined in another translation unit, we don't need to emit the
17797     // vtable even though we're using it.
17798     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17799     if (KeyFunction && !KeyFunction->hasBody()) {
17800       // The key function is in another translation unit.
17801       DefineVTable = false;
17802       TemplateSpecializationKind TSK =
17803           KeyFunction->getTemplateSpecializationKind();
17804       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17805              TSK != TSK_ImplicitInstantiation &&
17806              "Instantiations don't have key functions");
17807       (void)TSK;
17808     } else if (!KeyFunction) {
17809       // If we have a class with no key function that is the subject
17810       // of an explicit instantiation declaration, suppress the
17811       // vtable; it will live with the explicit instantiation
17812       // definition.
17813       bool IsExplicitInstantiationDeclaration =
17814           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17815       for (auto R : Class->redecls()) {
17816         TemplateSpecializationKind TSK
17817           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17818         if (TSK == TSK_ExplicitInstantiationDeclaration)
17819           IsExplicitInstantiationDeclaration = true;
17820         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17821           IsExplicitInstantiationDeclaration = false;
17822           break;
17823         }
17824       }
17825 
17826       if (IsExplicitInstantiationDeclaration)
17827         DefineVTable = false;
17828     }
17829 
17830     // The exception specifications for all virtual members may be needed even
17831     // if we are not providing an authoritative form of the vtable in this TU.
17832     // We may choose to emit it available_externally anyway.
17833     if (!DefineVTable) {
17834       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17835       continue;
17836     }
17837 
17838     // Mark all of the virtual members of this class as referenced, so
17839     // that we can build a vtable. Then, tell the AST consumer that a
17840     // vtable for this class is required.
17841     DefinedAnything = true;
17842     MarkVirtualMembersReferenced(Loc, Class);
17843     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17844     if (VTablesUsed[Canonical])
17845       Consumer.HandleVTable(Class);
17846 
17847     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17848     // no key function or the key function is inlined. Don't warn in C++ ABIs
17849     // that lack key functions, since the user won't be able to make one.
17850     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17851         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
17852         ClassTSK != TSK_ExplicitInstantiationDefinition) {
17853       const FunctionDecl *KeyFunctionDef = nullptr;
17854       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17855                            KeyFunctionDef->isInlined()))
17856         Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
17857     }
17858   }
17859   VTableUses.clear();
17860 
17861   return DefinedAnything;
17862 }
17863 
17864 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17865                                                  const CXXRecordDecl *RD) {
17866   for (const auto *I : RD->methods())
17867     if (I->isVirtual() && !I->isPure())
17868       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17869 }
17870 
17871 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17872                                         const CXXRecordDecl *RD,
17873                                         bool ConstexprOnly) {
17874   // Mark all functions which will appear in RD's vtable as used.
17875   CXXFinalOverriderMap FinalOverriders;
17876   RD->getFinalOverriders(FinalOverriders);
17877   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17878                                             E = FinalOverriders.end();
17879        I != E; ++I) {
17880     for (OverridingMethods::const_iterator OI = I->second.begin(),
17881                                            OE = I->second.end();
17882          OI != OE; ++OI) {
17883       assert(OI->second.size() > 0 && "no final overrider");
17884       CXXMethodDecl *Overrider = OI->second.front().Method;
17885 
17886       // C++ [basic.def.odr]p2:
17887       //   [...] A virtual member function is used if it is not pure. [...]
17888       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17889         MarkFunctionReferenced(Loc, Overrider);
17890     }
17891   }
17892 
17893   // Only classes that have virtual bases need a VTT.
17894   if (RD->getNumVBases() == 0)
17895     return;
17896 
17897   for (const auto &I : RD->bases()) {
17898     const auto *Base =
17899         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17900     if (Base->getNumVBases() == 0)
17901       continue;
17902     MarkVirtualMembersReferenced(Loc, Base);
17903   }
17904 }
17905 
17906 /// SetIvarInitializers - This routine builds initialization ASTs for the
17907 /// Objective-C implementation whose ivars need be initialized.
17908 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17909   if (!getLangOpts().CPlusPlus)
17910     return;
17911   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17912     SmallVector<ObjCIvarDecl*, 8> ivars;
17913     CollectIvarsToConstructOrDestruct(OID, ivars);
17914     if (ivars.empty())
17915       return;
17916     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17917     for (unsigned i = 0; i < ivars.size(); i++) {
17918       FieldDecl *Field = ivars[i];
17919       if (Field->isInvalidDecl())
17920         continue;
17921 
17922       CXXCtorInitializer *Member;
17923       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17924       InitializationKind InitKind =
17925         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17926 
17927       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17928       ExprResult MemberInit =
17929         InitSeq.Perform(*this, InitEntity, InitKind, None);
17930       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17931       // Note, MemberInit could actually come back empty if no initialization
17932       // is required (e.g., because it would call a trivial default constructor)
17933       if (!MemberInit.get() || MemberInit.isInvalid())
17934         continue;
17935 
17936       Member =
17937         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17938                                          SourceLocation(),
17939                                          MemberInit.getAs<Expr>(),
17940                                          SourceLocation());
17941       AllToInit.push_back(Member);
17942 
17943       // Be sure that the destructor is accessible and is marked as referenced.
17944       if (const RecordType *RecordTy =
17945               Context.getBaseElementType(Field->getType())
17946                   ->getAs<RecordType>()) {
17947         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17948         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17949           MarkFunctionReferenced(Field->getLocation(), Destructor);
17950           CheckDestructorAccess(Field->getLocation(), Destructor,
17951                             PDiag(diag::err_access_dtor_ivar)
17952                               << Context.getBaseElementType(Field->getType()));
17953         }
17954       }
17955     }
17956     ObjCImplementation->setIvarInitializers(Context,
17957                                             AllToInit.data(), AllToInit.size());
17958   }
17959 }
17960 
17961 static
17962 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17963                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17964                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17965                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17966                            Sema &S) {
17967   if (Ctor->isInvalidDecl())
17968     return;
17969 
17970   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17971 
17972   // Target may not be determinable yet, for instance if this is a dependent
17973   // call in an uninstantiated template.
17974   if (Target) {
17975     const FunctionDecl *FNTarget = nullptr;
17976     (void)Target->hasBody(FNTarget);
17977     Target = const_cast<CXXConstructorDecl*>(
17978       cast_or_null<CXXConstructorDecl>(FNTarget));
17979   }
17980 
17981   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17982                      // Avoid dereferencing a null pointer here.
17983                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17984 
17985   if (!Current.insert(Canonical).second)
17986     return;
17987 
17988   // We know that beyond here, we aren't chaining into a cycle.
17989   if (!Target || !Target->isDelegatingConstructor() ||
17990       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17991     Valid.insert(Current.begin(), Current.end());
17992     Current.clear();
17993   // We've hit a cycle.
17994   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17995              Current.count(TCanonical)) {
17996     // If we haven't diagnosed this cycle yet, do so now.
17997     if (!Invalid.count(TCanonical)) {
17998       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17999              diag::warn_delegating_ctor_cycle)
18000         << Ctor;
18001 
18002       // Don't add a note for a function delegating directly to itself.
18003       if (TCanonical != Canonical)
18004         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
18005 
18006       CXXConstructorDecl *C = Target;
18007       while (C->getCanonicalDecl() != Canonical) {
18008         const FunctionDecl *FNTarget = nullptr;
18009         (void)C->getTargetConstructor()->hasBody(FNTarget);
18010         assert(FNTarget && "Ctor cycle through bodiless function");
18011 
18012         C = const_cast<CXXConstructorDecl*>(
18013           cast<CXXConstructorDecl>(FNTarget));
18014         S.Diag(C->getLocation(), diag::note_which_delegates_to);
18015       }
18016     }
18017 
18018     Invalid.insert(Current.begin(), Current.end());
18019     Current.clear();
18020   } else {
18021     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
18022   }
18023 }
18024 
18025 
18026 void Sema::CheckDelegatingCtorCycles() {
18027   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
18028 
18029   for (DelegatingCtorDeclsType::iterator
18030          I = DelegatingCtorDecls.begin(ExternalSource),
18031          E = DelegatingCtorDecls.end();
18032        I != E; ++I)
18033     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
18034 
18035   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
18036     (*CI)->setInvalidDecl();
18037 }
18038 
18039 namespace {
18040   /// AST visitor that finds references to the 'this' expression.
18041   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
18042     Sema &S;
18043 
18044   public:
18045     explicit FindCXXThisExpr(Sema &S) : S(S) { }
18046 
18047     bool VisitCXXThisExpr(CXXThisExpr *E) {
18048       S.Diag(E->getLocation(), diag::err_this_static_member_func)
18049         << E->isImplicit();
18050       return false;
18051     }
18052   };
18053 }
18054 
18055 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
18056   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18057   if (!TSInfo)
18058     return false;
18059 
18060   TypeLoc TL = TSInfo->getTypeLoc();
18061   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18062   if (!ProtoTL)
18063     return false;
18064 
18065   // C++11 [expr.prim.general]p3:
18066   //   [The expression this] shall not appear before the optional
18067   //   cv-qualifier-seq and it shall not appear within the declaration of a
18068   //   static member function (although its type and value category are defined
18069   //   within a static member function as they are within a non-static member
18070   //   function). [ Note: this is because declaration matching does not occur
18071   //  until the complete declarator is known. - end note ]
18072   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18073   FindCXXThisExpr Finder(*this);
18074 
18075   // If the return type came after the cv-qualifier-seq, check it now.
18076   if (Proto->hasTrailingReturn() &&
18077       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
18078     return true;
18079 
18080   // Check the exception specification.
18081   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
18082     return true;
18083 
18084   // Check the trailing requires clause
18085   if (Expr *E = Method->getTrailingRequiresClause())
18086     if (!Finder.TraverseStmt(E))
18087       return true;
18088 
18089   return checkThisInStaticMemberFunctionAttributes(Method);
18090 }
18091 
18092 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
18093   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
18094   if (!TSInfo)
18095     return false;
18096 
18097   TypeLoc TL = TSInfo->getTypeLoc();
18098   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
18099   if (!ProtoTL)
18100     return false;
18101 
18102   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
18103   FindCXXThisExpr Finder(*this);
18104 
18105   switch (Proto->getExceptionSpecType()) {
18106   case EST_Unparsed:
18107   case EST_Uninstantiated:
18108   case EST_Unevaluated:
18109   case EST_BasicNoexcept:
18110   case EST_NoThrow:
18111   case EST_DynamicNone:
18112   case EST_MSAny:
18113   case EST_None:
18114     break;
18115 
18116   case EST_DependentNoexcept:
18117   case EST_NoexceptFalse:
18118   case EST_NoexceptTrue:
18119     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18120       return true;
18121     LLVM_FALLTHROUGH;
18122 
18123   case EST_Dynamic:
18124     for (const auto &E : Proto->exceptions()) {
18125       if (!Finder.TraverseType(E))
18126         return true;
18127     }
18128     break;
18129   }
18130 
18131   return false;
18132 }
18133 
18134 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
18135   FindCXXThisExpr Finder(*this);
18136 
18137   // Check attributes.
18138   for (const auto *A : Method->attrs()) {
18139     // FIXME: This should be emitted by tblgen.
18140     Expr *Arg = nullptr;
18141     ArrayRef<Expr *> Args;
18142     if (const auto *G = dyn_cast<GuardedByAttr>(A))
18143       Arg = G->getArg();
18144     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18145       Arg = G->getArg();
18146     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18147       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
18148     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18149       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
18150     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18151       Arg = ETLF->getSuccessValue();
18152       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
18153     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18154       Arg = STLF->getSuccessValue();
18155       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
18156     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18157       Arg = LR->getArg();
18158     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18159       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
18160     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18161       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18162     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18163       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18164     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18165       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18166     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18167       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18168 
18169     if (Arg && !Finder.TraverseStmt(Arg))
18170       return true;
18171 
18172     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18173       if (!Finder.TraverseStmt(Args[I]))
18174         return true;
18175     }
18176   }
18177 
18178   return false;
18179 }
18180 
18181 void Sema::checkExceptionSpecification(
18182     bool IsTopLevel, ExceptionSpecificationType EST,
18183     ArrayRef<ParsedType> DynamicExceptions,
18184     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18185     SmallVectorImpl<QualType> &Exceptions,
18186     FunctionProtoType::ExceptionSpecInfo &ESI) {
18187   Exceptions.clear();
18188   ESI.Type = EST;
18189   if (EST == EST_Dynamic) {
18190     Exceptions.reserve(DynamicExceptions.size());
18191     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18192       // FIXME: Preserve type source info.
18193       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18194 
18195       if (IsTopLevel) {
18196         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
18197         collectUnexpandedParameterPacks(ET, Unexpanded);
18198         if (!Unexpanded.empty()) {
18199           DiagnoseUnexpandedParameterPacks(
18200               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18201               Unexpanded);
18202           continue;
18203         }
18204       }
18205 
18206       // Check that the type is valid for an exception spec, and
18207       // drop it if not.
18208       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18209         Exceptions.push_back(ET);
18210     }
18211     ESI.Exceptions = Exceptions;
18212     return;
18213   }
18214 
18215   if (isComputedNoexcept(EST)) {
18216     assert((NoexceptExpr->isTypeDependent() ||
18217             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18218             Context.BoolTy) &&
18219            "Parser should have made sure that the expression is boolean");
18220     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18221       ESI.Type = EST_BasicNoexcept;
18222       return;
18223     }
18224 
18225     ESI.NoexceptExpr = NoexceptExpr;
18226     return;
18227   }
18228 }
18229 
18230 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
18231              ExceptionSpecificationType EST,
18232              SourceRange SpecificationRange,
18233              ArrayRef<ParsedType> DynamicExceptions,
18234              ArrayRef<SourceRange> DynamicExceptionRanges,
18235              Expr *NoexceptExpr) {
18236   if (!MethodD)
18237     return;
18238 
18239   // Dig out the method we're referring to.
18240   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18241     MethodD = FunTmpl->getTemplatedDecl();
18242 
18243   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18244   if (!Method)
18245     return;
18246 
18247   // Check the exception specification.
18248   llvm::SmallVector<QualType, 4> Exceptions;
18249   FunctionProtoType::ExceptionSpecInfo ESI;
18250   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18251                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
18252                               ESI);
18253 
18254   // Update the exception specification on the function type.
18255   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18256 
18257   if (Method->isStatic())
18258     checkThisInStaticMemberFunctionExceptionSpec(Method);
18259 
18260   if (Method->isVirtual()) {
18261     // Check overrides, which we previously had to delay.
18262     for (const CXXMethodDecl *O : Method->overridden_methods())
18263       CheckOverridingFunctionExceptionSpec(Method, O);
18264   }
18265 }
18266 
18267 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18268 ///
18269 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18270                                        SourceLocation DeclStart, Declarator &D,
18271                                        Expr *BitWidth,
18272                                        InClassInitStyle InitStyle,
18273                                        AccessSpecifier AS,
18274                                        const ParsedAttr &MSPropertyAttr) {
18275   IdentifierInfo *II = D.getIdentifier();
18276   if (!II) {
18277     Diag(DeclStart, diag::err_anonymous_property);
18278     return nullptr;
18279   }
18280   SourceLocation Loc = D.getIdentifierLoc();
18281 
18282   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18283   QualType T = TInfo->getType();
18284   if (getLangOpts().CPlusPlus) {
18285     CheckExtraCXXDefaultArguments(D);
18286 
18287     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18288                                         UPPC_DataMemberType)) {
18289       D.setInvalidType();
18290       T = Context.IntTy;
18291       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18292     }
18293   }
18294 
18295   DiagnoseFunctionSpecifiers(D.getDeclSpec());
18296 
18297   if (D.getDeclSpec().isInlineSpecified())
18298     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18299         << getLangOpts().CPlusPlus17;
18300   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18301     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18302          diag::err_invalid_thread)
18303       << DeclSpec::getSpecifierName(TSCS);
18304 
18305   // Check to see if this name was declared as a member previously
18306   NamedDecl *PrevDecl = nullptr;
18307   LookupResult Previous(*this, II, Loc, LookupMemberName,
18308                         ForVisibleRedeclaration);
18309   LookupName(Previous, S);
18310   switch (Previous.getResultKind()) {
18311   case LookupResult::Found:
18312   case LookupResult::FoundUnresolvedValue:
18313     PrevDecl = Previous.getAsSingle<NamedDecl>();
18314     break;
18315 
18316   case LookupResult::FoundOverloaded:
18317     PrevDecl = Previous.getRepresentativeDecl();
18318     break;
18319 
18320   case LookupResult::NotFound:
18321   case LookupResult::NotFoundInCurrentInstantiation:
18322   case LookupResult::Ambiguous:
18323     break;
18324   }
18325 
18326   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18327     // Maybe we will complain about the shadowed template parameter.
18328     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18329     // Just pretend that we didn't see the previous declaration.
18330     PrevDecl = nullptr;
18331   }
18332 
18333   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18334     PrevDecl = nullptr;
18335 
18336   SourceLocation TSSL = D.getBeginLoc();
18337   MSPropertyDecl *NewPD =
18338       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18339                              MSPropertyAttr.getPropertyDataGetter(),
18340                              MSPropertyAttr.getPropertyDataSetter());
18341   ProcessDeclAttributes(TUScope, NewPD, D);
18342   NewPD->setAccess(AS);
18343 
18344   if (NewPD->isInvalidDecl())
18345     Record->setInvalidDecl();
18346 
18347   if (D.getDeclSpec().isModulePrivateSpecified())
18348     NewPD->setModulePrivate();
18349 
18350   if (NewPD->isInvalidDecl() && PrevDecl) {
18351     // Don't introduce NewFD into scope; there's already something
18352     // with the same name in the same scope.
18353   } else if (II) {
18354     PushOnScopeChains(NewPD, S);
18355   } else
18356     Record->addDecl(NewPD);
18357 
18358   return NewPD;
18359 }
18360 
18361 void Sema::ActOnStartFunctionDeclarationDeclarator(
18362     Declarator &Declarator, unsigned TemplateParameterDepth) {
18363   auto &Info = InventedParameterInfos.emplace_back();
18364   TemplateParameterList *ExplicitParams = nullptr;
18365   ArrayRef<TemplateParameterList *> ExplicitLists =
18366       Declarator.getTemplateParameterLists();
18367   if (!ExplicitLists.empty()) {
18368     bool IsMemberSpecialization, IsInvalid;
18369     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18370         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18371         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18372         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18373         /*SuppressDiagnostic=*/true);
18374   }
18375   if (ExplicitParams) {
18376     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18377     llvm::append_range(Info.TemplateParams, *ExplicitParams);
18378     Info.NumExplicitTemplateParams = ExplicitParams->size();
18379   } else {
18380     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18381     Info.NumExplicitTemplateParams = 0;
18382   }
18383 }
18384 
18385 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18386   auto &FSI = InventedParameterInfos.back();
18387   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18388     if (FSI.NumExplicitTemplateParams != 0) {
18389       TemplateParameterList *ExplicitParams =
18390           Declarator.getTemplateParameterLists().back();
18391       Declarator.setInventedTemplateParameterList(
18392           TemplateParameterList::Create(
18393               Context, ExplicitParams->getTemplateLoc(),
18394               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18395               ExplicitParams->getRAngleLoc(),
18396               ExplicitParams->getRequiresClause()));
18397     } else {
18398       Declarator.setInventedTemplateParameterList(
18399           TemplateParameterList::Create(
18400               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18401               SourceLocation(), /*RequiresClause=*/nullptr));
18402     }
18403   }
18404   InventedParameterInfos.pop_back();
18405 }
18406