xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp (revision d5b0e70f7e04d971691517ce1304d86a1e367e2e)
1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for C++ declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/AttributeCommonInfo.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/CXXFieldCollector.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Initialization.h"
36 #include "clang/Sema/Lookup.h"
37 #include "clang/Sema/ParsedTemplate.h"
38 #include "clang/Sema/Scope.h"
39 #include "clang/Sema/ScopeInfo.h"
40 #include "clang/Sema/SemaInternal.h"
41 #include "clang/Sema/Template.h"
42 #include "llvm/ADT/ScopeExit.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include <map>
47 #include <set>
48 
49 using namespace clang;
50 
51 //===----------------------------------------------------------------------===//
52 // CheckDefaultArgumentVisitor
53 //===----------------------------------------------------------------------===//
54 
55 namespace {
56 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
57 /// the default argument of a parameter to determine whether it
58 /// contains any ill-formed subexpressions. For example, this will
59 /// diagnose the use of local variables or parameters within the
60 /// default argument expression.
61 class CheckDefaultArgumentVisitor
62     : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
63   Sema &S;
64   const Expr *DefaultArg;
65 
66 public:
67   CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
68       : S(S), DefaultArg(DefaultArg) {}
69 
70   bool VisitExpr(const Expr *Node);
71   bool VisitDeclRefExpr(const DeclRefExpr *DRE);
72   bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
73   bool VisitLambdaExpr(const LambdaExpr *Lambda);
74   bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
75 };
76 
77 /// VisitExpr - Visit all of the children of this expression.
78 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
79   bool IsInvalid = false;
80   for (const Stmt *SubStmt : Node->children())
81     IsInvalid |= Visit(SubStmt);
82   return IsInvalid;
83 }
84 
85 /// VisitDeclRefExpr - Visit a reference to a declaration, to
86 /// determine whether this declaration can be used in the default
87 /// argument expression.
88 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
89   const NamedDecl *Decl = DRE->getDecl();
90   if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
91     // C++ [dcl.fct.default]p9:
92     //   [...] parameters of a function shall not be used in default
93     //   argument expressions, even if they are not evaluated. [...]
94     //
95     // C++17 [dcl.fct.default]p9 (by CWG 2082):
96     //   [...] A parameter shall not appear as a potentially-evaluated
97     //   expression in a default argument. [...]
98     //
99     if (DRE->isNonOdrUse() != NOUR_Unevaluated)
100       return S.Diag(DRE->getBeginLoc(),
101                     diag::err_param_default_argument_references_param)
102              << Param->getDeclName() << DefaultArg->getSourceRange();
103   } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
104     // C++ [dcl.fct.default]p7:
105     //   Local variables shall not be used in default argument
106     //   expressions.
107     //
108     // C++17 [dcl.fct.default]p7 (by CWG 2082):
109     //   A local variable shall not appear as a potentially-evaluated
110     //   expression in a default argument.
111     //
112     // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
113     //   Note: A local variable cannot be odr-used (6.3) in a default argument.
114     //
115     if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
116       return S.Diag(DRE->getBeginLoc(),
117                     diag::err_param_default_argument_references_local)
118              << VDecl->getDeclName() << DefaultArg->getSourceRange();
119   }
120 
121   return false;
122 }
123 
124 /// VisitCXXThisExpr - Visit a C++ "this" expression.
125 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
126   // C++ [dcl.fct.default]p8:
127   //   The keyword this shall not be used in a default argument of a
128   //   member function.
129   return S.Diag(ThisE->getBeginLoc(),
130                 diag::err_param_default_argument_references_this)
131          << ThisE->getSourceRange();
132 }
133 
134 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
135     const PseudoObjectExpr *POE) {
136   bool Invalid = false;
137   for (const Expr *E : POE->semantics()) {
138     // Look through bindings.
139     if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
140       E = OVE->getSourceExpr();
141       assert(E && "pseudo-object binding without source expression?");
142     }
143 
144     Invalid |= Visit(E);
145   }
146   return Invalid;
147 }
148 
149 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
150   // C++11 [expr.lambda.prim]p13:
151   //   A lambda-expression appearing in a default argument shall not
152   //   implicitly or explicitly capture any entity.
153   if (Lambda->capture_begin() == Lambda->capture_end())
154     return false;
155 
156   return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
157 }
158 } // namespace
159 
160 void
161 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
162                                                  const CXXMethodDecl *Method) {
163   // If we have an MSAny spec already, don't bother.
164   if (!Method || ComputedEST == EST_MSAny)
165     return;
166 
167   const FunctionProtoType *Proto
168     = Method->getType()->getAs<FunctionProtoType>();
169   Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
170   if (!Proto)
171     return;
172 
173   ExceptionSpecificationType EST = Proto->getExceptionSpecType();
174 
175   // If we have a throw-all spec at this point, ignore the function.
176   if (ComputedEST == EST_None)
177     return;
178 
179   if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
180     EST = EST_BasicNoexcept;
181 
182   switch (EST) {
183   case EST_Unparsed:
184   case EST_Uninstantiated:
185   case EST_Unevaluated:
186     llvm_unreachable("should not see unresolved exception specs here");
187 
188   // If this function can throw any exceptions, make a note of that.
189   case EST_MSAny:
190   case EST_None:
191     // FIXME: Whichever we see last of MSAny and None determines our result.
192     // We should make a consistent, order-independent choice here.
193     ClearExceptions();
194     ComputedEST = EST;
195     return;
196   case EST_NoexceptFalse:
197     ClearExceptions();
198     ComputedEST = EST_None;
199     return;
200   // FIXME: If the call to this decl is using any of its default arguments, we
201   // need to search them for potentially-throwing calls.
202   // If this function has a basic noexcept, it doesn't affect the outcome.
203   case EST_BasicNoexcept:
204   case EST_NoexceptTrue:
205   case EST_NoThrow:
206     return;
207   // If we're still at noexcept(true) and there's a throw() callee,
208   // change to that specification.
209   case EST_DynamicNone:
210     if (ComputedEST == EST_BasicNoexcept)
211       ComputedEST = EST_DynamicNone;
212     return;
213   case EST_DependentNoexcept:
214     llvm_unreachable(
215         "should not generate implicit declarations for dependent cases");
216   case EST_Dynamic:
217     break;
218   }
219   assert(EST == EST_Dynamic && "EST case not considered earlier.");
220   assert(ComputedEST != EST_None &&
221          "Shouldn't collect exceptions when throw-all is guaranteed.");
222   ComputedEST = EST_Dynamic;
223   // Record the exceptions in this function's exception specification.
224   for (const auto &E : Proto->exceptions())
225     if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
226       Exceptions.push_back(E);
227 }
228 
229 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
230   if (!S || ComputedEST == EST_MSAny)
231     return;
232 
233   // FIXME:
234   //
235   // C++0x [except.spec]p14:
236   //   [An] implicit exception-specification specifies the type-id T if and
237   // only if T is allowed by the exception-specification of a function directly
238   // invoked by f's implicit definition; f shall allow all exceptions if any
239   // function it directly invokes allows all exceptions, and f shall allow no
240   // exceptions if every function it directly invokes allows no exceptions.
241   //
242   // Note in particular that if an implicit exception-specification is generated
243   // for a function containing a throw-expression, that specification can still
244   // be noexcept(true).
245   //
246   // Note also that 'directly invoked' is not defined in the standard, and there
247   // is no indication that we should only consider potentially-evaluated calls.
248   //
249   // Ultimately we should implement the intent of the standard: the exception
250   // specification should be the set of exceptions which can be thrown by the
251   // implicit definition. For now, we assume that any non-nothrow expression can
252   // throw any exception.
253 
254   if (Self->canThrow(S))
255     ComputedEST = EST_None;
256 }
257 
258 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
259                                              SourceLocation EqualLoc) {
260   if (RequireCompleteType(Param->getLocation(), Param->getType(),
261                           diag::err_typecheck_decl_incomplete_type))
262     return true;
263 
264   // C++ [dcl.fct.default]p5
265   //   A default argument expression is implicitly converted (clause
266   //   4) to the parameter type. The default argument expression has
267   //   the same semantic constraints as the initializer expression in
268   //   a declaration of a variable of the parameter type, using the
269   //   copy-initialization semantics (8.5).
270   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
271                                                                     Param);
272   InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
273                                                            EqualLoc);
274   InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276   if (Result.isInvalid())
277     return true;
278   Arg = Result.getAs<Expr>();
279 
280   CheckCompletedExpr(Arg, EqualLoc);
281   Arg = MaybeCreateExprWithCleanups(Arg);
282 
283   return Arg;
284 }
285 
286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
287                                    SourceLocation EqualLoc) {
288   // Add the default argument to the parameter
289   Param->setDefaultArg(Arg);
290 
291   // We have already instantiated this parameter; provide each of the
292   // instantiations with the uninstantiated default argument.
293   UnparsedDefaultArgInstantiationsMap::iterator InstPos
294     = UnparsedDefaultArgInstantiations.find(Param);
295   if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296     for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
297       InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
298 
299     // We're done tracking this parameter's instantiations.
300     UnparsedDefaultArgInstantiations.erase(InstPos);
301   }
302 }
303 
304 /// ActOnParamDefaultArgument - Check whether the default argument
305 /// provided for a function parameter is well-formed. If so, attach it
306 /// to the parameter declaration.
307 void
308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
309                                 Expr *DefaultArg) {
310   if (!param || !DefaultArg)
311     return;
312 
313   ParmVarDecl *Param = cast<ParmVarDecl>(param);
314   UnparsedDefaultArgLocs.erase(Param);
315 
316   auto Fail = [&] {
317     Param->setInvalidDecl();
318     Param->setDefaultArg(new (Context) OpaqueValueExpr(
319         EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
320   };
321 
322   // Default arguments are only permitted in C++
323   if (!getLangOpts().CPlusPlus) {
324     Diag(EqualLoc, diag::err_param_default_argument)
325       << DefaultArg->getSourceRange();
326     return Fail();
327   }
328 
329   // Check for unexpanded parameter packs.
330   if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
331     return Fail();
332   }
333 
334   // C++11 [dcl.fct.default]p3
335   //   A default argument expression [...] shall not be specified for a
336   //   parameter pack.
337   if (Param->isParameterPack()) {
338     Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339         << DefaultArg->getSourceRange();
340     // Recover by discarding the default argument.
341     Param->setDefaultArg(nullptr);
342     return;
343   }
344 
345   ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346   if (Result.isInvalid())
347     return Fail();
348 
349   DefaultArg = Result.getAs<Expr>();
350 
351   // Check that the default argument is well-formed
352   CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353   if (DefaultArgChecker.Visit(DefaultArg))
354     return Fail();
355 
356   SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
357 }
358 
359 /// ActOnParamUnparsedDefaultArgument - We've seen a default
360 /// argument for a function parameter, but we can't parse it yet
361 /// because we're inside a class definition. Note that this default
362 /// argument will be parsed later.
363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
364                                              SourceLocation EqualLoc,
365                                              SourceLocation ArgLoc) {
366   if (!param)
367     return;
368 
369   ParmVarDecl *Param = cast<ParmVarDecl>(param);
370   Param->setUnparsedDefaultArg();
371   UnparsedDefaultArgLocs[Param] = ArgLoc;
372 }
373 
374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375 /// the default argument for the parameter param failed.
376 void Sema::ActOnParamDefaultArgumentError(Decl *param,
377                                           SourceLocation EqualLoc) {
378   if (!param)
379     return;
380 
381   ParmVarDecl *Param = cast<ParmVarDecl>(param);
382   Param->setInvalidDecl();
383   UnparsedDefaultArgLocs.erase(Param);
384   Param->setDefaultArg(new (Context) OpaqueValueExpr(
385       EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
386 }
387 
388 /// CheckExtraCXXDefaultArguments - Check for any extra default
389 /// arguments in the declarator, which is not a function declaration
390 /// or definition and therefore is not permitted to have default
391 /// arguments. This routine should be invoked for every declarator
392 /// that is not a function declaration or definition.
393 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
394   // C++ [dcl.fct.default]p3
395   //   A default argument expression shall be specified only in the
396   //   parameter-declaration-clause of a function declaration or in a
397   //   template-parameter (14.1). It shall not be specified for a
398   //   parameter pack. If it is specified in a
399   //   parameter-declaration-clause, it shall not occur within a
400   //   declarator or abstract-declarator of a parameter-declaration.
401   bool MightBeFunction = D.isFunctionDeclarationContext();
402   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
403     DeclaratorChunk &chunk = D.getTypeObject(i);
404     if (chunk.Kind == DeclaratorChunk::Function) {
405       if (MightBeFunction) {
406         // This is a function declaration. It can have default arguments, but
407         // keep looking in case its return type is a function type with default
408         // arguments.
409         MightBeFunction = false;
410         continue;
411       }
412       for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
413            ++argIdx) {
414         ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
415         if (Param->hasUnparsedDefaultArg()) {
416           std::unique_ptr<CachedTokens> Toks =
417               std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
418           SourceRange SR;
419           if (Toks->size() > 1)
420             SR = SourceRange((*Toks)[1].getLocation(),
421                              Toks->back().getLocation());
422           else
423             SR = UnparsedDefaultArgLocs[Param];
424           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
425             << SR;
426         } else if (Param->getDefaultArg()) {
427           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
428             << Param->getDefaultArg()->getSourceRange();
429           Param->setDefaultArg(nullptr);
430         }
431       }
432     } else if (chunk.Kind != DeclaratorChunk::Paren) {
433       MightBeFunction = false;
434     }
435   }
436 }
437 
438 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
439   return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
440     return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
441   });
442 }
443 
444 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
445 /// function, once we already know that they have the same
446 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
447 /// error, false otherwise.
448 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
449                                 Scope *S) {
450   bool Invalid = false;
451 
452   // The declaration context corresponding to the scope is the semantic
453   // parent, unless this is a local function declaration, in which case
454   // it is that surrounding function.
455   DeclContext *ScopeDC = New->isLocalExternDecl()
456                              ? New->getLexicalDeclContext()
457                              : New->getDeclContext();
458 
459   // Find the previous declaration for the purpose of default arguments.
460   FunctionDecl *PrevForDefaultArgs = Old;
461   for (/**/; PrevForDefaultArgs;
462        // Don't bother looking back past the latest decl if this is a local
463        // extern declaration; nothing else could work.
464        PrevForDefaultArgs = New->isLocalExternDecl()
465                                 ? nullptr
466                                 : PrevForDefaultArgs->getPreviousDecl()) {
467     // Ignore hidden declarations.
468     if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
469       continue;
470 
471     if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
472         !New->isCXXClassMember()) {
473       // Ignore default arguments of old decl if they are not in
474       // the same scope and this is not an out-of-line definition of
475       // a member function.
476       continue;
477     }
478 
479     if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
480       // If only one of these is a local function declaration, then they are
481       // declared in different scopes, even though isDeclInScope may think
482       // they're in the same scope. (If both are local, the scope check is
483       // sufficient, and if neither is local, then they are in the same scope.)
484       continue;
485     }
486 
487     // We found the right previous declaration.
488     break;
489   }
490 
491   // C++ [dcl.fct.default]p4:
492   //   For non-template functions, default arguments can be added in
493   //   later declarations of a function in the same
494   //   scope. Declarations in different scopes have completely
495   //   distinct sets of default arguments. That is, declarations in
496   //   inner scopes do not acquire default arguments from
497   //   declarations in outer scopes, and vice versa. In a given
498   //   function declaration, all parameters subsequent to a
499   //   parameter with a default argument shall have default
500   //   arguments supplied in this or previous declarations. A
501   //   default argument shall not be redefined by a later
502   //   declaration (not even to the same value).
503   //
504   // C++ [dcl.fct.default]p6:
505   //   Except for member functions of class templates, the default arguments
506   //   in a member function definition that appears outside of the class
507   //   definition are added to the set of default arguments provided by the
508   //   member function declaration in the class definition.
509   for (unsigned p = 0, NumParams = PrevForDefaultArgs
510                                        ? PrevForDefaultArgs->getNumParams()
511                                        : 0;
512        p < NumParams; ++p) {
513     ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
514     ParmVarDecl *NewParam = New->getParamDecl(p);
515 
516     bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
517     bool NewParamHasDfl = NewParam->hasDefaultArg();
518 
519     if (OldParamHasDfl && NewParamHasDfl) {
520       unsigned DiagDefaultParamID =
521         diag::err_param_default_argument_redefinition;
522 
523       // MSVC accepts that default parameters be redefined for member functions
524       // of template class. The new default parameter's value is ignored.
525       Invalid = true;
526       if (getLangOpts().MicrosoftExt) {
527         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
528         if (MD && MD->getParent()->getDescribedClassTemplate()) {
529           // Merge the old default argument into the new parameter.
530           NewParam->setHasInheritedDefaultArg();
531           if (OldParam->hasUninstantiatedDefaultArg())
532             NewParam->setUninstantiatedDefaultArg(
533                                       OldParam->getUninstantiatedDefaultArg());
534           else
535             NewParam->setDefaultArg(OldParam->getInit());
536           DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
537           Invalid = false;
538         }
539       }
540 
541       // FIXME: If we knew where the '=' was, we could easily provide a fix-it
542       // hint here. Alternatively, we could walk the type-source information
543       // for NewParam to find the last source location in the type... but it
544       // isn't worth the effort right now. This is the kind of test case that
545       // is hard to get right:
546       //   int f(int);
547       //   void g(int (*fp)(int) = f);
548       //   void g(int (*fp)(int) = &f);
549       Diag(NewParam->getLocation(), DiagDefaultParamID)
550         << NewParam->getDefaultArgRange();
551 
552       // Look for the function declaration where the default argument was
553       // actually written, which may be a declaration prior to Old.
554       for (auto Older = PrevForDefaultArgs;
555            OldParam->hasInheritedDefaultArg(); /**/) {
556         Older = Older->getPreviousDecl();
557         OldParam = Older->getParamDecl(p);
558       }
559 
560       Diag(OldParam->getLocation(), diag::note_previous_definition)
561         << OldParam->getDefaultArgRange();
562     } else if (OldParamHasDfl) {
563       // Merge the old default argument into the new parameter unless the new
564       // function is a friend declaration in a template class. In the latter
565       // case the default arguments will be inherited when the friend
566       // declaration will be instantiated.
567       if (New->getFriendObjectKind() == Decl::FOK_None ||
568           !New->getLexicalDeclContext()->isDependentContext()) {
569         // It's important to use getInit() here;  getDefaultArg()
570         // strips off any top-level ExprWithCleanups.
571         NewParam->setHasInheritedDefaultArg();
572         if (OldParam->hasUnparsedDefaultArg())
573           NewParam->setUnparsedDefaultArg();
574         else if (OldParam->hasUninstantiatedDefaultArg())
575           NewParam->setUninstantiatedDefaultArg(
576                                        OldParam->getUninstantiatedDefaultArg());
577         else
578           NewParam->setDefaultArg(OldParam->getInit());
579       }
580     } else if (NewParamHasDfl) {
581       if (New->getDescribedFunctionTemplate()) {
582         // Paragraph 4, quoted above, only applies to non-template functions.
583         Diag(NewParam->getLocation(),
584              diag::err_param_default_argument_template_redecl)
585           << NewParam->getDefaultArgRange();
586         Diag(PrevForDefaultArgs->getLocation(),
587              diag::note_template_prev_declaration)
588             << false;
589       } else if (New->getTemplateSpecializationKind()
590                    != TSK_ImplicitInstantiation &&
591                  New->getTemplateSpecializationKind() != TSK_Undeclared) {
592         // C++ [temp.expr.spec]p21:
593         //   Default function arguments shall not be specified in a declaration
594         //   or a definition for one of the following explicit specializations:
595         //     - the explicit specialization of a function template;
596         //     - the explicit specialization of a member function template;
597         //     - the explicit specialization of a member function of a class
598         //       template where the class template specialization to which the
599         //       member function specialization belongs is implicitly
600         //       instantiated.
601         Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
602           << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
603           << New->getDeclName()
604           << NewParam->getDefaultArgRange();
605       } else if (New->getDeclContext()->isDependentContext()) {
606         // C++ [dcl.fct.default]p6 (DR217):
607         //   Default arguments for a member function of a class template shall
608         //   be specified on the initial declaration of the member function
609         //   within the class template.
610         //
611         // Reading the tea leaves a bit in DR217 and its reference to DR205
612         // leads me to the conclusion that one cannot add default function
613         // arguments for an out-of-line definition of a member function of a
614         // dependent type.
615         int WhichKind = 2;
616         if (CXXRecordDecl *Record
617               = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
618           if (Record->getDescribedClassTemplate())
619             WhichKind = 0;
620           else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
621             WhichKind = 1;
622           else
623             WhichKind = 2;
624         }
625 
626         Diag(NewParam->getLocation(),
627              diag::err_param_default_argument_member_template_redecl)
628           << WhichKind
629           << NewParam->getDefaultArgRange();
630       }
631     }
632   }
633 
634   // DR1344: If a default argument is added outside a class definition and that
635   // default argument makes the function a special member function, the program
636   // is ill-formed. This can only happen for constructors.
637   if (isa<CXXConstructorDecl>(New) &&
638       New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
639     CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
640                      OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
641     if (NewSM != OldSM) {
642       ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
643       assert(NewParam->hasDefaultArg());
644       Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
645         << NewParam->getDefaultArgRange() << NewSM;
646       Diag(Old->getLocation(), diag::note_previous_declaration);
647     }
648   }
649 
650   const FunctionDecl *Def;
651   // C++11 [dcl.constexpr]p1: If any declaration of a function or function
652   // template has a constexpr specifier then all its declarations shall
653   // contain the constexpr specifier.
654   if (New->getConstexprKind() != Old->getConstexprKind()) {
655     Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
656         << New << static_cast<int>(New->getConstexprKind())
657         << static_cast<int>(Old->getConstexprKind());
658     Diag(Old->getLocation(), diag::note_previous_declaration);
659     Invalid = true;
660   } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
661              Old->isDefined(Def) &&
662              // If a friend function is inlined but does not have 'inline'
663              // specifier, it is a definition. Do not report attribute conflict
664              // in this case, redefinition will be diagnosed later.
665              (New->isInlineSpecified() ||
666               New->getFriendObjectKind() == Decl::FOK_None)) {
667     // C++11 [dcl.fcn.spec]p4:
668     //   If the definition of a function appears in a translation unit before its
669     //   first declaration as inline, the program is ill-formed.
670     Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
671     Diag(Def->getLocation(), diag::note_previous_definition);
672     Invalid = true;
673   }
674 
675   // C++17 [temp.deduct.guide]p3:
676   //   Two deduction guide declarations in the same translation unit
677   //   for the same class template shall not have equivalent
678   //   parameter-declaration-clauses.
679   if (isa<CXXDeductionGuideDecl>(New) &&
680       !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
681     Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
682     Diag(Old->getLocation(), diag::note_previous_declaration);
683   }
684 
685   // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
686   // argument expression, that declaration shall be a definition and shall be
687   // the only declaration of the function or function template in the
688   // translation unit.
689   if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
690       functionDeclHasDefaultArgument(Old)) {
691     Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
692     Diag(Old->getLocation(), diag::note_previous_declaration);
693     Invalid = true;
694   }
695 
696   // C++11 [temp.friend]p4 (DR329):
697   //   When a function is defined in a friend function declaration in a class
698   //   template, the function is instantiated when the function is odr-used.
699   //   The same restrictions on multiple declarations and definitions that
700   //   apply to non-template function declarations and definitions also apply
701   //   to these implicit definitions.
702   const FunctionDecl *OldDefinition = nullptr;
703   if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
704       Old->isDefined(OldDefinition, true))
705     CheckForFunctionRedefinition(New, OldDefinition);
706 
707   return Invalid;
708 }
709 
710 NamedDecl *
711 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
712                                    MultiTemplateParamsArg TemplateParamLists) {
713   assert(D.isDecompositionDeclarator());
714   const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
715 
716   // The syntax only allows a decomposition declarator as a simple-declaration,
717   // a for-range-declaration, or a condition in Clang, but we parse it in more
718   // cases than that.
719   if (!D.mayHaveDecompositionDeclarator()) {
720     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
721       << Decomp.getSourceRange();
722     return nullptr;
723   }
724 
725   if (!TemplateParamLists.empty()) {
726     // FIXME: There's no rule against this, but there are also no rules that
727     // would actually make it usable, so we reject it for now.
728     Diag(TemplateParamLists.front()->getTemplateLoc(),
729          diag::err_decomp_decl_template);
730     return nullptr;
731   }
732 
733   Diag(Decomp.getLSquareLoc(),
734        !getLangOpts().CPlusPlus17
735            ? diag::ext_decomp_decl
736            : D.getContext() == DeclaratorContext::Condition
737                  ? diag::ext_decomp_decl_cond
738                  : diag::warn_cxx14_compat_decomp_decl)
739       << Decomp.getSourceRange();
740 
741   // The semantic context is always just the current context.
742   DeclContext *const DC = CurContext;
743 
744   // C++17 [dcl.dcl]/8:
745   //   The decl-specifier-seq shall contain only the type-specifier auto
746   //   and cv-qualifiers.
747   // C++2a [dcl.dcl]/8:
748   //   If decl-specifier-seq contains any decl-specifier other than static,
749   //   thread_local, auto, or cv-qualifiers, the program is ill-formed.
750   auto &DS = D.getDeclSpec();
751   {
752     SmallVector<StringRef, 8> BadSpecifiers;
753     SmallVector<SourceLocation, 8> BadSpecifierLocs;
754     SmallVector<StringRef, 8> CPlusPlus20Specifiers;
755     SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
756     if (auto SCS = DS.getStorageClassSpec()) {
757       if (SCS == DeclSpec::SCS_static) {
758         CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
759         CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
760       } else {
761         BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
762         BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
763       }
764     }
765     if (auto TSCS = DS.getThreadStorageClassSpec()) {
766       CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
767       CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
768     }
769     if (DS.hasConstexprSpecifier()) {
770       BadSpecifiers.push_back(
771           DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
772       BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
773     }
774     if (DS.isInlineSpecified()) {
775       BadSpecifiers.push_back("inline");
776       BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
777     }
778     if (!BadSpecifiers.empty()) {
779       auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
780       Err << (int)BadSpecifiers.size()
781           << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
782       // Don't add FixItHints to remove the specifiers; we do still respect
783       // them when building the underlying variable.
784       for (auto Loc : BadSpecifierLocs)
785         Err << SourceRange(Loc, Loc);
786     } else if (!CPlusPlus20Specifiers.empty()) {
787       auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
788                          getLangOpts().CPlusPlus20
789                              ? diag::warn_cxx17_compat_decomp_decl_spec
790                              : diag::ext_decomp_decl_spec);
791       Warn << (int)CPlusPlus20Specifiers.size()
792            << llvm::join(CPlusPlus20Specifiers.begin(),
793                          CPlusPlus20Specifiers.end(), " ");
794       for (auto Loc : CPlusPlus20SpecifierLocs)
795         Warn << SourceRange(Loc, Loc);
796     }
797     // We can't recover from it being declared as a typedef.
798     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
799       return nullptr;
800   }
801 
802   // C++2a [dcl.struct.bind]p1:
803   //   A cv that includes volatile is deprecated
804   if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
805       getLangOpts().CPlusPlus20)
806     Diag(DS.getVolatileSpecLoc(),
807          diag::warn_deprecated_volatile_structured_binding);
808 
809   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
810   QualType R = TInfo->getType();
811 
812   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
813                                       UPPC_DeclarationType))
814     D.setInvalidType();
815 
816   // The syntax only allows a single ref-qualifier prior to the decomposition
817   // declarator. No other declarator chunks are permitted. Also check the type
818   // specifier here.
819   if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
820       D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
821       (D.getNumTypeObjects() == 1 &&
822        D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
823     Diag(Decomp.getLSquareLoc(),
824          (D.hasGroupingParens() ||
825           (D.getNumTypeObjects() &&
826            D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
827              ? diag::err_decomp_decl_parens
828              : diag::err_decomp_decl_type)
829         << R;
830 
831     // In most cases, there's no actual problem with an explicitly-specified
832     // type, but a function type won't work here, and ActOnVariableDeclarator
833     // shouldn't be called for such a type.
834     if (R->isFunctionType())
835       D.setInvalidType();
836   }
837 
838   // Build the BindingDecls.
839   SmallVector<BindingDecl*, 8> Bindings;
840 
841   // Build the BindingDecls.
842   for (auto &B : D.getDecompositionDeclarator().bindings()) {
843     // Check for name conflicts.
844     DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
845     LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
846                           ForVisibleRedeclaration);
847     LookupName(Previous, S,
848                /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
849 
850     // It's not permitted to shadow a template parameter name.
851     if (Previous.isSingleResult() &&
852         Previous.getFoundDecl()->isTemplateParameter()) {
853       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
854                                       Previous.getFoundDecl());
855       Previous.clear();
856     }
857 
858     auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
859 
860     // Find the shadowed declaration before filtering for scope.
861     NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
862                                   ? getShadowedDeclaration(BD, Previous)
863                                   : nullptr;
864 
865     bool ConsiderLinkage = DC->isFunctionOrMethod() &&
866                            DS.getStorageClassSpec() == DeclSpec::SCS_extern;
867     FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
868                          /*AllowInlineNamespace*/false);
869 
870     if (!Previous.empty()) {
871       auto *Old = Previous.getRepresentativeDecl();
872       Diag(B.NameLoc, diag::err_redefinition) << B.Name;
873       Diag(Old->getLocation(), diag::note_previous_definition);
874     } else if (ShadowedDecl && !D.isRedeclaration()) {
875       CheckShadow(BD, ShadowedDecl, Previous);
876     }
877     PushOnScopeChains(BD, S, true);
878     Bindings.push_back(BD);
879     ParsingInitForAutoVars.insert(BD);
880   }
881 
882   // There are no prior lookup results for the variable itself, because it
883   // is unnamed.
884   DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
885                                Decomp.getLSquareLoc());
886   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
887                         ForVisibleRedeclaration);
888 
889   // Build the variable that holds the non-decomposed object.
890   bool AddToScope = true;
891   NamedDecl *New =
892       ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
893                               MultiTemplateParamsArg(), AddToScope, Bindings);
894   if (AddToScope) {
895     S->AddDecl(New);
896     CurContext->addHiddenDecl(New);
897   }
898 
899   if (isInOpenMPDeclareTargetContext())
900     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
901 
902   return New;
903 }
904 
905 static bool checkSimpleDecomposition(
906     Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
907     QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
908     llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
909   if ((int64_t)Bindings.size() != NumElems) {
910     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
911         << DecompType << (unsigned)Bindings.size()
912         << (unsigned)NumElems.getLimitedValue(UINT_MAX)
913         << toString(NumElems, 10) << (NumElems < Bindings.size());
914     return true;
915   }
916 
917   unsigned I = 0;
918   for (auto *B : Bindings) {
919     SourceLocation Loc = B->getLocation();
920     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
921     if (E.isInvalid())
922       return true;
923     E = GetInit(Loc, E.get(), I++);
924     if (E.isInvalid())
925       return true;
926     B->setBinding(ElemType, E.get());
927   }
928 
929   return false;
930 }
931 
932 static bool checkArrayLikeDecomposition(Sema &S,
933                                         ArrayRef<BindingDecl *> Bindings,
934                                         ValueDecl *Src, QualType DecompType,
935                                         const llvm::APSInt &NumElems,
936                                         QualType ElemType) {
937   return checkSimpleDecomposition(
938       S, Bindings, Src, DecompType, NumElems, ElemType,
939       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
940         ExprResult E = S.ActOnIntegerConstant(Loc, I);
941         if (E.isInvalid())
942           return ExprError();
943         return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
944       });
945 }
946 
947 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
948                                     ValueDecl *Src, QualType DecompType,
949                                     const ConstantArrayType *CAT) {
950   return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
951                                      llvm::APSInt(CAT->getSize()),
952                                      CAT->getElementType());
953 }
954 
955 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
956                                      ValueDecl *Src, QualType DecompType,
957                                      const VectorType *VT) {
958   return checkArrayLikeDecomposition(
959       S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
960       S.Context.getQualifiedType(VT->getElementType(),
961                                  DecompType.getQualifiers()));
962 }
963 
964 static bool checkComplexDecomposition(Sema &S,
965                                       ArrayRef<BindingDecl *> Bindings,
966                                       ValueDecl *Src, QualType DecompType,
967                                       const ComplexType *CT) {
968   return checkSimpleDecomposition(
969       S, Bindings, Src, DecompType, llvm::APSInt::get(2),
970       S.Context.getQualifiedType(CT->getElementType(),
971                                  DecompType.getQualifiers()),
972       [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
973         return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
974       });
975 }
976 
977 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
978                                      TemplateArgumentListInfo &Args,
979                                      const TemplateParameterList *Params) {
980   SmallString<128> SS;
981   llvm::raw_svector_ostream OS(SS);
982   bool First = true;
983   unsigned I = 0;
984   for (auto &Arg : Args.arguments()) {
985     if (!First)
986       OS << ", ";
987     Arg.getArgument().print(PrintingPolicy, OS,
988                             TemplateParameterList::shouldIncludeTypeForArgument(
989                                 PrintingPolicy, Params, I));
990     First = false;
991     I++;
992   }
993   return std::string(OS.str());
994 }
995 
996 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
997                                      SourceLocation Loc, StringRef Trait,
998                                      TemplateArgumentListInfo &Args,
999                                      unsigned DiagID) {
1000   auto DiagnoseMissing = [&] {
1001     if (DiagID)
1002       S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1003                                                Args, /*Params*/ nullptr);
1004     return true;
1005   };
1006 
1007   // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1008   NamespaceDecl *Std = S.getStdNamespace();
1009   if (!Std)
1010     return DiagnoseMissing();
1011 
1012   // Look up the trait itself, within namespace std. We can diagnose various
1013   // problems with this lookup even if we've been asked to not diagnose a
1014   // missing specialization, because this can only fail if the user has been
1015   // declaring their own names in namespace std or we don't support the
1016   // standard library implementation in use.
1017   LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1018                       Loc, Sema::LookupOrdinaryName);
1019   if (!S.LookupQualifiedName(Result, Std))
1020     return DiagnoseMissing();
1021   if (Result.isAmbiguous())
1022     return true;
1023 
1024   ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1025   if (!TraitTD) {
1026     Result.suppressDiagnostics();
1027     NamedDecl *Found = *Result.begin();
1028     S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1029     S.Diag(Found->getLocation(), diag::note_declared_at);
1030     return true;
1031   }
1032 
1033   // Build the template-id.
1034   QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1035   if (TraitTy.isNull())
1036     return true;
1037   if (!S.isCompleteType(Loc, TraitTy)) {
1038     if (DiagID)
1039       S.RequireCompleteType(
1040           Loc, TraitTy, DiagID,
1041           printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1042                             TraitTD->getTemplateParameters()));
1043     return true;
1044   }
1045 
1046   CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1047   assert(RD && "specialization of class template is not a class?");
1048 
1049   // Look up the member of the trait type.
1050   S.LookupQualifiedName(TraitMemberLookup, RD);
1051   return TraitMemberLookup.isAmbiguous();
1052 }
1053 
1054 static TemplateArgumentLoc
1055 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1056                                    uint64_t I) {
1057   TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1058   return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1059 }
1060 
1061 static TemplateArgumentLoc
1062 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1063   return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1064 }
1065 
1066 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1067 
1068 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1069                                llvm::APSInt &Size) {
1070   EnterExpressionEvaluationContext ContextRAII(
1071       S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1072 
1073   DeclarationName Value = S.PP.getIdentifierInfo("value");
1074   LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1075 
1076   // Form template argument list for tuple_size<T>.
1077   TemplateArgumentListInfo Args(Loc, Loc);
1078   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1079 
1080   // If there's no tuple_size specialization or the lookup of 'value' is empty,
1081   // it's not tuple-like.
1082   if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1083       R.empty())
1084     return IsTupleLike::NotTupleLike;
1085 
1086   // If we get this far, we've committed to the tuple interpretation, but
1087   // we can still fail if there actually isn't a usable ::value.
1088 
1089   struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1090     LookupResult &R;
1091     TemplateArgumentListInfo &Args;
1092     ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1093         : R(R), Args(Args) {}
1094     Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1095                                                SourceLocation Loc) override {
1096       return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1097              << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1098                                   /*Params*/ nullptr);
1099     }
1100   } Diagnoser(R, Args);
1101 
1102   ExprResult E =
1103       S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1104   if (E.isInvalid())
1105     return IsTupleLike::Error;
1106 
1107   E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1108   if (E.isInvalid())
1109     return IsTupleLike::Error;
1110 
1111   return IsTupleLike::TupleLike;
1112 }
1113 
1114 /// \return std::tuple_element<I, T>::type.
1115 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1116                                         unsigned I, QualType T) {
1117   // Form template argument list for tuple_element<I, T>.
1118   TemplateArgumentListInfo Args(Loc, Loc);
1119   Args.addArgument(
1120       getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1121   Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1122 
1123   DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1124   LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1125   if (lookupStdTypeTraitMember(
1126           S, R, Loc, "tuple_element", Args,
1127           diag::err_decomp_decl_std_tuple_element_not_specialized))
1128     return QualType();
1129 
1130   auto *TD = R.getAsSingle<TypeDecl>();
1131   if (!TD) {
1132     R.suppressDiagnostics();
1133     S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1134         << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1135                              /*Params*/ nullptr);
1136     if (!R.empty())
1137       S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1138     return QualType();
1139   }
1140 
1141   return S.Context.getTypeDeclType(TD);
1142 }
1143 
1144 namespace {
1145 struct InitializingBinding {
1146   Sema &S;
1147   InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1148     Sema::CodeSynthesisContext Ctx;
1149     Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1150     Ctx.PointOfInstantiation = BD->getLocation();
1151     Ctx.Entity = BD;
1152     S.pushCodeSynthesisContext(Ctx);
1153   }
1154   ~InitializingBinding() {
1155     S.popCodeSynthesisContext();
1156   }
1157 };
1158 }
1159 
1160 static bool checkTupleLikeDecomposition(Sema &S,
1161                                         ArrayRef<BindingDecl *> Bindings,
1162                                         VarDecl *Src, QualType DecompType,
1163                                         const llvm::APSInt &TupleSize) {
1164   if ((int64_t)Bindings.size() != TupleSize) {
1165     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1166         << DecompType << (unsigned)Bindings.size()
1167         << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1168         << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1169     return true;
1170   }
1171 
1172   if (Bindings.empty())
1173     return false;
1174 
1175   DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1176 
1177   // [dcl.decomp]p3:
1178   //   The unqualified-id get is looked up in the scope of E by class member
1179   //   access lookup ...
1180   LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1181   bool UseMemberGet = false;
1182   if (S.isCompleteType(Src->getLocation(), DecompType)) {
1183     if (auto *RD = DecompType->getAsCXXRecordDecl())
1184       S.LookupQualifiedName(MemberGet, RD);
1185     if (MemberGet.isAmbiguous())
1186       return true;
1187     //   ... and if that finds at least one declaration that is a function
1188     //   template whose first template parameter is a non-type parameter ...
1189     for (NamedDecl *D : MemberGet) {
1190       if (FunctionTemplateDecl *FTD =
1191               dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1192         TemplateParameterList *TPL = FTD->getTemplateParameters();
1193         if (TPL->size() != 0 &&
1194             isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1195           //   ... the initializer is e.get<i>().
1196           UseMemberGet = true;
1197           break;
1198         }
1199       }
1200     }
1201   }
1202 
1203   unsigned I = 0;
1204   for (auto *B : Bindings) {
1205     InitializingBinding InitContext(S, B);
1206     SourceLocation Loc = B->getLocation();
1207 
1208     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1209     if (E.isInvalid())
1210       return true;
1211 
1212     //   e is an lvalue if the type of the entity is an lvalue reference and
1213     //   an xvalue otherwise
1214     if (!Src->getType()->isLValueReferenceType())
1215       E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1216                                    E.get(), nullptr, VK_XValue,
1217                                    FPOptionsOverride());
1218 
1219     TemplateArgumentListInfo Args(Loc, Loc);
1220     Args.addArgument(
1221         getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1222 
1223     if (UseMemberGet) {
1224       //   if [lookup of member get] finds at least one declaration, the
1225       //   initializer is e.get<i-1>().
1226       E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1227                                      CXXScopeSpec(), SourceLocation(), nullptr,
1228                                      MemberGet, &Args, nullptr);
1229       if (E.isInvalid())
1230         return true;
1231 
1232       E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1233     } else {
1234       //   Otherwise, the initializer is get<i-1>(e), where get is looked up
1235       //   in the associated namespaces.
1236       Expr *Get = UnresolvedLookupExpr::Create(
1237           S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1238           DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1239           UnresolvedSetIterator(), UnresolvedSetIterator());
1240 
1241       Expr *Arg = E.get();
1242       E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1243     }
1244     if (E.isInvalid())
1245       return true;
1246     Expr *Init = E.get();
1247 
1248     //   Given the type T designated by std::tuple_element<i - 1, E>::type,
1249     QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1250     if (T.isNull())
1251       return true;
1252 
1253     //   each vi is a variable of type "reference to T" initialized with the
1254     //   initializer, where the reference is an lvalue reference if the
1255     //   initializer is an lvalue and an rvalue reference otherwise
1256     QualType RefType =
1257         S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1258     if (RefType.isNull())
1259       return true;
1260     auto *RefVD = VarDecl::Create(
1261         S.Context, Src->getDeclContext(), Loc, Loc,
1262         B->getDeclName().getAsIdentifierInfo(), RefType,
1263         S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1264     RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1265     RefVD->setTSCSpec(Src->getTSCSpec());
1266     RefVD->setImplicit();
1267     if (Src->isInlineSpecified())
1268       RefVD->setInlineSpecified();
1269     RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1270 
1271     InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1272     InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1273     InitializationSequence Seq(S, Entity, Kind, Init);
1274     E = Seq.Perform(S, Entity, Kind, Init);
1275     if (E.isInvalid())
1276       return true;
1277     E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1278     if (E.isInvalid())
1279       return true;
1280     RefVD->setInit(E.get());
1281     S.CheckCompleteVariableDeclaration(RefVD);
1282 
1283     E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1284                                    DeclarationNameInfo(B->getDeclName(), Loc),
1285                                    RefVD);
1286     if (E.isInvalid())
1287       return true;
1288 
1289     B->setBinding(T, E.get());
1290     I++;
1291   }
1292 
1293   return false;
1294 }
1295 
1296 /// Find the base class to decompose in a built-in decomposition of a class type.
1297 /// This base class search is, unfortunately, not quite like any other that we
1298 /// perform anywhere else in C++.
1299 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1300                                                 const CXXRecordDecl *RD,
1301                                                 CXXCastPath &BasePath) {
1302   auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1303                           CXXBasePath &Path) {
1304     return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1305   };
1306 
1307   const CXXRecordDecl *ClassWithFields = nullptr;
1308   AccessSpecifier AS = AS_public;
1309   if (RD->hasDirectFields())
1310     // [dcl.decomp]p4:
1311     //   Otherwise, all of E's non-static data members shall be public direct
1312     //   members of E ...
1313     ClassWithFields = RD;
1314   else {
1315     //   ... or of ...
1316     CXXBasePaths Paths;
1317     Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1318     if (!RD->lookupInBases(BaseHasFields, Paths)) {
1319       // If no classes have fields, just decompose RD itself. (This will work
1320       // if and only if zero bindings were provided.)
1321       return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1322     }
1323 
1324     CXXBasePath *BestPath = nullptr;
1325     for (auto &P : Paths) {
1326       if (!BestPath)
1327         BestPath = &P;
1328       else if (!S.Context.hasSameType(P.back().Base->getType(),
1329                                       BestPath->back().Base->getType())) {
1330         //   ... the same ...
1331         S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1332           << false << RD << BestPath->back().Base->getType()
1333           << P.back().Base->getType();
1334         return DeclAccessPair();
1335       } else if (P.Access < BestPath->Access) {
1336         BestPath = &P;
1337       }
1338     }
1339 
1340     //   ... unambiguous ...
1341     QualType BaseType = BestPath->back().Base->getType();
1342     if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1343       S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1344         << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1345       return DeclAccessPair();
1346     }
1347 
1348     //   ... [accessible, implied by other rules] base class of E.
1349     S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1350                            *BestPath, diag::err_decomp_decl_inaccessible_base);
1351     AS = BestPath->Access;
1352 
1353     ClassWithFields = BaseType->getAsCXXRecordDecl();
1354     S.BuildBasePathArray(Paths, BasePath);
1355   }
1356 
1357   // The above search did not check whether the selected class itself has base
1358   // classes with fields, so check that now.
1359   CXXBasePaths Paths;
1360   if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1361     S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1362       << (ClassWithFields == RD) << RD << ClassWithFields
1363       << Paths.front().back().Base->getType();
1364     return DeclAccessPair();
1365   }
1366 
1367   return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1368 }
1369 
1370 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1371                                      ValueDecl *Src, QualType DecompType,
1372                                      const CXXRecordDecl *OrigRD) {
1373   if (S.RequireCompleteType(Src->getLocation(), DecompType,
1374                             diag::err_incomplete_type))
1375     return true;
1376 
1377   CXXCastPath BasePath;
1378   DeclAccessPair BasePair =
1379       findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1380   const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1381   if (!RD)
1382     return true;
1383   QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1384                                                  DecompType.getQualifiers());
1385 
1386   auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1387     unsigned NumFields = llvm::count_if(
1388         RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1389     assert(Bindings.size() != NumFields);
1390     S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1391         << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1392         << (NumFields < Bindings.size());
1393     return true;
1394   };
1395 
1396   //   all of E's non-static data members shall be [...] well-formed
1397   //   when named as e.name in the context of the structured binding,
1398   //   E shall not have an anonymous union member, ...
1399   unsigned I = 0;
1400   for (auto *FD : RD->fields()) {
1401     if (FD->isUnnamedBitfield())
1402       continue;
1403 
1404     // All the non-static data members are required to be nameable, so they
1405     // must all have names.
1406     if (!FD->getDeclName()) {
1407       if (RD->isLambda()) {
1408         S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1409         S.Diag(RD->getLocation(), diag::note_lambda_decl);
1410         return true;
1411       }
1412 
1413       if (FD->isAnonymousStructOrUnion()) {
1414         S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1415           << DecompType << FD->getType()->isUnionType();
1416         S.Diag(FD->getLocation(), diag::note_declared_at);
1417         return true;
1418       }
1419 
1420       // FIXME: Are there any other ways we could have an anonymous member?
1421     }
1422 
1423     // We have a real field to bind.
1424     if (I >= Bindings.size())
1425       return DiagnoseBadNumberOfBindings();
1426     auto *B = Bindings[I++];
1427     SourceLocation Loc = B->getLocation();
1428 
1429     // The field must be accessible in the context of the structured binding.
1430     // We already checked that the base class is accessible.
1431     // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1432     // const_cast here.
1433     S.CheckStructuredBindingMemberAccess(
1434         Loc, const_cast<CXXRecordDecl *>(OrigRD),
1435         DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1436                                      BasePair.getAccess(), FD->getAccess())));
1437 
1438     // Initialize the binding to Src.FD.
1439     ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1440     if (E.isInvalid())
1441       return true;
1442     E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1443                             VK_LValue, &BasePath);
1444     if (E.isInvalid())
1445       return true;
1446     E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1447                                   CXXScopeSpec(), FD,
1448                                   DeclAccessPair::make(FD, FD->getAccess()),
1449                                   DeclarationNameInfo(FD->getDeclName(), Loc));
1450     if (E.isInvalid())
1451       return true;
1452 
1453     // If the type of the member is T, the referenced type is cv T, where cv is
1454     // the cv-qualification of the decomposition expression.
1455     //
1456     // FIXME: We resolve a defect here: if the field is mutable, we do not add
1457     // 'const' to the type of the field.
1458     Qualifiers Q = DecompType.getQualifiers();
1459     if (FD->isMutable())
1460       Q.removeConst();
1461     B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1462   }
1463 
1464   if (I != Bindings.size())
1465     return DiagnoseBadNumberOfBindings();
1466 
1467   return false;
1468 }
1469 
1470 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1471   QualType DecompType = DD->getType();
1472 
1473   // If the type of the decomposition is dependent, then so is the type of
1474   // each binding.
1475   if (DecompType->isDependentType()) {
1476     for (auto *B : DD->bindings())
1477       B->setType(Context.DependentTy);
1478     return;
1479   }
1480 
1481   DecompType = DecompType.getNonReferenceType();
1482   ArrayRef<BindingDecl*> Bindings = DD->bindings();
1483 
1484   // C++1z [dcl.decomp]/2:
1485   //   If E is an array type [...]
1486   // As an extension, we also support decomposition of built-in complex and
1487   // vector types.
1488   if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1489     if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1490       DD->setInvalidDecl();
1491     return;
1492   }
1493   if (auto *VT = DecompType->getAs<VectorType>()) {
1494     if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1495       DD->setInvalidDecl();
1496     return;
1497   }
1498   if (auto *CT = DecompType->getAs<ComplexType>()) {
1499     if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1500       DD->setInvalidDecl();
1501     return;
1502   }
1503 
1504   // C++1z [dcl.decomp]/3:
1505   //   if the expression std::tuple_size<E>::value is a well-formed integral
1506   //   constant expression, [...]
1507   llvm::APSInt TupleSize(32);
1508   switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1509   case IsTupleLike::Error:
1510     DD->setInvalidDecl();
1511     return;
1512 
1513   case IsTupleLike::TupleLike:
1514     if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1515       DD->setInvalidDecl();
1516     return;
1517 
1518   case IsTupleLike::NotTupleLike:
1519     break;
1520   }
1521 
1522   // C++1z [dcl.dcl]/8:
1523   //   [E shall be of array or non-union class type]
1524   CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1525   if (!RD || RD->isUnion()) {
1526     Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1527         << DD << !RD << DecompType;
1528     DD->setInvalidDecl();
1529     return;
1530   }
1531 
1532   // C++1z [dcl.decomp]/4:
1533   //   all of E's non-static data members shall be [...] direct members of
1534   //   E or of the same unambiguous public base class of E, ...
1535   if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1536     DD->setInvalidDecl();
1537 }
1538 
1539 /// Merge the exception specifications of two variable declarations.
1540 ///
1541 /// This is called when there's a redeclaration of a VarDecl. The function
1542 /// checks if the redeclaration might have an exception specification and
1543 /// validates compatibility and merges the specs if necessary.
1544 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1545   // Shortcut if exceptions are disabled.
1546   if (!getLangOpts().CXXExceptions)
1547     return;
1548 
1549   assert(Context.hasSameType(New->getType(), Old->getType()) &&
1550          "Should only be called if types are otherwise the same.");
1551 
1552   QualType NewType = New->getType();
1553   QualType OldType = Old->getType();
1554 
1555   // We're only interested in pointers and references to functions, as well
1556   // as pointers to member functions.
1557   if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1558     NewType = R->getPointeeType();
1559     OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1560   } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1561     NewType = P->getPointeeType();
1562     OldType = OldType->castAs<PointerType>()->getPointeeType();
1563   } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1564     NewType = M->getPointeeType();
1565     OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1566   }
1567 
1568   if (!NewType->isFunctionProtoType())
1569     return;
1570 
1571   // There's lots of special cases for functions. For function pointers, system
1572   // libraries are hopefully not as broken so that we don't need these
1573   // workarounds.
1574   if (CheckEquivalentExceptionSpec(
1575         OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1576         NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1577     New->setInvalidDecl();
1578   }
1579 }
1580 
1581 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1582 /// function declaration are well-formed according to C++
1583 /// [dcl.fct.default].
1584 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1585   unsigned NumParams = FD->getNumParams();
1586   unsigned ParamIdx = 0;
1587 
1588   // This checking doesn't make sense for explicit specializations; their
1589   // default arguments are determined by the declaration we're specializing,
1590   // not by FD.
1591   if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1592     return;
1593   if (auto *FTD = FD->getDescribedFunctionTemplate())
1594     if (FTD->isMemberSpecialization())
1595       return;
1596 
1597   // Find first parameter with a default argument
1598   for (; ParamIdx < NumParams; ++ParamIdx) {
1599     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1600     if (Param->hasDefaultArg())
1601       break;
1602   }
1603 
1604   // C++20 [dcl.fct.default]p4:
1605   //   In a given function declaration, each parameter subsequent to a parameter
1606   //   with a default argument shall have a default argument supplied in this or
1607   //   a previous declaration, unless the parameter was expanded from a
1608   //   parameter pack, or shall be a function parameter pack.
1609   for (; ParamIdx < NumParams; ++ParamIdx) {
1610     ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1611     if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1612         !(CurrentInstantiationScope &&
1613           CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1614       if (Param->isInvalidDecl())
1615         /* We already complained about this parameter. */;
1616       else if (Param->getIdentifier())
1617         Diag(Param->getLocation(),
1618              diag::err_param_default_argument_missing_name)
1619           << Param->getIdentifier();
1620       else
1621         Diag(Param->getLocation(),
1622              diag::err_param_default_argument_missing);
1623     }
1624   }
1625 }
1626 
1627 /// Check that the given type is a literal type. Issue a diagnostic if not,
1628 /// if Kind is Diagnose.
1629 /// \return \c true if a problem has been found (and optionally diagnosed).
1630 template <typename... Ts>
1631 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1632                              SourceLocation Loc, QualType T, unsigned DiagID,
1633                              Ts &&...DiagArgs) {
1634   if (T->isDependentType())
1635     return false;
1636 
1637   switch (Kind) {
1638   case Sema::CheckConstexprKind::Diagnose:
1639     return SemaRef.RequireLiteralType(Loc, T, DiagID,
1640                                       std::forward<Ts>(DiagArgs)...);
1641 
1642   case Sema::CheckConstexprKind::CheckValid:
1643     return !T->isLiteralType(SemaRef.Context);
1644   }
1645 
1646   llvm_unreachable("unknown CheckConstexprKind");
1647 }
1648 
1649 /// Determine whether a destructor cannot be constexpr due to
1650 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1651                                                const CXXDestructorDecl *DD,
1652                                                Sema::CheckConstexprKind Kind) {
1653   auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1654     const CXXRecordDecl *RD =
1655         T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1656     if (!RD || RD->hasConstexprDestructor())
1657       return true;
1658 
1659     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1660       SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1661           << static_cast<int>(DD->getConstexprKind()) << !FD
1662           << (FD ? FD->getDeclName() : DeclarationName()) << T;
1663       SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1664           << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1665     }
1666     return false;
1667   };
1668 
1669   const CXXRecordDecl *RD = DD->getParent();
1670   for (const CXXBaseSpecifier &B : RD->bases())
1671     if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1672       return false;
1673   for (const FieldDecl *FD : RD->fields())
1674     if (!Check(FD->getLocation(), FD->getType(), FD))
1675       return false;
1676   return true;
1677 }
1678 
1679 /// Check whether a function's parameter types are all literal types. If so,
1680 /// return true. If not, produce a suitable diagnostic and return false.
1681 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1682                                          const FunctionDecl *FD,
1683                                          Sema::CheckConstexprKind Kind) {
1684   unsigned ArgIndex = 0;
1685   const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1686   for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1687                                               e = FT->param_type_end();
1688        i != e; ++i, ++ArgIndex) {
1689     const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1690     SourceLocation ParamLoc = PD->getLocation();
1691     if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1692                          diag::err_constexpr_non_literal_param, ArgIndex + 1,
1693                          PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1694                          FD->isConsteval()))
1695       return false;
1696   }
1697   return true;
1698 }
1699 
1700 /// Check whether a function's return type is a literal type. If so, return
1701 /// true. If not, produce a suitable diagnostic and return false.
1702 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1703                                      Sema::CheckConstexprKind Kind) {
1704   if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1705                        diag::err_constexpr_non_literal_return,
1706                        FD->isConsteval()))
1707     return false;
1708   return true;
1709 }
1710 
1711 /// Get diagnostic %select index for tag kind for
1712 /// record diagnostic message.
1713 /// WARNING: Indexes apply to particular diagnostics only!
1714 ///
1715 /// \returns diagnostic %select index.
1716 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1717   switch (Tag) {
1718   case TTK_Struct: return 0;
1719   case TTK_Interface: return 1;
1720   case TTK_Class:  return 2;
1721   default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1722   }
1723 }
1724 
1725 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1726                                        Stmt *Body,
1727                                        Sema::CheckConstexprKind Kind);
1728 
1729 // Check whether a function declaration satisfies the requirements of a
1730 // constexpr function definition or a constexpr constructor definition. If so,
1731 // return true. If not, produce appropriate diagnostics (unless asked not to by
1732 // Kind) and return false.
1733 //
1734 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1735 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1736                                             CheckConstexprKind Kind) {
1737   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1738   if (MD && MD->isInstance()) {
1739     // C++11 [dcl.constexpr]p4:
1740     //  The definition of a constexpr constructor shall satisfy the following
1741     //  constraints:
1742     //  - the class shall not have any virtual base classes;
1743     //
1744     // FIXME: This only applies to constructors and destructors, not arbitrary
1745     // member functions.
1746     const CXXRecordDecl *RD = MD->getParent();
1747     if (RD->getNumVBases()) {
1748       if (Kind == CheckConstexprKind::CheckValid)
1749         return false;
1750 
1751       Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1752         << isa<CXXConstructorDecl>(NewFD)
1753         << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1754       for (const auto &I : RD->vbases())
1755         Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1756             << I.getSourceRange();
1757       return false;
1758     }
1759   }
1760 
1761   if (!isa<CXXConstructorDecl>(NewFD)) {
1762     // C++11 [dcl.constexpr]p3:
1763     //  The definition of a constexpr function shall satisfy the following
1764     //  constraints:
1765     // - it shall not be virtual; (removed in C++20)
1766     const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1767     if (Method && Method->isVirtual()) {
1768       if (getLangOpts().CPlusPlus20) {
1769         if (Kind == CheckConstexprKind::Diagnose)
1770           Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1771       } else {
1772         if (Kind == CheckConstexprKind::CheckValid)
1773           return false;
1774 
1775         Method = Method->getCanonicalDecl();
1776         Diag(Method->getLocation(), diag::err_constexpr_virtual);
1777 
1778         // If it's not obvious why this function is virtual, find an overridden
1779         // function which uses the 'virtual' keyword.
1780         const CXXMethodDecl *WrittenVirtual = Method;
1781         while (!WrittenVirtual->isVirtualAsWritten())
1782           WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1783         if (WrittenVirtual != Method)
1784           Diag(WrittenVirtual->getLocation(),
1785                diag::note_overridden_virtual_function);
1786         return false;
1787       }
1788     }
1789 
1790     // - its return type shall be a literal type;
1791     if (!CheckConstexprReturnType(*this, NewFD, Kind))
1792       return false;
1793   }
1794 
1795   if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1796     // A destructor can be constexpr only if the defaulted destructor could be;
1797     // we don't need to check the members and bases if we already know they all
1798     // have constexpr destructors.
1799     if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1800       if (Kind == CheckConstexprKind::CheckValid)
1801         return false;
1802       if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1803         return false;
1804     }
1805   }
1806 
1807   // - each of its parameter types shall be a literal type;
1808   if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1809     return false;
1810 
1811   Stmt *Body = NewFD->getBody();
1812   assert(Body &&
1813          "CheckConstexprFunctionDefinition called on function with no body");
1814   return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1815 }
1816 
1817 /// Check the given declaration statement is legal within a constexpr function
1818 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1819 ///
1820 /// \return true if the body is OK (maybe only as an extension), false if we
1821 ///         have diagnosed a problem.
1822 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1823                                    DeclStmt *DS, SourceLocation &Cxx1yLoc,
1824                                    Sema::CheckConstexprKind Kind) {
1825   // C++11 [dcl.constexpr]p3 and p4:
1826   //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
1827   //  contain only
1828   for (const auto *DclIt : DS->decls()) {
1829     switch (DclIt->getKind()) {
1830     case Decl::StaticAssert:
1831     case Decl::Using:
1832     case Decl::UsingShadow:
1833     case Decl::UsingDirective:
1834     case Decl::UnresolvedUsingTypename:
1835     case Decl::UnresolvedUsingValue:
1836     case Decl::UsingEnum:
1837       //   - static_assert-declarations
1838       //   - using-declarations,
1839       //   - using-directives,
1840       //   - using-enum-declaration
1841       continue;
1842 
1843     case Decl::Typedef:
1844     case Decl::TypeAlias: {
1845       //   - typedef declarations and alias-declarations that do not define
1846       //     classes or enumerations,
1847       const auto *TN = cast<TypedefNameDecl>(DclIt);
1848       if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1849         // Don't allow variably-modified types in constexpr functions.
1850         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1851           TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1852           SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1853             << TL.getSourceRange() << TL.getType()
1854             << isa<CXXConstructorDecl>(Dcl);
1855         }
1856         return false;
1857       }
1858       continue;
1859     }
1860 
1861     case Decl::Enum:
1862     case Decl::CXXRecord:
1863       // C++1y allows types to be defined, not just declared.
1864       if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1865         if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866           SemaRef.Diag(DS->getBeginLoc(),
1867                        SemaRef.getLangOpts().CPlusPlus14
1868                            ? diag::warn_cxx11_compat_constexpr_type_definition
1869                            : diag::ext_constexpr_type_definition)
1870               << isa<CXXConstructorDecl>(Dcl);
1871         } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1872           return false;
1873         }
1874       }
1875       continue;
1876 
1877     case Decl::EnumConstant:
1878     case Decl::IndirectField:
1879     case Decl::ParmVar:
1880       // These can only appear with other declarations which are banned in
1881       // C++11 and permitted in C++1y, so ignore them.
1882       continue;
1883 
1884     case Decl::Var:
1885     case Decl::Decomposition: {
1886       // C++1y [dcl.constexpr]p3 allows anything except:
1887       //   a definition of a variable of non-literal type or of static or
1888       //   thread storage duration or [before C++2a] for which no
1889       //   initialization is performed.
1890       const auto *VD = cast<VarDecl>(DclIt);
1891       if (VD->isThisDeclarationADefinition()) {
1892         if (VD->isStaticLocal()) {
1893           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1894             SemaRef.Diag(VD->getLocation(),
1895                          diag::err_constexpr_local_var_static)
1896               << isa<CXXConstructorDecl>(Dcl)
1897               << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1898           }
1899           return false;
1900         }
1901         if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1902                              diag::err_constexpr_local_var_non_literal_type,
1903                              isa<CXXConstructorDecl>(Dcl)))
1904           return false;
1905         if (!VD->getType()->isDependentType() &&
1906             !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1907           if (Kind == Sema::CheckConstexprKind::Diagnose) {
1908             SemaRef.Diag(
1909                 VD->getLocation(),
1910                 SemaRef.getLangOpts().CPlusPlus20
1911                     ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1912                     : diag::ext_constexpr_local_var_no_init)
1913                 << isa<CXXConstructorDecl>(Dcl);
1914           } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1915             return false;
1916           }
1917           continue;
1918         }
1919       }
1920       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1921         SemaRef.Diag(VD->getLocation(),
1922                      SemaRef.getLangOpts().CPlusPlus14
1923                       ? diag::warn_cxx11_compat_constexpr_local_var
1924                       : diag::ext_constexpr_local_var)
1925           << isa<CXXConstructorDecl>(Dcl);
1926       } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1927         return false;
1928       }
1929       continue;
1930     }
1931 
1932     case Decl::NamespaceAlias:
1933     case Decl::Function:
1934       // These are disallowed in C++11 and permitted in C++1y. Allow them
1935       // everywhere as an extension.
1936       if (!Cxx1yLoc.isValid())
1937         Cxx1yLoc = DS->getBeginLoc();
1938       continue;
1939 
1940     default:
1941       if (Kind == Sema::CheckConstexprKind::Diagnose) {
1942         SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1943             << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1944       }
1945       return false;
1946     }
1947   }
1948 
1949   return true;
1950 }
1951 
1952 /// Check that the given field is initialized within a constexpr constructor.
1953 ///
1954 /// \param Dcl The constexpr constructor being checked.
1955 /// \param Field The field being checked. This may be a member of an anonymous
1956 ///        struct or union nested within the class being checked.
1957 /// \param Inits All declarations, including anonymous struct/union members and
1958 ///        indirect members, for which any initialization was provided.
1959 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1960 ///        multiple notes for different members to the same error.
1961 /// \param Kind Whether we're diagnosing a constructor as written or determining
1962 ///        whether the formal requirements are satisfied.
1963 /// \return \c false if we're checking for validity and the constructor does
1964 ///         not satisfy the requirements on a constexpr constructor.
1965 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1966                                           const FunctionDecl *Dcl,
1967                                           FieldDecl *Field,
1968                                           llvm::SmallSet<Decl*, 16> &Inits,
1969                                           bool &Diagnosed,
1970                                           Sema::CheckConstexprKind Kind) {
1971   // In C++20 onwards, there's nothing to check for validity.
1972   if (Kind == Sema::CheckConstexprKind::CheckValid &&
1973       SemaRef.getLangOpts().CPlusPlus20)
1974     return true;
1975 
1976   if (Field->isInvalidDecl())
1977     return true;
1978 
1979   if (Field->isUnnamedBitfield())
1980     return true;
1981 
1982   // Anonymous unions with no variant members and empty anonymous structs do not
1983   // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1984   // indirect fields don't need initializing.
1985   if (Field->isAnonymousStructOrUnion() &&
1986       (Field->getType()->isUnionType()
1987            ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1988            : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1989     return true;
1990 
1991   if (!Inits.count(Field)) {
1992     if (Kind == Sema::CheckConstexprKind::Diagnose) {
1993       if (!Diagnosed) {
1994         SemaRef.Diag(Dcl->getLocation(),
1995                      SemaRef.getLangOpts().CPlusPlus20
1996                          ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1997                          : diag::ext_constexpr_ctor_missing_init);
1998         Diagnosed = true;
1999       }
2000       SemaRef.Diag(Field->getLocation(),
2001                    diag::note_constexpr_ctor_missing_init);
2002     } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2003       return false;
2004     }
2005   } else if (Field->isAnonymousStructOrUnion()) {
2006     const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2007     for (auto *I : RD->fields())
2008       // If an anonymous union contains an anonymous struct of which any member
2009       // is initialized, all members must be initialized.
2010       if (!RD->isUnion() || Inits.count(I))
2011         if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2012                                            Kind))
2013           return false;
2014   }
2015   return true;
2016 }
2017 
2018 /// Check the provided statement is allowed in a constexpr function
2019 /// definition.
2020 static bool
2021 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2022                            SmallVectorImpl<SourceLocation> &ReturnStmts,
2023                            SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2024                            Sema::CheckConstexprKind Kind) {
2025   // - its function-body shall be [...] a compound-statement that contains only
2026   switch (S->getStmtClass()) {
2027   case Stmt::NullStmtClass:
2028     //   - null statements,
2029     return true;
2030 
2031   case Stmt::DeclStmtClass:
2032     //   - static_assert-declarations
2033     //   - using-declarations,
2034     //   - using-directives,
2035     //   - typedef declarations and alias-declarations that do not define
2036     //     classes or enumerations,
2037     if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2038       return false;
2039     return true;
2040 
2041   case Stmt::ReturnStmtClass:
2042     //   - and exactly one return statement;
2043     if (isa<CXXConstructorDecl>(Dcl)) {
2044       // C++1y allows return statements in constexpr constructors.
2045       if (!Cxx1yLoc.isValid())
2046         Cxx1yLoc = S->getBeginLoc();
2047       return true;
2048     }
2049 
2050     ReturnStmts.push_back(S->getBeginLoc());
2051     return true;
2052 
2053   case Stmt::AttributedStmtClass:
2054     // Attributes on a statement don't affect its formal kind and hence don't
2055     // affect its validity in a constexpr function.
2056     return CheckConstexprFunctionStmt(SemaRef, Dcl,
2057                                       cast<AttributedStmt>(S)->getSubStmt(),
2058                                       ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind);
2059 
2060   case Stmt::CompoundStmtClass: {
2061     // C++1y allows compound-statements.
2062     if (!Cxx1yLoc.isValid())
2063       Cxx1yLoc = S->getBeginLoc();
2064 
2065     CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2066     for (auto *BodyIt : CompStmt->body()) {
2067       if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2068                                       Cxx1yLoc, Cxx2aLoc, Kind))
2069         return false;
2070     }
2071     return true;
2072   }
2073 
2074   case Stmt::IfStmtClass: {
2075     // C++1y allows if-statements.
2076     if (!Cxx1yLoc.isValid())
2077       Cxx1yLoc = S->getBeginLoc();
2078 
2079     IfStmt *If = cast<IfStmt>(S);
2080     if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2081                                     Cxx1yLoc, Cxx2aLoc, Kind))
2082       return false;
2083     if (If->getElse() &&
2084         !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2085                                     Cxx1yLoc, Cxx2aLoc, Kind))
2086       return false;
2087     return true;
2088   }
2089 
2090   case Stmt::WhileStmtClass:
2091   case Stmt::DoStmtClass:
2092   case Stmt::ForStmtClass:
2093   case Stmt::CXXForRangeStmtClass:
2094   case Stmt::ContinueStmtClass:
2095     // C++1y allows all of these. We don't allow them as extensions in C++11,
2096     // because they don't make sense without variable mutation.
2097     if (!SemaRef.getLangOpts().CPlusPlus14)
2098       break;
2099     if (!Cxx1yLoc.isValid())
2100       Cxx1yLoc = S->getBeginLoc();
2101     for (Stmt *SubStmt : S->children())
2102       if (SubStmt &&
2103           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2104                                       Cxx1yLoc, Cxx2aLoc, Kind))
2105         return false;
2106     return true;
2107 
2108   case Stmt::SwitchStmtClass:
2109   case Stmt::CaseStmtClass:
2110   case Stmt::DefaultStmtClass:
2111   case Stmt::BreakStmtClass:
2112     // C++1y allows switch-statements, and since they don't need variable
2113     // mutation, we can reasonably allow them in C++11 as an extension.
2114     if (!Cxx1yLoc.isValid())
2115       Cxx1yLoc = S->getBeginLoc();
2116     for (Stmt *SubStmt : S->children())
2117       if (SubStmt &&
2118           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2119                                       Cxx1yLoc, Cxx2aLoc, Kind))
2120         return false;
2121     return true;
2122 
2123   case Stmt::GCCAsmStmtClass:
2124   case Stmt::MSAsmStmtClass:
2125     // C++2a allows inline assembly statements.
2126   case Stmt::CXXTryStmtClass:
2127     if (Cxx2aLoc.isInvalid())
2128       Cxx2aLoc = S->getBeginLoc();
2129     for (Stmt *SubStmt : S->children()) {
2130       if (SubStmt &&
2131           !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2132                                       Cxx1yLoc, Cxx2aLoc, Kind))
2133         return false;
2134     }
2135     return true;
2136 
2137   case Stmt::CXXCatchStmtClass:
2138     // Do not bother checking the language mode (already covered by the
2139     // try block check).
2140     if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2141                                     cast<CXXCatchStmt>(S)->getHandlerBlock(),
2142                                     ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2143       return false;
2144     return true;
2145 
2146   default:
2147     if (!isa<Expr>(S))
2148       break;
2149 
2150     // C++1y allows expression-statements.
2151     if (!Cxx1yLoc.isValid())
2152       Cxx1yLoc = S->getBeginLoc();
2153     return true;
2154   }
2155 
2156   if (Kind == Sema::CheckConstexprKind::Diagnose) {
2157     SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2158         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2159   }
2160   return false;
2161 }
2162 
2163 /// Check the body for the given constexpr function declaration only contains
2164 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2165 ///
2166 /// \return true if the body is OK, false if we have found or diagnosed a
2167 /// problem.
2168 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2169                                        Stmt *Body,
2170                                        Sema::CheckConstexprKind Kind) {
2171   SmallVector<SourceLocation, 4> ReturnStmts;
2172 
2173   if (isa<CXXTryStmt>(Body)) {
2174     // C++11 [dcl.constexpr]p3:
2175     //  The definition of a constexpr function shall satisfy the following
2176     //  constraints: [...]
2177     // - its function-body shall be = delete, = default, or a
2178     //   compound-statement
2179     //
2180     // C++11 [dcl.constexpr]p4:
2181     //  In the definition of a constexpr constructor, [...]
2182     // - its function-body shall not be a function-try-block;
2183     //
2184     // This restriction is lifted in C++2a, as long as inner statements also
2185     // apply the general constexpr rules.
2186     switch (Kind) {
2187     case Sema::CheckConstexprKind::CheckValid:
2188       if (!SemaRef.getLangOpts().CPlusPlus20)
2189         return false;
2190       break;
2191 
2192     case Sema::CheckConstexprKind::Diagnose:
2193       SemaRef.Diag(Body->getBeginLoc(),
2194            !SemaRef.getLangOpts().CPlusPlus20
2195                ? diag::ext_constexpr_function_try_block_cxx20
2196                : diag::warn_cxx17_compat_constexpr_function_try_block)
2197           << isa<CXXConstructorDecl>(Dcl);
2198       break;
2199     }
2200   }
2201 
2202   // - its function-body shall be [...] a compound-statement that contains only
2203   //   [... list of cases ...]
2204   //
2205   // Note that walking the children here is enough to properly check for
2206   // CompoundStmt and CXXTryStmt body.
2207   SourceLocation Cxx1yLoc, Cxx2aLoc;
2208   for (Stmt *SubStmt : Body->children()) {
2209     if (SubStmt &&
2210         !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2211                                     Cxx1yLoc, Cxx2aLoc, Kind))
2212       return false;
2213   }
2214 
2215   if (Kind == Sema::CheckConstexprKind::CheckValid) {
2216     // If this is only valid as an extension, report that we don't satisfy the
2217     // constraints of the current language.
2218     if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2219         (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2220       return false;
2221   } else if (Cxx2aLoc.isValid()) {
2222     SemaRef.Diag(Cxx2aLoc,
2223          SemaRef.getLangOpts().CPlusPlus20
2224            ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2225            : diag::ext_constexpr_body_invalid_stmt_cxx20)
2226       << isa<CXXConstructorDecl>(Dcl);
2227   } else if (Cxx1yLoc.isValid()) {
2228     SemaRef.Diag(Cxx1yLoc,
2229          SemaRef.getLangOpts().CPlusPlus14
2230            ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2231            : diag::ext_constexpr_body_invalid_stmt)
2232       << isa<CXXConstructorDecl>(Dcl);
2233   }
2234 
2235   if (const CXXConstructorDecl *Constructor
2236         = dyn_cast<CXXConstructorDecl>(Dcl)) {
2237     const CXXRecordDecl *RD = Constructor->getParent();
2238     // DR1359:
2239     // - every non-variant non-static data member and base class sub-object
2240     //   shall be initialized;
2241     // DR1460:
2242     // - if the class is a union having variant members, exactly one of them
2243     //   shall be initialized;
2244     if (RD->isUnion()) {
2245       if (Constructor->getNumCtorInitializers() == 0 &&
2246           RD->hasVariantMembers()) {
2247         if (Kind == Sema::CheckConstexprKind::Diagnose) {
2248           SemaRef.Diag(
2249               Dcl->getLocation(),
2250               SemaRef.getLangOpts().CPlusPlus20
2251                   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2252                   : diag::ext_constexpr_union_ctor_no_init);
2253         } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2254           return false;
2255         }
2256       }
2257     } else if (!Constructor->isDependentContext() &&
2258                !Constructor->isDelegatingConstructor()) {
2259       assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2260 
2261       // Skip detailed checking if we have enough initializers, and we would
2262       // allow at most one initializer per member.
2263       bool AnyAnonStructUnionMembers = false;
2264       unsigned Fields = 0;
2265       for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2266            E = RD->field_end(); I != E; ++I, ++Fields) {
2267         if (I->isAnonymousStructOrUnion()) {
2268           AnyAnonStructUnionMembers = true;
2269           break;
2270         }
2271       }
2272       // DR1460:
2273       // - if the class is a union-like class, but is not a union, for each of
2274       //   its anonymous union members having variant members, exactly one of
2275       //   them shall be initialized;
2276       if (AnyAnonStructUnionMembers ||
2277           Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2278         // Check initialization of non-static data members. Base classes are
2279         // always initialized so do not need to be checked. Dependent bases
2280         // might not have initializers in the member initializer list.
2281         llvm::SmallSet<Decl*, 16> Inits;
2282         for (const auto *I: Constructor->inits()) {
2283           if (FieldDecl *FD = I->getMember())
2284             Inits.insert(FD);
2285           else if (IndirectFieldDecl *ID = I->getIndirectMember())
2286             Inits.insert(ID->chain_begin(), ID->chain_end());
2287         }
2288 
2289         bool Diagnosed = false;
2290         for (auto *I : RD->fields())
2291           if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2292                                              Kind))
2293             return false;
2294       }
2295     }
2296   } else {
2297     if (ReturnStmts.empty()) {
2298       // C++1y doesn't require constexpr functions to contain a 'return'
2299       // statement. We still do, unless the return type might be void, because
2300       // otherwise if there's no return statement, the function cannot
2301       // be used in a core constant expression.
2302       bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2303                 (Dcl->getReturnType()->isVoidType() ||
2304                  Dcl->getReturnType()->isDependentType());
2305       switch (Kind) {
2306       case Sema::CheckConstexprKind::Diagnose:
2307         SemaRef.Diag(Dcl->getLocation(),
2308                      OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2309                         : diag::err_constexpr_body_no_return)
2310             << Dcl->isConsteval();
2311         if (!OK)
2312           return false;
2313         break;
2314 
2315       case Sema::CheckConstexprKind::CheckValid:
2316         // The formal requirements don't include this rule in C++14, even
2317         // though the "must be able to produce a constant expression" rules
2318         // still imply it in some cases.
2319         if (!SemaRef.getLangOpts().CPlusPlus14)
2320           return false;
2321         break;
2322       }
2323     } else if (ReturnStmts.size() > 1) {
2324       switch (Kind) {
2325       case Sema::CheckConstexprKind::Diagnose:
2326         SemaRef.Diag(
2327             ReturnStmts.back(),
2328             SemaRef.getLangOpts().CPlusPlus14
2329                 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2330                 : diag::ext_constexpr_body_multiple_return);
2331         for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2332           SemaRef.Diag(ReturnStmts[I],
2333                        diag::note_constexpr_body_previous_return);
2334         break;
2335 
2336       case Sema::CheckConstexprKind::CheckValid:
2337         if (!SemaRef.getLangOpts().CPlusPlus14)
2338           return false;
2339         break;
2340       }
2341     }
2342   }
2343 
2344   // C++11 [dcl.constexpr]p5:
2345   //   if no function argument values exist such that the function invocation
2346   //   substitution would produce a constant expression, the program is
2347   //   ill-formed; no diagnostic required.
2348   // C++11 [dcl.constexpr]p3:
2349   //   - every constructor call and implicit conversion used in initializing the
2350   //     return value shall be one of those allowed in a constant expression.
2351   // C++11 [dcl.constexpr]p4:
2352   //   - every constructor involved in initializing non-static data members and
2353   //     base class sub-objects shall be a constexpr constructor.
2354   //
2355   // Note that this rule is distinct from the "requirements for a constexpr
2356   // function", so is not checked in CheckValid mode.
2357   SmallVector<PartialDiagnosticAt, 8> Diags;
2358   if (Kind == Sema::CheckConstexprKind::Diagnose &&
2359       !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2360     SemaRef.Diag(Dcl->getLocation(),
2361                  diag::ext_constexpr_function_never_constant_expr)
2362         << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2363     for (size_t I = 0, N = Diags.size(); I != N; ++I)
2364       SemaRef.Diag(Diags[I].first, Diags[I].second);
2365     // Don't return false here: we allow this for compatibility in
2366     // system headers.
2367   }
2368 
2369   return true;
2370 }
2371 
2372 /// Get the class that is directly named by the current context. This is the
2373 /// class for which an unqualified-id in this scope could name a constructor
2374 /// or destructor.
2375 ///
2376 /// If the scope specifier denotes a class, this will be that class.
2377 /// If the scope specifier is empty, this will be the class whose
2378 /// member-specification we are currently within. Otherwise, there
2379 /// is no such class.
2380 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2381   assert(getLangOpts().CPlusPlus && "No class names in C!");
2382 
2383   if (SS && SS->isInvalid())
2384     return nullptr;
2385 
2386   if (SS && SS->isNotEmpty()) {
2387     DeclContext *DC = computeDeclContext(*SS, true);
2388     return dyn_cast_or_null<CXXRecordDecl>(DC);
2389   }
2390 
2391   return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2392 }
2393 
2394 /// isCurrentClassName - Determine whether the identifier II is the
2395 /// name of the class type currently being defined. In the case of
2396 /// nested classes, this will only return true if II is the name of
2397 /// the innermost class.
2398 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2399                               const CXXScopeSpec *SS) {
2400   CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2401   return CurDecl && &II == CurDecl->getIdentifier();
2402 }
2403 
2404 /// Determine whether the identifier II is a typo for the name of
2405 /// the class type currently being defined. If so, update it to the identifier
2406 /// that should have been used.
2407 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2408   assert(getLangOpts().CPlusPlus && "No class names in C!");
2409 
2410   if (!getLangOpts().SpellChecking)
2411     return false;
2412 
2413   CXXRecordDecl *CurDecl;
2414   if (SS && SS->isSet() && !SS->isInvalid()) {
2415     DeclContext *DC = computeDeclContext(*SS, true);
2416     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2417   } else
2418     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2419 
2420   if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2421       3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2422           < II->getLength()) {
2423     II = CurDecl->getIdentifier();
2424     return true;
2425   }
2426 
2427   return false;
2428 }
2429 
2430 /// Determine whether the given class is a base class of the given
2431 /// class, including looking at dependent bases.
2432 static bool findCircularInheritance(const CXXRecordDecl *Class,
2433                                     const CXXRecordDecl *Current) {
2434   SmallVector<const CXXRecordDecl*, 8> Queue;
2435 
2436   Class = Class->getCanonicalDecl();
2437   while (true) {
2438     for (const auto &I : Current->bases()) {
2439       CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2440       if (!Base)
2441         continue;
2442 
2443       Base = Base->getDefinition();
2444       if (!Base)
2445         continue;
2446 
2447       if (Base->getCanonicalDecl() == Class)
2448         return true;
2449 
2450       Queue.push_back(Base);
2451     }
2452 
2453     if (Queue.empty())
2454       return false;
2455 
2456     Current = Queue.pop_back_val();
2457   }
2458 
2459   return false;
2460 }
2461 
2462 /// Check the validity of a C++ base class specifier.
2463 ///
2464 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2465 /// and returns NULL otherwise.
2466 CXXBaseSpecifier *
2467 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2468                          SourceRange SpecifierRange,
2469                          bool Virtual, AccessSpecifier Access,
2470                          TypeSourceInfo *TInfo,
2471                          SourceLocation EllipsisLoc) {
2472   QualType BaseType = TInfo->getType();
2473   if (BaseType->containsErrors()) {
2474     // Already emitted a diagnostic when parsing the error type.
2475     return nullptr;
2476   }
2477   // C++ [class.union]p1:
2478   //   A union shall not have base classes.
2479   if (Class->isUnion()) {
2480     Diag(Class->getLocation(), diag::err_base_clause_on_union)
2481       << SpecifierRange;
2482     return nullptr;
2483   }
2484 
2485   if (EllipsisLoc.isValid() &&
2486       !TInfo->getType()->containsUnexpandedParameterPack()) {
2487     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2488       << TInfo->getTypeLoc().getSourceRange();
2489     EllipsisLoc = SourceLocation();
2490   }
2491 
2492   SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2493 
2494   if (BaseType->isDependentType()) {
2495     // Make sure that we don't have circular inheritance among our dependent
2496     // bases. For non-dependent bases, the check for completeness below handles
2497     // this.
2498     if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2499       if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2500           ((BaseDecl = BaseDecl->getDefinition()) &&
2501            findCircularInheritance(Class, BaseDecl))) {
2502         Diag(BaseLoc, diag::err_circular_inheritance)
2503           << BaseType << Context.getTypeDeclType(Class);
2504 
2505         if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2506           Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2507             << BaseType;
2508 
2509         return nullptr;
2510       }
2511     }
2512 
2513     // Make sure that we don't make an ill-formed AST where the type of the
2514     // Class is non-dependent and its attached base class specifier is an
2515     // dependent type, which violates invariants in many clang code paths (e.g.
2516     // constexpr evaluator). If this case happens (in errory-recovery mode), we
2517     // explicitly mark the Class decl invalid. The diagnostic was already
2518     // emitted.
2519     if (!Class->getTypeForDecl()->isDependentType())
2520       Class->setInvalidDecl();
2521     return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2522                                           Class->getTagKind() == TTK_Class,
2523                                           Access, TInfo, EllipsisLoc);
2524   }
2525 
2526   // Base specifiers must be record types.
2527   if (!BaseType->isRecordType()) {
2528     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2529     return nullptr;
2530   }
2531 
2532   // C++ [class.union]p1:
2533   //   A union shall not be used as a base class.
2534   if (BaseType->isUnionType()) {
2535     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2536     return nullptr;
2537   }
2538 
2539   // For the MS ABI, propagate DLL attributes to base class templates.
2540   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2541     if (Attr *ClassAttr = getDLLAttr(Class)) {
2542       if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2543               BaseType->getAsCXXRecordDecl())) {
2544         propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2545                                             BaseLoc);
2546       }
2547     }
2548   }
2549 
2550   // C++ [class.derived]p2:
2551   //   The class-name in a base-specifier shall not be an incompletely
2552   //   defined class.
2553   if (RequireCompleteType(BaseLoc, BaseType,
2554                           diag::err_incomplete_base_class, SpecifierRange)) {
2555     Class->setInvalidDecl();
2556     return nullptr;
2557   }
2558 
2559   // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2560   RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2561   assert(BaseDecl && "Record type has no declaration");
2562   BaseDecl = BaseDecl->getDefinition();
2563   assert(BaseDecl && "Base type is not incomplete, but has no definition");
2564   CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2565   assert(CXXBaseDecl && "Base type is not a C++ type");
2566 
2567   // Microsoft docs say:
2568   // "If a base-class has a code_seg attribute, derived classes must have the
2569   // same attribute."
2570   const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2571   const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2572   if ((DerivedCSA || BaseCSA) &&
2573       (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2574     Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2575     Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2576       << CXXBaseDecl;
2577     return nullptr;
2578   }
2579 
2580   // A class which contains a flexible array member is not suitable for use as a
2581   // base class:
2582   //   - If the layout determines that a base comes before another base,
2583   //     the flexible array member would index into the subsequent base.
2584   //   - If the layout determines that base comes before the derived class,
2585   //     the flexible array member would index into the derived class.
2586   if (CXXBaseDecl->hasFlexibleArrayMember()) {
2587     Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2588       << CXXBaseDecl->getDeclName();
2589     return nullptr;
2590   }
2591 
2592   // C++ [class]p3:
2593   //   If a class is marked final and it appears as a base-type-specifier in
2594   //   base-clause, the program is ill-formed.
2595   if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2596     Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2597       << CXXBaseDecl->getDeclName()
2598       << FA->isSpelledAsSealed();
2599     Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2600         << CXXBaseDecl->getDeclName() << FA->getRange();
2601     return nullptr;
2602   }
2603 
2604   if (BaseDecl->isInvalidDecl())
2605     Class->setInvalidDecl();
2606 
2607   // Create the base specifier.
2608   return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2609                                         Class->getTagKind() == TTK_Class,
2610                                         Access, TInfo, EllipsisLoc);
2611 }
2612 
2613 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2614 /// one entry in the base class list of a class specifier, for
2615 /// example:
2616 ///    class foo : public bar, virtual private baz {
2617 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2618 BaseResult
2619 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2620                          ParsedAttributes &Attributes,
2621                          bool Virtual, AccessSpecifier Access,
2622                          ParsedType basetype, SourceLocation BaseLoc,
2623                          SourceLocation EllipsisLoc) {
2624   if (!classdecl)
2625     return true;
2626 
2627   AdjustDeclIfTemplate(classdecl);
2628   CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2629   if (!Class)
2630     return true;
2631 
2632   // We haven't yet attached the base specifiers.
2633   Class->setIsParsingBaseSpecifiers();
2634 
2635   // We do not support any C++11 attributes on base-specifiers yet.
2636   // Diagnose any attributes we see.
2637   for (const ParsedAttr &AL : Attributes) {
2638     if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2639       continue;
2640     Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2641                           ? (unsigned)diag::warn_unknown_attribute_ignored
2642                           : (unsigned)diag::err_base_specifier_attribute)
2643         << AL << AL.getRange();
2644   }
2645 
2646   TypeSourceInfo *TInfo = nullptr;
2647   GetTypeFromParser(basetype, &TInfo);
2648 
2649   if (EllipsisLoc.isInvalid() &&
2650       DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2651                                       UPPC_BaseType))
2652     return true;
2653 
2654   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2655                                                       Virtual, Access, TInfo,
2656                                                       EllipsisLoc))
2657     return BaseSpec;
2658   else
2659     Class->setInvalidDecl();
2660 
2661   return true;
2662 }
2663 
2664 /// Use small set to collect indirect bases.  As this is only used
2665 /// locally, there's no need to abstract the small size parameter.
2666 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2667 
2668 /// Recursively add the bases of Type.  Don't add Type itself.
2669 static void
2670 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2671                   const QualType &Type)
2672 {
2673   // Even though the incoming type is a base, it might not be
2674   // a class -- it could be a template parm, for instance.
2675   if (auto Rec = Type->getAs<RecordType>()) {
2676     auto Decl = Rec->getAsCXXRecordDecl();
2677 
2678     // Iterate over its bases.
2679     for (const auto &BaseSpec : Decl->bases()) {
2680       QualType Base = Context.getCanonicalType(BaseSpec.getType())
2681         .getUnqualifiedType();
2682       if (Set.insert(Base).second)
2683         // If we've not already seen it, recurse.
2684         NoteIndirectBases(Context, Set, Base);
2685     }
2686   }
2687 }
2688 
2689 /// Performs the actual work of attaching the given base class
2690 /// specifiers to a C++ class.
2691 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2692                                 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2693  if (Bases.empty())
2694     return false;
2695 
2696   // Used to keep track of which base types we have already seen, so
2697   // that we can properly diagnose redundant direct base types. Note
2698   // that the key is always the unqualified canonical type of the base
2699   // class.
2700   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2701 
2702   // Used to track indirect bases so we can see if a direct base is
2703   // ambiguous.
2704   IndirectBaseSet IndirectBaseTypes;
2705 
2706   // Copy non-redundant base specifiers into permanent storage.
2707   unsigned NumGoodBases = 0;
2708   bool Invalid = false;
2709   for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2710     QualType NewBaseType
2711       = Context.getCanonicalType(Bases[idx]->getType());
2712     NewBaseType = NewBaseType.getLocalUnqualifiedType();
2713 
2714     CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2715     if (KnownBase) {
2716       // C++ [class.mi]p3:
2717       //   A class shall not be specified as a direct base class of a
2718       //   derived class more than once.
2719       Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2720           << KnownBase->getType() << Bases[idx]->getSourceRange();
2721 
2722       // Delete the duplicate base class specifier; we're going to
2723       // overwrite its pointer later.
2724       Context.Deallocate(Bases[idx]);
2725 
2726       Invalid = true;
2727     } else {
2728       // Okay, add this new base class.
2729       KnownBase = Bases[idx];
2730       Bases[NumGoodBases++] = Bases[idx];
2731 
2732       if (NewBaseType->isDependentType())
2733         continue;
2734       // Note this base's direct & indirect bases, if there could be ambiguity.
2735       if (Bases.size() > 1)
2736         NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2737 
2738       if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2739         const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2740         if (Class->isInterface() &&
2741               (!RD->isInterfaceLike() ||
2742                KnownBase->getAccessSpecifier() != AS_public)) {
2743           // The Microsoft extension __interface does not permit bases that
2744           // are not themselves public interfaces.
2745           Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2746               << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2747               << RD->getSourceRange();
2748           Invalid = true;
2749         }
2750         if (RD->hasAttr<WeakAttr>())
2751           Class->addAttr(WeakAttr::CreateImplicit(Context));
2752       }
2753     }
2754   }
2755 
2756   // Attach the remaining base class specifiers to the derived class.
2757   Class->setBases(Bases.data(), NumGoodBases);
2758 
2759   // Check that the only base classes that are duplicate are virtual.
2760   for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2761     // Check whether this direct base is inaccessible due to ambiguity.
2762     QualType BaseType = Bases[idx]->getType();
2763 
2764     // Skip all dependent types in templates being used as base specifiers.
2765     // Checks below assume that the base specifier is a CXXRecord.
2766     if (BaseType->isDependentType())
2767       continue;
2768 
2769     CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2770       .getUnqualifiedType();
2771 
2772     if (IndirectBaseTypes.count(CanonicalBase)) {
2773       CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2774                          /*DetectVirtual=*/true);
2775       bool found
2776         = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2777       assert(found);
2778       (void)found;
2779 
2780       if (Paths.isAmbiguous(CanonicalBase))
2781         Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2782             << BaseType << getAmbiguousPathsDisplayString(Paths)
2783             << Bases[idx]->getSourceRange();
2784       else
2785         assert(Bases[idx]->isVirtual());
2786     }
2787 
2788     // Delete the base class specifier, since its data has been copied
2789     // into the CXXRecordDecl.
2790     Context.Deallocate(Bases[idx]);
2791   }
2792 
2793   return Invalid;
2794 }
2795 
2796 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2797 /// class, after checking whether there are any duplicate base
2798 /// classes.
2799 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2800                                MutableArrayRef<CXXBaseSpecifier *> Bases) {
2801   if (!ClassDecl || Bases.empty())
2802     return;
2803 
2804   AdjustDeclIfTemplate(ClassDecl);
2805   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2806 }
2807 
2808 /// Determine whether the type \p Derived is a C++ class that is
2809 /// derived from the type \p Base.
2810 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2811   if (!getLangOpts().CPlusPlus)
2812     return false;
2813 
2814   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2815   if (!DerivedRD)
2816     return false;
2817 
2818   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2819   if (!BaseRD)
2820     return false;
2821 
2822   // If either the base or the derived type is invalid, don't try to
2823   // check whether one is derived from the other.
2824   if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2825     return false;
2826 
2827   // FIXME: In a modules build, do we need the entire path to be visible for us
2828   // to be able to use the inheritance relationship?
2829   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2830     return false;
2831 
2832   return DerivedRD->isDerivedFrom(BaseRD);
2833 }
2834 
2835 /// Determine whether the type \p Derived is a C++ class that is
2836 /// derived from the type \p Base.
2837 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2838                          CXXBasePaths &Paths) {
2839   if (!getLangOpts().CPlusPlus)
2840     return false;
2841 
2842   CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2843   if (!DerivedRD)
2844     return false;
2845 
2846   CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2847   if (!BaseRD)
2848     return false;
2849 
2850   if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2851     return false;
2852 
2853   return DerivedRD->isDerivedFrom(BaseRD, Paths);
2854 }
2855 
2856 static void BuildBasePathArray(const CXXBasePath &Path,
2857                                CXXCastPath &BasePathArray) {
2858   // We first go backward and check if we have a virtual base.
2859   // FIXME: It would be better if CXXBasePath had the base specifier for
2860   // the nearest virtual base.
2861   unsigned Start = 0;
2862   for (unsigned I = Path.size(); I != 0; --I) {
2863     if (Path[I - 1].Base->isVirtual()) {
2864       Start = I - 1;
2865       break;
2866     }
2867   }
2868 
2869   // Now add all bases.
2870   for (unsigned I = Start, E = Path.size(); I != E; ++I)
2871     BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2872 }
2873 
2874 
2875 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2876                               CXXCastPath &BasePathArray) {
2877   assert(BasePathArray.empty() && "Base path array must be empty!");
2878   assert(Paths.isRecordingPaths() && "Must record paths!");
2879   return ::BuildBasePathArray(Paths.front(), BasePathArray);
2880 }
2881 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2882 /// conversion (where Derived and Base are class types) is
2883 /// well-formed, meaning that the conversion is unambiguous (and
2884 /// that all of the base classes are accessible). Returns true
2885 /// and emits a diagnostic if the code is ill-formed, returns false
2886 /// otherwise. Loc is the location where this routine should point to
2887 /// if there is an error, and Range is the source range to highlight
2888 /// if there is an error.
2889 ///
2890 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2891 /// diagnostic for the respective type of error will be suppressed, but the
2892 /// check for ill-formed code will still be performed.
2893 bool
2894 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2895                                    unsigned InaccessibleBaseID,
2896                                    unsigned AmbiguousBaseConvID,
2897                                    SourceLocation Loc, SourceRange Range,
2898                                    DeclarationName Name,
2899                                    CXXCastPath *BasePath,
2900                                    bool IgnoreAccess) {
2901   // First, determine whether the path from Derived to Base is
2902   // ambiguous. This is slightly more expensive than checking whether
2903   // the Derived to Base conversion exists, because here we need to
2904   // explore multiple paths to determine if there is an ambiguity.
2905   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2906                      /*DetectVirtual=*/false);
2907   bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2908   if (!DerivationOkay)
2909     return true;
2910 
2911   const CXXBasePath *Path = nullptr;
2912   if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2913     Path = &Paths.front();
2914 
2915   // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2916   // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2917   // user to access such bases.
2918   if (!Path && getLangOpts().MSVCCompat) {
2919     for (const CXXBasePath &PossiblePath : Paths) {
2920       if (PossiblePath.size() == 1) {
2921         Path = &PossiblePath;
2922         if (AmbiguousBaseConvID)
2923           Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2924               << Base << Derived << Range;
2925         break;
2926       }
2927     }
2928   }
2929 
2930   if (Path) {
2931     if (!IgnoreAccess) {
2932       // Check that the base class can be accessed.
2933       switch (
2934           CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2935       case AR_inaccessible:
2936         return true;
2937       case AR_accessible:
2938       case AR_dependent:
2939       case AR_delayed:
2940         break;
2941       }
2942     }
2943 
2944     // Build a base path if necessary.
2945     if (BasePath)
2946       ::BuildBasePathArray(*Path, *BasePath);
2947     return false;
2948   }
2949 
2950   if (AmbiguousBaseConvID) {
2951     // We know that the derived-to-base conversion is ambiguous, and
2952     // we're going to produce a diagnostic. Perform the derived-to-base
2953     // search just one more time to compute all of the possible paths so
2954     // that we can print them out. This is more expensive than any of
2955     // the previous derived-to-base checks we've done, but at this point
2956     // performance isn't as much of an issue.
2957     Paths.clear();
2958     Paths.setRecordingPaths(true);
2959     bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2960     assert(StillOkay && "Can only be used with a derived-to-base conversion");
2961     (void)StillOkay;
2962 
2963     // Build up a textual representation of the ambiguous paths, e.g.,
2964     // D -> B -> A, that will be used to illustrate the ambiguous
2965     // conversions in the diagnostic. We only print one of the paths
2966     // to each base class subobject.
2967     std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2968 
2969     Diag(Loc, AmbiguousBaseConvID)
2970     << Derived << Base << PathDisplayStr << Range << Name;
2971   }
2972   return true;
2973 }
2974 
2975 bool
2976 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2977                                    SourceLocation Loc, SourceRange Range,
2978                                    CXXCastPath *BasePath,
2979                                    bool IgnoreAccess) {
2980   return CheckDerivedToBaseConversion(
2981       Derived, Base, diag::err_upcast_to_inaccessible_base,
2982       diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2983       BasePath, IgnoreAccess);
2984 }
2985 
2986 
2987 /// Builds a string representing ambiguous paths from a
2988 /// specific derived class to different subobjects of the same base
2989 /// class.
2990 ///
2991 /// This function builds a string that can be used in error messages
2992 /// to show the different paths that one can take through the
2993 /// inheritance hierarchy to go from the derived class to different
2994 /// subobjects of a base class. The result looks something like this:
2995 /// @code
2996 /// struct D -> struct B -> struct A
2997 /// struct D -> struct C -> struct A
2998 /// @endcode
2999 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3000   std::string PathDisplayStr;
3001   std::set<unsigned> DisplayedPaths;
3002   for (CXXBasePaths::paths_iterator Path = Paths.begin();
3003        Path != Paths.end(); ++Path) {
3004     if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3005       // We haven't displayed a path to this particular base
3006       // class subobject yet.
3007       PathDisplayStr += "\n    ";
3008       PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3009       for (CXXBasePath::const_iterator Element = Path->begin();
3010            Element != Path->end(); ++Element)
3011         PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3012     }
3013   }
3014 
3015   return PathDisplayStr;
3016 }
3017 
3018 //===----------------------------------------------------------------------===//
3019 // C++ class member Handling
3020 //===----------------------------------------------------------------------===//
3021 
3022 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3023 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3024                                 SourceLocation ColonLoc,
3025                                 const ParsedAttributesView &Attrs) {
3026   assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3027   AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3028                                                   ASLoc, ColonLoc);
3029   CurContext->addHiddenDecl(ASDecl);
3030   return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3031 }
3032 
3033 /// CheckOverrideControl - Check C++11 override control semantics.
3034 void Sema::CheckOverrideControl(NamedDecl *D) {
3035   if (D->isInvalidDecl())
3036     return;
3037 
3038   // We only care about "override" and "final" declarations.
3039   if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3040     return;
3041 
3042   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3043 
3044   // We can't check dependent instance methods.
3045   if (MD && MD->isInstance() &&
3046       (MD->getParent()->hasAnyDependentBases() ||
3047        MD->getType()->isDependentType()))
3048     return;
3049 
3050   if (MD && !MD->isVirtual()) {
3051     // If we have a non-virtual method, check if if hides a virtual method.
3052     // (In that case, it's most likely the method has the wrong type.)
3053     SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3054     FindHiddenVirtualMethods(MD, OverloadedMethods);
3055 
3056     if (!OverloadedMethods.empty()) {
3057       if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3058         Diag(OA->getLocation(),
3059              diag::override_keyword_hides_virtual_member_function)
3060           << "override" << (OverloadedMethods.size() > 1);
3061       } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3062         Diag(FA->getLocation(),
3063              diag::override_keyword_hides_virtual_member_function)
3064           << (FA->isSpelledAsSealed() ? "sealed" : "final")
3065           << (OverloadedMethods.size() > 1);
3066       }
3067       NoteHiddenVirtualMethods(MD, OverloadedMethods);
3068       MD->setInvalidDecl();
3069       return;
3070     }
3071     // Fall through into the general case diagnostic.
3072     // FIXME: We might want to attempt typo correction here.
3073   }
3074 
3075   if (!MD || !MD->isVirtual()) {
3076     if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3077       Diag(OA->getLocation(),
3078            diag::override_keyword_only_allowed_on_virtual_member_functions)
3079         << "override" << FixItHint::CreateRemoval(OA->getLocation());
3080       D->dropAttr<OverrideAttr>();
3081     }
3082     if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3083       Diag(FA->getLocation(),
3084            diag::override_keyword_only_allowed_on_virtual_member_functions)
3085         << (FA->isSpelledAsSealed() ? "sealed" : "final")
3086         << FixItHint::CreateRemoval(FA->getLocation());
3087       D->dropAttr<FinalAttr>();
3088     }
3089     return;
3090   }
3091 
3092   // C++11 [class.virtual]p5:
3093   //   If a function is marked with the virt-specifier override and
3094   //   does not override a member function of a base class, the program is
3095   //   ill-formed.
3096   bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3097   if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3098     Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3099       << MD->getDeclName();
3100 }
3101 
3102 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3103   if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3104     return;
3105   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3106   if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3107     return;
3108 
3109   SourceLocation Loc = MD->getLocation();
3110   SourceLocation SpellingLoc = Loc;
3111   if (getSourceManager().isMacroArgExpansion(Loc))
3112     SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3113   SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3114   if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3115       return;
3116 
3117   if (MD->size_overridden_methods() > 0) {
3118     auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3119       unsigned DiagID =
3120           Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3121               ? DiagInconsistent
3122               : DiagSuggest;
3123       Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3124       const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3125       Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3126     };
3127     if (isa<CXXDestructorDecl>(MD))
3128       EmitDiag(
3129           diag::warn_inconsistent_destructor_marked_not_override_overriding,
3130           diag::warn_suggest_destructor_marked_not_override_overriding);
3131     else
3132       EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3133                diag::warn_suggest_function_marked_not_override_overriding);
3134   }
3135 }
3136 
3137 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3138 /// function overrides a virtual member function marked 'final', according to
3139 /// C++11 [class.virtual]p4.
3140 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3141                                                   const CXXMethodDecl *Old) {
3142   FinalAttr *FA = Old->getAttr<FinalAttr>();
3143   if (!FA)
3144     return false;
3145 
3146   Diag(New->getLocation(), diag::err_final_function_overridden)
3147     << New->getDeclName()
3148     << FA->isSpelledAsSealed();
3149   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3150   return true;
3151 }
3152 
3153 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3154   const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3155   // FIXME: Destruction of ObjC lifetime types has side-effects.
3156   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3157     return !RD->isCompleteDefinition() ||
3158            !RD->hasTrivialDefaultConstructor() ||
3159            !RD->hasTrivialDestructor();
3160   return false;
3161 }
3162 
3163 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3164   ParsedAttributesView::const_iterator Itr =
3165       llvm::find_if(list, [](const ParsedAttr &AL) {
3166         return AL.isDeclspecPropertyAttribute();
3167       });
3168   if (Itr != list.end())
3169     return &*Itr;
3170   return nullptr;
3171 }
3172 
3173 // Check if there is a field shadowing.
3174 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3175                                       DeclarationName FieldName,
3176                                       const CXXRecordDecl *RD,
3177                                       bool DeclIsField) {
3178   if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3179     return;
3180 
3181   // To record a shadowed field in a base
3182   std::map<CXXRecordDecl*, NamedDecl*> Bases;
3183   auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3184                            CXXBasePath &Path) {
3185     const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3186     // Record an ambiguous path directly
3187     if (Bases.find(Base) != Bases.end())
3188       return true;
3189     for (const auto Field : Base->lookup(FieldName)) {
3190       if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3191           Field->getAccess() != AS_private) {
3192         assert(Field->getAccess() != AS_none);
3193         assert(Bases.find(Base) == Bases.end());
3194         Bases[Base] = Field;
3195         return true;
3196       }
3197     }
3198     return false;
3199   };
3200 
3201   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3202                      /*DetectVirtual=*/true);
3203   if (!RD->lookupInBases(FieldShadowed, Paths))
3204     return;
3205 
3206   for (const auto &P : Paths) {
3207     auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3208     auto It = Bases.find(Base);
3209     // Skip duplicated bases
3210     if (It == Bases.end())
3211       continue;
3212     auto BaseField = It->second;
3213     assert(BaseField->getAccess() != AS_private);
3214     if (AS_none !=
3215         CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3216       Diag(Loc, diag::warn_shadow_field)
3217         << FieldName << RD << Base << DeclIsField;
3218       Diag(BaseField->getLocation(), diag::note_shadow_field);
3219       Bases.erase(It);
3220     }
3221   }
3222 }
3223 
3224 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3225 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3226 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3227 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3228 /// present (but parsing it has been deferred).
3229 NamedDecl *
3230 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3231                                MultiTemplateParamsArg TemplateParameterLists,
3232                                Expr *BW, const VirtSpecifiers &VS,
3233                                InClassInitStyle InitStyle) {
3234   const DeclSpec &DS = D.getDeclSpec();
3235   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3236   DeclarationName Name = NameInfo.getName();
3237   SourceLocation Loc = NameInfo.getLoc();
3238 
3239   // For anonymous bitfields, the location should point to the type.
3240   if (Loc.isInvalid())
3241     Loc = D.getBeginLoc();
3242 
3243   Expr *BitWidth = static_cast<Expr*>(BW);
3244 
3245   assert(isa<CXXRecordDecl>(CurContext));
3246   assert(!DS.isFriendSpecified());
3247 
3248   bool isFunc = D.isDeclarationOfFunction();
3249   const ParsedAttr *MSPropertyAttr =
3250       getMSPropertyAttr(D.getDeclSpec().getAttributes());
3251 
3252   if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3253     // The Microsoft extension __interface only permits public member functions
3254     // and prohibits constructors, destructors, operators, non-public member
3255     // functions, static methods and data members.
3256     unsigned InvalidDecl;
3257     bool ShowDeclName = true;
3258     if (!isFunc &&
3259         (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3260       InvalidDecl = 0;
3261     else if (!isFunc)
3262       InvalidDecl = 1;
3263     else if (AS != AS_public)
3264       InvalidDecl = 2;
3265     else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3266       InvalidDecl = 3;
3267     else switch (Name.getNameKind()) {
3268       case DeclarationName::CXXConstructorName:
3269         InvalidDecl = 4;
3270         ShowDeclName = false;
3271         break;
3272 
3273       case DeclarationName::CXXDestructorName:
3274         InvalidDecl = 5;
3275         ShowDeclName = false;
3276         break;
3277 
3278       case DeclarationName::CXXOperatorName:
3279       case DeclarationName::CXXConversionFunctionName:
3280         InvalidDecl = 6;
3281         break;
3282 
3283       default:
3284         InvalidDecl = 0;
3285         break;
3286     }
3287 
3288     if (InvalidDecl) {
3289       if (ShowDeclName)
3290         Diag(Loc, diag::err_invalid_member_in_interface)
3291           << (InvalidDecl-1) << Name;
3292       else
3293         Diag(Loc, diag::err_invalid_member_in_interface)
3294           << (InvalidDecl-1) << "";
3295       return nullptr;
3296     }
3297   }
3298 
3299   // C++ 9.2p6: A member shall not be declared to have automatic storage
3300   // duration (auto, register) or with the extern storage-class-specifier.
3301   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3302   // data members and cannot be applied to names declared const or static,
3303   // and cannot be applied to reference members.
3304   switch (DS.getStorageClassSpec()) {
3305   case DeclSpec::SCS_unspecified:
3306   case DeclSpec::SCS_typedef:
3307   case DeclSpec::SCS_static:
3308     break;
3309   case DeclSpec::SCS_mutable:
3310     if (isFunc) {
3311       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3312 
3313       // FIXME: It would be nicer if the keyword was ignored only for this
3314       // declarator. Otherwise we could get follow-up errors.
3315       D.getMutableDeclSpec().ClearStorageClassSpecs();
3316     }
3317     break;
3318   default:
3319     Diag(DS.getStorageClassSpecLoc(),
3320          diag::err_storageclass_invalid_for_member);
3321     D.getMutableDeclSpec().ClearStorageClassSpecs();
3322     break;
3323   }
3324 
3325   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3326                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3327                       !isFunc);
3328 
3329   if (DS.hasConstexprSpecifier() && isInstField) {
3330     SemaDiagnosticBuilder B =
3331         Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3332     SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3333     if (InitStyle == ICIS_NoInit) {
3334       B << 0 << 0;
3335       if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3336         B << FixItHint::CreateRemoval(ConstexprLoc);
3337       else {
3338         B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3339         D.getMutableDeclSpec().ClearConstexprSpec();
3340         const char *PrevSpec;
3341         unsigned DiagID;
3342         bool Failed = D.getMutableDeclSpec().SetTypeQual(
3343             DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3344         (void)Failed;
3345         assert(!Failed && "Making a constexpr member const shouldn't fail");
3346       }
3347     } else {
3348       B << 1;
3349       const char *PrevSpec;
3350       unsigned DiagID;
3351       if (D.getMutableDeclSpec().SetStorageClassSpec(
3352           *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3353           Context.getPrintingPolicy())) {
3354         assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3355                "This is the only DeclSpec that should fail to be applied");
3356         B << 1;
3357       } else {
3358         B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3359         isInstField = false;
3360       }
3361     }
3362   }
3363 
3364   NamedDecl *Member;
3365   if (isInstField) {
3366     CXXScopeSpec &SS = D.getCXXScopeSpec();
3367 
3368     // Data members must have identifiers for names.
3369     if (!Name.isIdentifier()) {
3370       Diag(Loc, diag::err_bad_variable_name)
3371         << Name;
3372       return nullptr;
3373     }
3374 
3375     IdentifierInfo *II = Name.getAsIdentifierInfo();
3376 
3377     // Member field could not be with "template" keyword.
3378     // So TemplateParameterLists should be empty in this case.
3379     if (TemplateParameterLists.size()) {
3380       TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3381       if (TemplateParams->size()) {
3382         // There is no such thing as a member field template.
3383         Diag(D.getIdentifierLoc(), diag::err_template_member)
3384             << II
3385             << SourceRange(TemplateParams->getTemplateLoc(),
3386                 TemplateParams->getRAngleLoc());
3387       } else {
3388         // There is an extraneous 'template<>' for this member.
3389         Diag(TemplateParams->getTemplateLoc(),
3390             diag::err_template_member_noparams)
3391             << II
3392             << SourceRange(TemplateParams->getTemplateLoc(),
3393                 TemplateParams->getRAngleLoc());
3394       }
3395       return nullptr;
3396     }
3397 
3398     if (SS.isSet() && !SS.isInvalid()) {
3399       // The user provided a superfluous scope specifier inside a class
3400       // definition:
3401       //
3402       // class X {
3403       //   int X::member;
3404       // };
3405       if (DeclContext *DC = computeDeclContext(SS, false))
3406         diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3407                                      D.getName().getKind() ==
3408                                          UnqualifiedIdKind::IK_TemplateId);
3409       else
3410         Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3411           << Name << SS.getRange();
3412 
3413       SS.clear();
3414     }
3415 
3416     if (MSPropertyAttr) {
3417       Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3418                                 BitWidth, InitStyle, AS, *MSPropertyAttr);
3419       if (!Member)
3420         return nullptr;
3421       isInstField = false;
3422     } else {
3423       Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3424                                 BitWidth, InitStyle, AS);
3425       if (!Member)
3426         return nullptr;
3427     }
3428 
3429     CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3430   } else {
3431     Member = HandleDeclarator(S, D, TemplateParameterLists);
3432     if (!Member)
3433       return nullptr;
3434 
3435     // Non-instance-fields can't have a bitfield.
3436     if (BitWidth) {
3437       if (Member->isInvalidDecl()) {
3438         // don't emit another diagnostic.
3439       } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3440         // C++ 9.6p3: A bit-field shall not be a static member.
3441         // "static member 'A' cannot be a bit-field"
3442         Diag(Loc, diag::err_static_not_bitfield)
3443           << Name << BitWidth->getSourceRange();
3444       } else if (isa<TypedefDecl>(Member)) {
3445         // "typedef member 'x' cannot be a bit-field"
3446         Diag(Loc, diag::err_typedef_not_bitfield)
3447           << Name << BitWidth->getSourceRange();
3448       } else {
3449         // A function typedef ("typedef int f(); f a;").
3450         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3451         Diag(Loc, diag::err_not_integral_type_bitfield)
3452           << Name << cast<ValueDecl>(Member)->getType()
3453           << BitWidth->getSourceRange();
3454       }
3455 
3456       BitWidth = nullptr;
3457       Member->setInvalidDecl();
3458     }
3459 
3460     NamedDecl *NonTemplateMember = Member;
3461     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3462       NonTemplateMember = FunTmpl->getTemplatedDecl();
3463     else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3464       NonTemplateMember = VarTmpl->getTemplatedDecl();
3465 
3466     Member->setAccess(AS);
3467 
3468     // If we have declared a member function template or static data member
3469     // template, set the access of the templated declaration as well.
3470     if (NonTemplateMember != Member)
3471       NonTemplateMember->setAccess(AS);
3472 
3473     // C++ [temp.deduct.guide]p3:
3474     //   A deduction guide [...] for a member class template [shall be
3475     //   declared] with the same access [as the template].
3476     if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3477       auto *TD = DG->getDeducedTemplate();
3478       // Access specifiers are only meaningful if both the template and the
3479       // deduction guide are from the same scope.
3480       if (AS != TD->getAccess() &&
3481           TD->getDeclContext()->getRedeclContext()->Equals(
3482               DG->getDeclContext()->getRedeclContext())) {
3483         Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3484         Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3485             << TD->getAccess();
3486         const AccessSpecDecl *LastAccessSpec = nullptr;
3487         for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3488           if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3489             LastAccessSpec = AccessSpec;
3490         }
3491         assert(LastAccessSpec && "differing access with no access specifier");
3492         Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3493             << AS;
3494       }
3495     }
3496   }
3497 
3498   if (VS.isOverrideSpecified())
3499     Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3500                                          AttributeCommonInfo::AS_Keyword));
3501   if (VS.isFinalSpecified())
3502     Member->addAttr(FinalAttr::Create(
3503         Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3504         static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3505 
3506   if (VS.getLastLocation().isValid()) {
3507     // Update the end location of a method that has a virt-specifiers.
3508     if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3509       MD->setRangeEnd(VS.getLastLocation());
3510   }
3511 
3512   CheckOverrideControl(Member);
3513 
3514   assert((Name || isInstField) && "No identifier for non-field ?");
3515 
3516   if (isInstField) {
3517     FieldDecl *FD = cast<FieldDecl>(Member);
3518     FieldCollector->Add(FD);
3519 
3520     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3521       // Remember all explicit private FieldDecls that have a name, no side
3522       // effects and are not part of a dependent type declaration.
3523       if (!FD->isImplicit() && FD->getDeclName() &&
3524           FD->getAccess() == AS_private &&
3525           !FD->hasAttr<UnusedAttr>() &&
3526           !FD->getParent()->isDependentContext() &&
3527           !InitializationHasSideEffects(*FD))
3528         UnusedPrivateFields.insert(FD);
3529     }
3530   }
3531 
3532   return Member;
3533 }
3534 
3535 namespace {
3536   class UninitializedFieldVisitor
3537       : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3538     Sema &S;
3539     // List of Decls to generate a warning on.  Also remove Decls that become
3540     // initialized.
3541     llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3542     // List of base classes of the record.  Classes are removed after their
3543     // initializers.
3544     llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3545     // Vector of decls to be removed from the Decl set prior to visiting the
3546     // nodes.  These Decls may have been initialized in the prior initializer.
3547     llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3548     // If non-null, add a note to the warning pointing back to the constructor.
3549     const CXXConstructorDecl *Constructor;
3550     // Variables to hold state when processing an initializer list.  When
3551     // InitList is true, special case initialization of FieldDecls matching
3552     // InitListFieldDecl.
3553     bool InitList;
3554     FieldDecl *InitListFieldDecl;
3555     llvm::SmallVector<unsigned, 4> InitFieldIndex;
3556 
3557   public:
3558     typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3559     UninitializedFieldVisitor(Sema &S,
3560                               llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3561                               llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3562       : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3563         Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3564 
3565     // Returns true if the use of ME is not an uninitialized use.
3566     bool IsInitListMemberExprInitialized(MemberExpr *ME,
3567                                          bool CheckReferenceOnly) {
3568       llvm::SmallVector<FieldDecl*, 4> Fields;
3569       bool ReferenceField = false;
3570       while (ME) {
3571         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3572         if (!FD)
3573           return false;
3574         Fields.push_back(FD);
3575         if (FD->getType()->isReferenceType())
3576           ReferenceField = true;
3577         ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3578       }
3579 
3580       // Binding a reference to an uninitialized field is not an
3581       // uninitialized use.
3582       if (CheckReferenceOnly && !ReferenceField)
3583         return true;
3584 
3585       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3586       // Discard the first field since it is the field decl that is being
3587       // initialized.
3588       for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3589         UsedFieldIndex.push_back(FD->getFieldIndex());
3590 
3591       for (auto UsedIter = UsedFieldIndex.begin(),
3592                 UsedEnd = UsedFieldIndex.end(),
3593                 OrigIter = InitFieldIndex.begin(),
3594                 OrigEnd = InitFieldIndex.end();
3595            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3596         if (*UsedIter < *OrigIter)
3597           return true;
3598         if (*UsedIter > *OrigIter)
3599           break;
3600       }
3601 
3602       return false;
3603     }
3604 
3605     void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3606                           bool AddressOf) {
3607       if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3608         return;
3609 
3610       // FieldME is the inner-most MemberExpr that is not an anonymous struct
3611       // or union.
3612       MemberExpr *FieldME = ME;
3613 
3614       bool AllPODFields = FieldME->getType().isPODType(S.Context);
3615 
3616       Expr *Base = ME;
3617       while (MemberExpr *SubME =
3618                  dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3619 
3620         if (isa<VarDecl>(SubME->getMemberDecl()))
3621           return;
3622 
3623         if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3624           if (!FD->isAnonymousStructOrUnion())
3625             FieldME = SubME;
3626 
3627         if (!FieldME->getType().isPODType(S.Context))
3628           AllPODFields = false;
3629 
3630         Base = SubME->getBase();
3631       }
3632 
3633       if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3634         Visit(Base);
3635         return;
3636       }
3637 
3638       if (AddressOf && AllPODFields)
3639         return;
3640 
3641       ValueDecl* FoundVD = FieldME->getMemberDecl();
3642 
3643       if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3644         while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3645           BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3646         }
3647 
3648         if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3649           QualType T = BaseCast->getType();
3650           if (T->isPointerType() &&
3651               BaseClasses.count(T->getPointeeType())) {
3652             S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3653                 << T->getPointeeType() << FoundVD;
3654           }
3655         }
3656       }
3657 
3658       if (!Decls.count(FoundVD))
3659         return;
3660 
3661       const bool IsReference = FoundVD->getType()->isReferenceType();
3662 
3663       if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3664         // Special checking for initializer lists.
3665         if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3666           return;
3667         }
3668       } else {
3669         // Prevent double warnings on use of unbounded references.
3670         if (CheckReferenceOnly && !IsReference)
3671           return;
3672       }
3673 
3674       unsigned diag = IsReference
3675           ? diag::warn_reference_field_is_uninit
3676           : diag::warn_field_is_uninit;
3677       S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3678       if (Constructor)
3679         S.Diag(Constructor->getLocation(),
3680                diag::note_uninit_in_this_constructor)
3681           << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3682 
3683     }
3684 
3685     void HandleValue(Expr *E, bool AddressOf) {
3686       E = E->IgnoreParens();
3687 
3688       if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3689         HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3690                          AddressOf /*AddressOf*/);
3691         return;
3692       }
3693 
3694       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3695         Visit(CO->getCond());
3696         HandleValue(CO->getTrueExpr(), AddressOf);
3697         HandleValue(CO->getFalseExpr(), AddressOf);
3698         return;
3699       }
3700 
3701       if (BinaryConditionalOperator *BCO =
3702               dyn_cast<BinaryConditionalOperator>(E)) {
3703         Visit(BCO->getCond());
3704         HandleValue(BCO->getFalseExpr(), AddressOf);
3705         return;
3706       }
3707 
3708       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3709         HandleValue(OVE->getSourceExpr(), AddressOf);
3710         return;
3711       }
3712 
3713       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3714         switch (BO->getOpcode()) {
3715         default:
3716           break;
3717         case(BO_PtrMemD):
3718         case(BO_PtrMemI):
3719           HandleValue(BO->getLHS(), AddressOf);
3720           Visit(BO->getRHS());
3721           return;
3722         case(BO_Comma):
3723           Visit(BO->getLHS());
3724           HandleValue(BO->getRHS(), AddressOf);
3725           return;
3726         }
3727       }
3728 
3729       Visit(E);
3730     }
3731 
3732     void CheckInitListExpr(InitListExpr *ILE) {
3733       InitFieldIndex.push_back(0);
3734       for (auto Child : ILE->children()) {
3735         if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3736           CheckInitListExpr(SubList);
3737         } else {
3738           Visit(Child);
3739         }
3740         ++InitFieldIndex.back();
3741       }
3742       InitFieldIndex.pop_back();
3743     }
3744 
3745     void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3746                           FieldDecl *Field, const Type *BaseClass) {
3747       // Remove Decls that may have been initialized in the previous
3748       // initializer.
3749       for (ValueDecl* VD : DeclsToRemove)
3750         Decls.erase(VD);
3751       DeclsToRemove.clear();
3752 
3753       Constructor = FieldConstructor;
3754       InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3755 
3756       if (ILE && Field) {
3757         InitList = true;
3758         InitListFieldDecl = Field;
3759         InitFieldIndex.clear();
3760         CheckInitListExpr(ILE);
3761       } else {
3762         InitList = false;
3763         Visit(E);
3764       }
3765 
3766       if (Field)
3767         Decls.erase(Field);
3768       if (BaseClass)
3769         BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3770     }
3771 
3772     void VisitMemberExpr(MemberExpr *ME) {
3773       // All uses of unbounded reference fields will warn.
3774       HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3775     }
3776 
3777     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3778       if (E->getCastKind() == CK_LValueToRValue) {
3779         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3780         return;
3781       }
3782 
3783       Inherited::VisitImplicitCastExpr(E);
3784     }
3785 
3786     void VisitCXXConstructExpr(CXXConstructExpr *E) {
3787       if (E->getConstructor()->isCopyConstructor()) {
3788         Expr *ArgExpr = E->getArg(0);
3789         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3790           if (ILE->getNumInits() == 1)
3791             ArgExpr = ILE->getInit(0);
3792         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3793           if (ICE->getCastKind() == CK_NoOp)
3794             ArgExpr = ICE->getSubExpr();
3795         HandleValue(ArgExpr, false /*AddressOf*/);
3796         return;
3797       }
3798       Inherited::VisitCXXConstructExpr(E);
3799     }
3800 
3801     void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3802       Expr *Callee = E->getCallee();
3803       if (isa<MemberExpr>(Callee)) {
3804         HandleValue(Callee, false /*AddressOf*/);
3805         for (auto Arg : E->arguments())
3806           Visit(Arg);
3807         return;
3808       }
3809 
3810       Inherited::VisitCXXMemberCallExpr(E);
3811     }
3812 
3813     void VisitCallExpr(CallExpr *E) {
3814       // Treat std::move as a use.
3815       if (E->isCallToStdMove()) {
3816         HandleValue(E->getArg(0), /*AddressOf=*/false);
3817         return;
3818       }
3819 
3820       Inherited::VisitCallExpr(E);
3821     }
3822 
3823     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3824       Expr *Callee = E->getCallee();
3825 
3826       if (isa<UnresolvedLookupExpr>(Callee))
3827         return Inherited::VisitCXXOperatorCallExpr(E);
3828 
3829       Visit(Callee);
3830       for (auto Arg : E->arguments())
3831         HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3832     }
3833 
3834     void VisitBinaryOperator(BinaryOperator *E) {
3835       // If a field assignment is detected, remove the field from the
3836       // uninitiailized field set.
3837       if (E->getOpcode() == BO_Assign)
3838         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3839           if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3840             if (!FD->getType()->isReferenceType())
3841               DeclsToRemove.push_back(FD);
3842 
3843       if (E->isCompoundAssignmentOp()) {
3844         HandleValue(E->getLHS(), false /*AddressOf*/);
3845         Visit(E->getRHS());
3846         return;
3847       }
3848 
3849       Inherited::VisitBinaryOperator(E);
3850     }
3851 
3852     void VisitUnaryOperator(UnaryOperator *E) {
3853       if (E->isIncrementDecrementOp()) {
3854         HandleValue(E->getSubExpr(), false /*AddressOf*/);
3855         return;
3856       }
3857       if (E->getOpcode() == UO_AddrOf) {
3858         if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3859           HandleValue(ME->getBase(), true /*AddressOf*/);
3860           return;
3861         }
3862       }
3863 
3864       Inherited::VisitUnaryOperator(E);
3865     }
3866   };
3867 
3868   // Diagnose value-uses of fields to initialize themselves, e.g.
3869   //   foo(foo)
3870   // where foo is not also a parameter to the constructor.
3871   // Also diagnose across field uninitialized use such as
3872   //   x(y), y(x)
3873   // TODO: implement -Wuninitialized and fold this into that framework.
3874   static void DiagnoseUninitializedFields(
3875       Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3876 
3877     if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3878                                            Constructor->getLocation())) {
3879       return;
3880     }
3881 
3882     if (Constructor->isInvalidDecl())
3883       return;
3884 
3885     const CXXRecordDecl *RD = Constructor->getParent();
3886 
3887     if (RD->isDependentContext())
3888       return;
3889 
3890     // Holds fields that are uninitialized.
3891     llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3892 
3893     // At the beginning, all fields are uninitialized.
3894     for (auto *I : RD->decls()) {
3895       if (auto *FD = dyn_cast<FieldDecl>(I)) {
3896         UninitializedFields.insert(FD);
3897       } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3898         UninitializedFields.insert(IFD->getAnonField());
3899       }
3900     }
3901 
3902     llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3903     for (auto I : RD->bases())
3904       UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3905 
3906     if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3907       return;
3908 
3909     UninitializedFieldVisitor UninitializedChecker(SemaRef,
3910                                                    UninitializedFields,
3911                                                    UninitializedBaseClasses);
3912 
3913     for (const auto *FieldInit : Constructor->inits()) {
3914       if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3915         break;
3916 
3917       Expr *InitExpr = FieldInit->getInit();
3918       if (!InitExpr)
3919         continue;
3920 
3921       if (CXXDefaultInitExpr *Default =
3922               dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3923         InitExpr = Default->getExpr();
3924         if (!InitExpr)
3925           continue;
3926         // In class initializers will point to the constructor.
3927         UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3928                                               FieldInit->getAnyMember(),
3929                                               FieldInit->getBaseClass());
3930       } else {
3931         UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3932                                               FieldInit->getAnyMember(),
3933                                               FieldInit->getBaseClass());
3934       }
3935     }
3936   }
3937 } // namespace
3938 
3939 /// Enter a new C++ default initializer scope. After calling this, the
3940 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3941 /// parsing or instantiating the initializer failed.
3942 void Sema::ActOnStartCXXInClassMemberInitializer() {
3943   // Create a synthetic function scope to represent the call to the constructor
3944   // that notionally surrounds a use of this initializer.
3945   PushFunctionScope();
3946 }
3947 
3948 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3949   if (!D.isFunctionDeclarator())
3950     return;
3951   auto &FTI = D.getFunctionTypeInfo();
3952   if (!FTI.Params)
3953     return;
3954   for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3955                                                           FTI.NumParams)) {
3956     auto *ParamDecl = cast<NamedDecl>(Param.Param);
3957     if (ParamDecl->getDeclName())
3958       PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3959   }
3960 }
3961 
3962 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3963   return ActOnRequiresClause(ConstraintExpr);
3964 }
3965 
3966 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
3967   if (ConstraintExpr.isInvalid())
3968     return ExprError();
3969 
3970   ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
3971   if (ConstraintExpr.isInvalid())
3972     return ExprError();
3973 
3974   if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
3975                                       UPPC_RequiresClause))
3976     return ExprError();
3977 
3978   return ConstraintExpr;
3979 }
3980 
3981 /// This is invoked after parsing an in-class initializer for a
3982 /// non-static C++ class member, and after instantiating an in-class initializer
3983 /// in a class template. Such actions are deferred until the class is complete.
3984 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3985                                                   SourceLocation InitLoc,
3986                                                   Expr *InitExpr) {
3987   // Pop the notional constructor scope we created earlier.
3988   PopFunctionScopeInfo(nullptr, D);
3989 
3990   FieldDecl *FD = dyn_cast<FieldDecl>(D);
3991   assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3992          "must set init style when field is created");
3993 
3994   if (!InitExpr) {
3995     D->setInvalidDecl();
3996     if (FD)
3997       FD->removeInClassInitializer();
3998     return;
3999   }
4000 
4001   if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
4002     FD->setInvalidDecl();
4003     FD->removeInClassInitializer();
4004     return;
4005   }
4006 
4007   ExprResult Init = InitExpr;
4008   if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
4009     InitializedEntity Entity =
4010         InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4011     InitializationKind Kind =
4012         FD->getInClassInitStyle() == ICIS_ListInit
4013             ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4014                                                    InitExpr->getBeginLoc(),
4015                                                    InitExpr->getEndLoc())
4016             : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4017     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4018     Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4019     if (Init.isInvalid()) {
4020       FD->setInvalidDecl();
4021       return;
4022     }
4023   }
4024 
4025   // C++11 [class.base.init]p7:
4026   //   The initialization of each base and member constitutes a
4027   //   full-expression.
4028   Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4029   if (Init.isInvalid()) {
4030     FD->setInvalidDecl();
4031     return;
4032   }
4033 
4034   InitExpr = Init.get();
4035 
4036   FD->setInClassInitializer(InitExpr);
4037 }
4038 
4039 /// Find the direct and/or virtual base specifiers that
4040 /// correspond to the given base type, for use in base initialization
4041 /// within a constructor.
4042 static bool FindBaseInitializer(Sema &SemaRef,
4043                                 CXXRecordDecl *ClassDecl,
4044                                 QualType BaseType,
4045                                 const CXXBaseSpecifier *&DirectBaseSpec,
4046                                 const CXXBaseSpecifier *&VirtualBaseSpec) {
4047   // First, check for a direct base class.
4048   DirectBaseSpec = nullptr;
4049   for (const auto &Base : ClassDecl->bases()) {
4050     if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4051       // We found a direct base of this type. That's what we're
4052       // initializing.
4053       DirectBaseSpec = &Base;
4054       break;
4055     }
4056   }
4057 
4058   // Check for a virtual base class.
4059   // FIXME: We might be able to short-circuit this if we know in advance that
4060   // there are no virtual bases.
4061   VirtualBaseSpec = nullptr;
4062   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4063     // We haven't found a base yet; search the class hierarchy for a
4064     // virtual base class.
4065     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4066                        /*DetectVirtual=*/false);
4067     if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4068                               SemaRef.Context.getTypeDeclType(ClassDecl),
4069                               BaseType, Paths)) {
4070       for (CXXBasePaths::paths_iterator Path = Paths.begin();
4071            Path != Paths.end(); ++Path) {
4072         if (Path->back().Base->isVirtual()) {
4073           VirtualBaseSpec = Path->back().Base;
4074           break;
4075         }
4076       }
4077     }
4078   }
4079 
4080   return DirectBaseSpec || VirtualBaseSpec;
4081 }
4082 
4083 /// Handle a C++ member initializer using braced-init-list syntax.
4084 MemInitResult
4085 Sema::ActOnMemInitializer(Decl *ConstructorD,
4086                           Scope *S,
4087                           CXXScopeSpec &SS,
4088                           IdentifierInfo *MemberOrBase,
4089                           ParsedType TemplateTypeTy,
4090                           const DeclSpec &DS,
4091                           SourceLocation IdLoc,
4092                           Expr *InitList,
4093                           SourceLocation EllipsisLoc) {
4094   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4095                              DS, IdLoc, InitList,
4096                              EllipsisLoc);
4097 }
4098 
4099 /// Handle a C++ member initializer using parentheses syntax.
4100 MemInitResult
4101 Sema::ActOnMemInitializer(Decl *ConstructorD,
4102                           Scope *S,
4103                           CXXScopeSpec &SS,
4104                           IdentifierInfo *MemberOrBase,
4105                           ParsedType TemplateTypeTy,
4106                           const DeclSpec &DS,
4107                           SourceLocation IdLoc,
4108                           SourceLocation LParenLoc,
4109                           ArrayRef<Expr *> Args,
4110                           SourceLocation RParenLoc,
4111                           SourceLocation EllipsisLoc) {
4112   Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4113   return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4114                              DS, IdLoc, List, EllipsisLoc);
4115 }
4116 
4117 namespace {
4118 
4119 // Callback to only accept typo corrections that can be a valid C++ member
4120 // initializer: either a non-static field member or a base class.
4121 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4122 public:
4123   explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4124       : ClassDecl(ClassDecl) {}
4125 
4126   bool ValidateCandidate(const TypoCorrection &candidate) override {
4127     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4128       if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4129         return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4130       return isa<TypeDecl>(ND);
4131     }
4132     return false;
4133   }
4134 
4135   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4136     return std::make_unique<MemInitializerValidatorCCC>(*this);
4137   }
4138 
4139 private:
4140   CXXRecordDecl *ClassDecl;
4141 };
4142 
4143 }
4144 
4145 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4146                                              CXXScopeSpec &SS,
4147                                              ParsedType TemplateTypeTy,
4148                                              IdentifierInfo *MemberOrBase) {
4149   if (SS.getScopeRep() || TemplateTypeTy)
4150     return nullptr;
4151   for (auto *D : ClassDecl->lookup(MemberOrBase))
4152     if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4153       return cast<ValueDecl>(D);
4154   return nullptr;
4155 }
4156 
4157 /// Handle a C++ member initializer.
4158 MemInitResult
4159 Sema::BuildMemInitializer(Decl *ConstructorD,
4160                           Scope *S,
4161                           CXXScopeSpec &SS,
4162                           IdentifierInfo *MemberOrBase,
4163                           ParsedType TemplateTypeTy,
4164                           const DeclSpec &DS,
4165                           SourceLocation IdLoc,
4166                           Expr *Init,
4167                           SourceLocation EllipsisLoc) {
4168   ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4169                                              /*RecoverUncorrectedTypos=*/true);
4170   if (!Res.isUsable())
4171     return true;
4172   Init = Res.get();
4173 
4174   if (!ConstructorD)
4175     return true;
4176 
4177   AdjustDeclIfTemplate(ConstructorD);
4178 
4179   CXXConstructorDecl *Constructor
4180     = dyn_cast<CXXConstructorDecl>(ConstructorD);
4181   if (!Constructor) {
4182     // The user wrote a constructor initializer on a function that is
4183     // not a C++ constructor. Ignore the error for now, because we may
4184     // have more member initializers coming; we'll diagnose it just
4185     // once in ActOnMemInitializers.
4186     return true;
4187   }
4188 
4189   CXXRecordDecl *ClassDecl = Constructor->getParent();
4190 
4191   // C++ [class.base.init]p2:
4192   //   Names in a mem-initializer-id are looked up in the scope of the
4193   //   constructor's class and, if not found in that scope, are looked
4194   //   up in the scope containing the constructor's definition.
4195   //   [Note: if the constructor's class contains a member with the
4196   //   same name as a direct or virtual base class of the class, a
4197   //   mem-initializer-id naming the member or base class and composed
4198   //   of a single identifier refers to the class member. A
4199   //   mem-initializer-id for the hidden base class may be specified
4200   //   using a qualified name. ]
4201 
4202   // Look for a member, first.
4203   if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4204           ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4205     if (EllipsisLoc.isValid())
4206       Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4207           << MemberOrBase
4208           << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4209 
4210     return BuildMemberInitializer(Member, Init, IdLoc);
4211   }
4212   // It didn't name a member, so see if it names a class.
4213   QualType BaseType;
4214   TypeSourceInfo *TInfo = nullptr;
4215 
4216   if (TemplateTypeTy) {
4217     BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4218     if (BaseType.isNull())
4219       return true;
4220   } else if (DS.getTypeSpecType() == TST_decltype) {
4221     BaseType = BuildDecltypeType(DS.getRepAsExpr());
4222   } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4223     Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4224     return true;
4225   } else {
4226     LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4227     LookupParsedName(R, S, &SS);
4228 
4229     TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4230     if (!TyD) {
4231       if (R.isAmbiguous()) return true;
4232 
4233       // We don't want access-control diagnostics here.
4234       R.suppressDiagnostics();
4235 
4236       if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4237         bool NotUnknownSpecialization = false;
4238         DeclContext *DC = computeDeclContext(SS, false);
4239         if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4240           NotUnknownSpecialization = !Record->hasAnyDependentBases();
4241 
4242         if (!NotUnknownSpecialization) {
4243           // When the scope specifier can refer to a member of an unknown
4244           // specialization, we take it as a type name.
4245           BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4246                                        SS.getWithLocInContext(Context),
4247                                        *MemberOrBase, IdLoc);
4248           if (BaseType.isNull())
4249             return true;
4250 
4251           TInfo = Context.CreateTypeSourceInfo(BaseType);
4252           DependentNameTypeLoc TL =
4253               TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4254           if (!TL.isNull()) {
4255             TL.setNameLoc(IdLoc);
4256             TL.setElaboratedKeywordLoc(SourceLocation());
4257             TL.setQualifierLoc(SS.getWithLocInContext(Context));
4258           }
4259 
4260           R.clear();
4261           R.setLookupName(MemberOrBase);
4262         }
4263       }
4264 
4265       // If no results were found, try to correct typos.
4266       TypoCorrection Corr;
4267       MemInitializerValidatorCCC CCC(ClassDecl);
4268       if (R.empty() && BaseType.isNull() &&
4269           (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4270                               CCC, CTK_ErrorRecovery, ClassDecl))) {
4271         if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4272           // We have found a non-static data member with a similar
4273           // name to what was typed; complain and initialize that
4274           // member.
4275           diagnoseTypo(Corr,
4276                        PDiag(diag::err_mem_init_not_member_or_class_suggest)
4277                          << MemberOrBase << true);
4278           return BuildMemberInitializer(Member, Init, IdLoc);
4279         } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4280           const CXXBaseSpecifier *DirectBaseSpec;
4281           const CXXBaseSpecifier *VirtualBaseSpec;
4282           if (FindBaseInitializer(*this, ClassDecl,
4283                                   Context.getTypeDeclType(Type),
4284                                   DirectBaseSpec, VirtualBaseSpec)) {
4285             // We have found a direct or virtual base class with a
4286             // similar name to what was typed; complain and initialize
4287             // that base class.
4288             diagnoseTypo(Corr,
4289                          PDiag(diag::err_mem_init_not_member_or_class_suggest)
4290                            << MemberOrBase << false,
4291                          PDiag() /*Suppress note, we provide our own.*/);
4292 
4293             const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4294                                                               : VirtualBaseSpec;
4295             Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4296                 << BaseSpec->getType() << BaseSpec->getSourceRange();
4297 
4298             TyD = Type;
4299           }
4300         }
4301       }
4302 
4303       if (!TyD && BaseType.isNull()) {
4304         Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4305           << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4306         return true;
4307       }
4308     }
4309 
4310     if (BaseType.isNull()) {
4311       BaseType = Context.getTypeDeclType(TyD);
4312       MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4313       if (SS.isSet()) {
4314         BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4315                                              BaseType);
4316         TInfo = Context.CreateTypeSourceInfo(BaseType);
4317         ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4318         TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4319         TL.setElaboratedKeywordLoc(SourceLocation());
4320         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4321       }
4322     }
4323   }
4324 
4325   if (!TInfo)
4326     TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4327 
4328   return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4329 }
4330 
4331 MemInitResult
4332 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4333                              SourceLocation IdLoc) {
4334   FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4335   IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4336   assert((DirectMember || IndirectMember) &&
4337          "Member must be a FieldDecl or IndirectFieldDecl");
4338 
4339   if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4340     return true;
4341 
4342   if (Member->isInvalidDecl())
4343     return true;
4344 
4345   MultiExprArg Args;
4346   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4347     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4348   } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4349     Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4350   } else {
4351     // Template instantiation doesn't reconstruct ParenListExprs for us.
4352     Args = Init;
4353   }
4354 
4355   SourceRange InitRange = Init->getSourceRange();
4356 
4357   if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4358     // Can't check initialization for a member of dependent type or when
4359     // any of the arguments are type-dependent expressions.
4360     DiscardCleanupsInEvaluationContext();
4361   } else {
4362     bool InitList = false;
4363     if (isa<InitListExpr>(Init)) {
4364       InitList = true;
4365       Args = Init;
4366     }
4367 
4368     // Initialize the member.
4369     InitializedEntity MemberEntity =
4370       DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4371                    : InitializedEntity::InitializeMember(IndirectMember,
4372                                                          nullptr);
4373     InitializationKind Kind =
4374         InitList ? InitializationKind::CreateDirectList(
4375                        IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4376                  : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4377                                                     InitRange.getEnd());
4378 
4379     InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4380     ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4381                                             nullptr);
4382     if (!MemberInit.isInvalid()) {
4383       // C++11 [class.base.init]p7:
4384       //   The initialization of each base and member constitutes a
4385       //   full-expression.
4386       MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4387                                        /*DiscardedValue*/ false);
4388     }
4389 
4390     if (MemberInit.isInvalid()) {
4391       // Args were sensible expressions but we couldn't initialize the member
4392       // from them. Preserve them in a RecoveryExpr instead.
4393       Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4394                                 Member->getType())
4395                  .get();
4396       if (!Init)
4397         return true;
4398     } else {
4399       Init = MemberInit.get();
4400     }
4401   }
4402 
4403   if (DirectMember) {
4404     return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4405                                             InitRange.getBegin(), Init,
4406                                             InitRange.getEnd());
4407   } else {
4408     return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4409                                             InitRange.getBegin(), Init,
4410                                             InitRange.getEnd());
4411   }
4412 }
4413 
4414 MemInitResult
4415 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4416                                  CXXRecordDecl *ClassDecl) {
4417   SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4418   if (!LangOpts.CPlusPlus11)
4419     return Diag(NameLoc, diag::err_delegating_ctor)
4420       << TInfo->getTypeLoc().getLocalSourceRange();
4421   Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4422 
4423   bool InitList = true;
4424   MultiExprArg Args = Init;
4425   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4426     InitList = false;
4427     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4428   }
4429 
4430   SourceRange InitRange = Init->getSourceRange();
4431   // Initialize the object.
4432   InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4433                                      QualType(ClassDecl->getTypeForDecl(), 0));
4434   InitializationKind Kind =
4435       InitList ? InitializationKind::CreateDirectList(
4436                      NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4437                : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4438                                                   InitRange.getEnd());
4439   InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4440   ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4441                                               Args, nullptr);
4442   if (!DelegationInit.isInvalid()) {
4443     assert((DelegationInit.get()->containsErrors() ||
4444             cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4445            "Delegating constructor with no target?");
4446 
4447     // C++11 [class.base.init]p7:
4448     //   The initialization of each base and member constitutes a
4449     //   full-expression.
4450     DelegationInit = ActOnFinishFullExpr(
4451         DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4452   }
4453 
4454   if (DelegationInit.isInvalid()) {
4455     DelegationInit =
4456         CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4457                            QualType(ClassDecl->getTypeForDecl(), 0));
4458     if (DelegationInit.isInvalid())
4459       return true;
4460   } else {
4461     // If we are in a dependent context, template instantiation will
4462     // perform this type-checking again. Just save the arguments that we
4463     // received in a ParenListExpr.
4464     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4465     // of the information that we have about the base
4466     // initializer. However, deconstructing the ASTs is a dicey process,
4467     // and this approach is far more likely to get the corner cases right.
4468     if (CurContext->isDependentContext())
4469       DelegationInit = Init;
4470   }
4471 
4472   return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4473                                           DelegationInit.getAs<Expr>(),
4474                                           InitRange.getEnd());
4475 }
4476 
4477 MemInitResult
4478 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4479                            Expr *Init, CXXRecordDecl *ClassDecl,
4480                            SourceLocation EllipsisLoc) {
4481   SourceLocation BaseLoc
4482     = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4483 
4484   if (!BaseType->isDependentType() && !BaseType->isRecordType())
4485     return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4486              << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4487 
4488   // C++ [class.base.init]p2:
4489   //   [...] Unless the mem-initializer-id names a nonstatic data
4490   //   member of the constructor's class or a direct or virtual base
4491   //   of that class, the mem-initializer is ill-formed. A
4492   //   mem-initializer-list can initialize a base class using any
4493   //   name that denotes that base class type.
4494 
4495   // We can store the initializers in "as-written" form and delay analysis until
4496   // instantiation if the constructor is dependent. But not for dependent
4497   // (broken) code in a non-template! SetCtorInitializers does not expect this.
4498   bool Dependent = CurContext->isDependentContext() &&
4499                    (BaseType->isDependentType() || Init->isTypeDependent());
4500 
4501   SourceRange InitRange = Init->getSourceRange();
4502   if (EllipsisLoc.isValid()) {
4503     // This is a pack expansion.
4504     if (!BaseType->containsUnexpandedParameterPack())  {
4505       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4506         << SourceRange(BaseLoc, InitRange.getEnd());
4507 
4508       EllipsisLoc = SourceLocation();
4509     }
4510   } else {
4511     // Check for any unexpanded parameter packs.
4512     if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4513       return true;
4514 
4515     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4516       return true;
4517   }
4518 
4519   // Check for direct and virtual base classes.
4520   const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4521   const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4522   if (!Dependent) {
4523     if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4524                                        BaseType))
4525       return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4526 
4527     FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4528                         VirtualBaseSpec);
4529 
4530     // C++ [base.class.init]p2:
4531     // Unless the mem-initializer-id names a nonstatic data member of the
4532     // constructor's class or a direct or virtual base of that class, the
4533     // mem-initializer is ill-formed.
4534     if (!DirectBaseSpec && !VirtualBaseSpec) {
4535       // If the class has any dependent bases, then it's possible that
4536       // one of those types will resolve to the same type as
4537       // BaseType. Therefore, just treat this as a dependent base
4538       // class initialization.  FIXME: Should we try to check the
4539       // initialization anyway? It seems odd.
4540       if (ClassDecl->hasAnyDependentBases())
4541         Dependent = true;
4542       else
4543         return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4544           << BaseType << Context.getTypeDeclType(ClassDecl)
4545           << BaseTInfo->getTypeLoc().getLocalSourceRange();
4546     }
4547   }
4548 
4549   if (Dependent) {
4550     DiscardCleanupsInEvaluationContext();
4551 
4552     return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4553                                             /*IsVirtual=*/false,
4554                                             InitRange.getBegin(), Init,
4555                                             InitRange.getEnd(), EllipsisLoc);
4556   }
4557 
4558   // C++ [base.class.init]p2:
4559   //   If a mem-initializer-id is ambiguous because it designates both
4560   //   a direct non-virtual base class and an inherited virtual base
4561   //   class, the mem-initializer is ill-formed.
4562   if (DirectBaseSpec && VirtualBaseSpec)
4563     return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4564       << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4565 
4566   const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4567   if (!BaseSpec)
4568     BaseSpec = VirtualBaseSpec;
4569 
4570   // Initialize the base.
4571   bool InitList = true;
4572   MultiExprArg Args = Init;
4573   if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4574     InitList = false;
4575     Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4576   }
4577 
4578   InitializedEntity BaseEntity =
4579     InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4580   InitializationKind Kind =
4581       InitList ? InitializationKind::CreateDirectList(BaseLoc)
4582                : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4583                                                   InitRange.getEnd());
4584   InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4585   ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4586   if (!BaseInit.isInvalid()) {
4587     // C++11 [class.base.init]p7:
4588     //   The initialization of each base and member constitutes a
4589     //   full-expression.
4590     BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4591                                    /*DiscardedValue*/ false);
4592   }
4593 
4594   if (BaseInit.isInvalid()) {
4595     BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4596                                   Args, BaseType);
4597     if (BaseInit.isInvalid())
4598       return true;
4599   } else {
4600     // If we are in a dependent context, template instantiation will
4601     // perform this type-checking again. Just save the arguments that we
4602     // received in a ParenListExpr.
4603     // FIXME: This isn't quite ideal, since our ASTs don't capture all
4604     // of the information that we have about the base
4605     // initializer. However, deconstructing the ASTs is a dicey process,
4606     // and this approach is far more likely to get the corner cases right.
4607     if (CurContext->isDependentContext())
4608       BaseInit = Init;
4609   }
4610 
4611   return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4612                                           BaseSpec->isVirtual(),
4613                                           InitRange.getBegin(),
4614                                           BaseInit.getAs<Expr>(),
4615                                           InitRange.getEnd(), EllipsisLoc);
4616 }
4617 
4618 // Create a static_cast\<T&&>(expr).
4619 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4620   if (T.isNull()) T = E->getType();
4621   QualType TargetType = SemaRef.BuildReferenceType(
4622       T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4623   SourceLocation ExprLoc = E->getBeginLoc();
4624   TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4625       TargetType, ExprLoc);
4626 
4627   return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4628                                    SourceRange(ExprLoc, ExprLoc),
4629                                    E->getSourceRange()).get();
4630 }
4631 
4632 /// ImplicitInitializerKind - How an implicit base or member initializer should
4633 /// initialize its base or member.
4634 enum ImplicitInitializerKind {
4635   IIK_Default,
4636   IIK_Copy,
4637   IIK_Move,
4638   IIK_Inherit
4639 };
4640 
4641 static bool
4642 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4643                              ImplicitInitializerKind ImplicitInitKind,
4644                              CXXBaseSpecifier *BaseSpec,
4645                              bool IsInheritedVirtualBase,
4646                              CXXCtorInitializer *&CXXBaseInit) {
4647   InitializedEntity InitEntity
4648     = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4649                                         IsInheritedVirtualBase);
4650 
4651   ExprResult BaseInit;
4652 
4653   switch (ImplicitInitKind) {
4654   case IIK_Inherit:
4655   case IIK_Default: {
4656     InitializationKind InitKind
4657       = InitializationKind::CreateDefault(Constructor->getLocation());
4658     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4659     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4660     break;
4661   }
4662 
4663   case IIK_Move:
4664   case IIK_Copy: {
4665     bool Moving = ImplicitInitKind == IIK_Move;
4666     ParmVarDecl *Param = Constructor->getParamDecl(0);
4667     QualType ParamType = Param->getType().getNonReferenceType();
4668 
4669     Expr *CopyCtorArg =
4670       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4671                           SourceLocation(), Param, false,
4672                           Constructor->getLocation(), ParamType,
4673                           VK_LValue, nullptr);
4674 
4675     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4676 
4677     // Cast to the base class to avoid ambiguities.
4678     QualType ArgTy =
4679       SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4680                                        ParamType.getQualifiers());
4681 
4682     if (Moving) {
4683       CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4684     }
4685 
4686     CXXCastPath BasePath;
4687     BasePath.push_back(BaseSpec);
4688     CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4689                                             CK_UncheckedDerivedToBase,
4690                                             Moving ? VK_XValue : VK_LValue,
4691                                             &BasePath).get();
4692 
4693     InitializationKind InitKind
4694       = InitializationKind::CreateDirect(Constructor->getLocation(),
4695                                          SourceLocation(), SourceLocation());
4696     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4697     BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4698     break;
4699   }
4700   }
4701 
4702   BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4703   if (BaseInit.isInvalid())
4704     return true;
4705 
4706   CXXBaseInit =
4707     new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4708                SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4709                                                         SourceLocation()),
4710                                              BaseSpec->isVirtual(),
4711                                              SourceLocation(),
4712                                              BaseInit.getAs<Expr>(),
4713                                              SourceLocation(),
4714                                              SourceLocation());
4715 
4716   return false;
4717 }
4718 
4719 static bool RefersToRValueRef(Expr *MemRef) {
4720   ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4721   return Referenced->getType()->isRValueReferenceType();
4722 }
4723 
4724 static bool
4725 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4726                                ImplicitInitializerKind ImplicitInitKind,
4727                                FieldDecl *Field, IndirectFieldDecl *Indirect,
4728                                CXXCtorInitializer *&CXXMemberInit) {
4729   if (Field->isInvalidDecl())
4730     return true;
4731 
4732   SourceLocation Loc = Constructor->getLocation();
4733 
4734   if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4735     bool Moving = ImplicitInitKind == IIK_Move;
4736     ParmVarDecl *Param = Constructor->getParamDecl(0);
4737     QualType ParamType = Param->getType().getNonReferenceType();
4738 
4739     // Suppress copying zero-width bitfields.
4740     if (Field->isZeroLengthBitField(SemaRef.Context))
4741       return false;
4742 
4743     Expr *MemberExprBase =
4744       DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4745                           SourceLocation(), Param, false,
4746                           Loc, ParamType, VK_LValue, nullptr);
4747 
4748     SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4749 
4750     if (Moving) {
4751       MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4752     }
4753 
4754     // Build a reference to this field within the parameter.
4755     CXXScopeSpec SS;
4756     LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4757                               Sema::LookupMemberName);
4758     MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4759                                   : cast<ValueDecl>(Field), AS_public);
4760     MemberLookup.resolveKind();
4761     ExprResult CtorArg
4762       = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4763                                          ParamType, Loc,
4764                                          /*IsArrow=*/false,
4765                                          SS,
4766                                          /*TemplateKWLoc=*/SourceLocation(),
4767                                          /*FirstQualifierInScope=*/nullptr,
4768                                          MemberLookup,
4769                                          /*TemplateArgs=*/nullptr,
4770                                          /*S*/nullptr);
4771     if (CtorArg.isInvalid())
4772       return true;
4773 
4774     // C++11 [class.copy]p15:
4775     //   - if a member m has rvalue reference type T&&, it is direct-initialized
4776     //     with static_cast<T&&>(x.m);
4777     if (RefersToRValueRef(CtorArg.get())) {
4778       CtorArg = CastForMoving(SemaRef, CtorArg.get());
4779     }
4780 
4781     InitializedEntity Entity =
4782         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4783                                                        /*Implicit*/ true)
4784                  : InitializedEntity::InitializeMember(Field, nullptr,
4785                                                        /*Implicit*/ true);
4786 
4787     // Direct-initialize to use the copy constructor.
4788     InitializationKind InitKind =
4789       InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4790 
4791     Expr *CtorArgE = CtorArg.getAs<Expr>();
4792     InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4793     ExprResult MemberInit =
4794         InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4795     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4796     if (MemberInit.isInvalid())
4797       return true;
4798 
4799     if (Indirect)
4800       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4801           SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4802     else
4803       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4804           SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4805     return false;
4806   }
4807 
4808   assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4809          "Unhandled implicit init kind!");
4810 
4811   QualType FieldBaseElementType =
4812     SemaRef.Context.getBaseElementType(Field->getType());
4813 
4814   if (FieldBaseElementType->isRecordType()) {
4815     InitializedEntity InitEntity =
4816         Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4817                                                        /*Implicit*/ true)
4818                  : InitializedEntity::InitializeMember(Field, nullptr,
4819                                                        /*Implicit*/ true);
4820     InitializationKind InitKind =
4821       InitializationKind::CreateDefault(Loc);
4822 
4823     InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4824     ExprResult MemberInit =
4825       InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4826 
4827     MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4828     if (MemberInit.isInvalid())
4829       return true;
4830 
4831     if (Indirect)
4832       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4833                                                                Indirect, Loc,
4834                                                                Loc,
4835                                                                MemberInit.get(),
4836                                                                Loc);
4837     else
4838       CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4839                                                                Field, Loc, Loc,
4840                                                                MemberInit.get(),
4841                                                                Loc);
4842     return false;
4843   }
4844 
4845   if (!Field->getParent()->isUnion()) {
4846     if (FieldBaseElementType->isReferenceType()) {
4847       SemaRef.Diag(Constructor->getLocation(),
4848                    diag::err_uninitialized_member_in_ctor)
4849       << (int)Constructor->isImplicit()
4850       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4851       << 0 << Field->getDeclName();
4852       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4853       return true;
4854     }
4855 
4856     if (FieldBaseElementType.isConstQualified()) {
4857       SemaRef.Diag(Constructor->getLocation(),
4858                    diag::err_uninitialized_member_in_ctor)
4859       << (int)Constructor->isImplicit()
4860       << SemaRef.Context.getTagDeclType(Constructor->getParent())
4861       << 1 << Field->getDeclName();
4862       SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4863       return true;
4864     }
4865   }
4866 
4867   if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4868     // ARC and Weak:
4869     //   Default-initialize Objective-C pointers to NULL.
4870     CXXMemberInit
4871       = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4872                                                  Loc, Loc,
4873                  new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4874                                                  Loc);
4875     return false;
4876   }
4877 
4878   // Nothing to initialize.
4879   CXXMemberInit = nullptr;
4880   return false;
4881 }
4882 
4883 namespace {
4884 struct BaseAndFieldInfo {
4885   Sema &S;
4886   CXXConstructorDecl *Ctor;
4887   bool AnyErrorsInInits;
4888   ImplicitInitializerKind IIK;
4889   llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4890   SmallVector<CXXCtorInitializer*, 8> AllToInit;
4891   llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4892 
4893   BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4894     : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4895     bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4896     if (Ctor->getInheritedConstructor())
4897       IIK = IIK_Inherit;
4898     else if (Generated && Ctor->isCopyConstructor())
4899       IIK = IIK_Copy;
4900     else if (Generated && Ctor->isMoveConstructor())
4901       IIK = IIK_Move;
4902     else
4903       IIK = IIK_Default;
4904   }
4905 
4906   bool isImplicitCopyOrMove() const {
4907     switch (IIK) {
4908     case IIK_Copy:
4909     case IIK_Move:
4910       return true;
4911 
4912     case IIK_Default:
4913     case IIK_Inherit:
4914       return false;
4915     }
4916 
4917     llvm_unreachable("Invalid ImplicitInitializerKind!");
4918   }
4919 
4920   bool addFieldInitializer(CXXCtorInitializer *Init) {
4921     AllToInit.push_back(Init);
4922 
4923     // Check whether this initializer makes the field "used".
4924     if (Init->getInit()->HasSideEffects(S.Context))
4925       S.UnusedPrivateFields.remove(Init->getAnyMember());
4926 
4927     return false;
4928   }
4929 
4930   bool isInactiveUnionMember(FieldDecl *Field) {
4931     RecordDecl *Record = Field->getParent();
4932     if (!Record->isUnion())
4933       return false;
4934 
4935     if (FieldDecl *Active =
4936             ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4937       return Active != Field->getCanonicalDecl();
4938 
4939     // In an implicit copy or move constructor, ignore any in-class initializer.
4940     if (isImplicitCopyOrMove())
4941       return true;
4942 
4943     // If there's no explicit initialization, the field is active only if it
4944     // has an in-class initializer...
4945     if (Field->hasInClassInitializer())
4946       return false;
4947     // ... or it's an anonymous struct or union whose class has an in-class
4948     // initializer.
4949     if (!Field->isAnonymousStructOrUnion())
4950       return true;
4951     CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4952     return !FieldRD->hasInClassInitializer();
4953   }
4954 
4955   /// Determine whether the given field is, or is within, a union member
4956   /// that is inactive (because there was an initializer given for a different
4957   /// member of the union, or because the union was not initialized at all).
4958   bool isWithinInactiveUnionMember(FieldDecl *Field,
4959                                    IndirectFieldDecl *Indirect) {
4960     if (!Indirect)
4961       return isInactiveUnionMember(Field);
4962 
4963     for (auto *C : Indirect->chain()) {
4964       FieldDecl *Field = dyn_cast<FieldDecl>(C);
4965       if (Field && isInactiveUnionMember(Field))
4966         return true;
4967     }
4968     return false;
4969   }
4970 };
4971 }
4972 
4973 /// Determine whether the given type is an incomplete or zero-lenfgth
4974 /// array type.
4975 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4976   if (T->isIncompleteArrayType())
4977     return true;
4978 
4979   while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4980     if (!ArrayT->getSize())
4981       return true;
4982 
4983     T = ArrayT->getElementType();
4984   }
4985 
4986   return false;
4987 }
4988 
4989 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4990                                     FieldDecl *Field,
4991                                     IndirectFieldDecl *Indirect = nullptr) {
4992   if (Field->isInvalidDecl())
4993     return false;
4994 
4995   // Overwhelmingly common case: we have a direct initializer for this field.
4996   if (CXXCtorInitializer *Init =
4997           Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4998     return Info.addFieldInitializer(Init);
4999 
5000   // C++11 [class.base.init]p8:
5001   //   if the entity is a non-static data member that has a
5002   //   brace-or-equal-initializer and either
5003   //   -- the constructor's class is a union and no other variant member of that
5004   //      union is designated by a mem-initializer-id or
5005   //   -- the constructor's class is not a union, and, if the entity is a member
5006   //      of an anonymous union, no other member of that union is designated by
5007   //      a mem-initializer-id,
5008   //   the entity is initialized as specified in [dcl.init].
5009   //
5010   // We also apply the same rules to handle anonymous structs within anonymous
5011   // unions.
5012   if (Info.isWithinInactiveUnionMember(Field, Indirect))
5013     return false;
5014 
5015   if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5016     ExprResult DIE =
5017         SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5018     if (DIE.isInvalid())
5019       return true;
5020 
5021     auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5022     SemaRef.checkInitializerLifetime(Entity, DIE.get());
5023 
5024     CXXCtorInitializer *Init;
5025     if (Indirect)
5026       Init = new (SemaRef.Context)
5027           CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5028                              SourceLocation(), DIE.get(), SourceLocation());
5029     else
5030       Init = new (SemaRef.Context)
5031           CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5032                              SourceLocation(), DIE.get(), SourceLocation());
5033     return Info.addFieldInitializer(Init);
5034   }
5035 
5036   // Don't initialize incomplete or zero-length arrays.
5037   if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5038     return false;
5039 
5040   // Don't try to build an implicit initializer if there were semantic
5041   // errors in any of the initializers (and therefore we might be
5042   // missing some that the user actually wrote).
5043   if (Info.AnyErrorsInInits)
5044     return false;
5045 
5046   CXXCtorInitializer *Init = nullptr;
5047   if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5048                                      Indirect, Init))
5049     return true;
5050 
5051   if (!Init)
5052     return false;
5053 
5054   return Info.addFieldInitializer(Init);
5055 }
5056 
5057 bool
5058 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5059                                CXXCtorInitializer *Initializer) {
5060   assert(Initializer->isDelegatingInitializer());
5061   Constructor->setNumCtorInitializers(1);
5062   CXXCtorInitializer **initializer =
5063     new (Context) CXXCtorInitializer*[1];
5064   memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5065   Constructor->setCtorInitializers(initializer);
5066 
5067   if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5068     MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5069     DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5070   }
5071 
5072   DelegatingCtorDecls.push_back(Constructor);
5073 
5074   DiagnoseUninitializedFields(*this, Constructor);
5075 
5076   return false;
5077 }
5078 
5079 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5080                                ArrayRef<CXXCtorInitializer *> Initializers) {
5081   if (Constructor->isDependentContext()) {
5082     // Just store the initializers as written, they will be checked during
5083     // instantiation.
5084     if (!Initializers.empty()) {
5085       Constructor->setNumCtorInitializers(Initializers.size());
5086       CXXCtorInitializer **baseOrMemberInitializers =
5087         new (Context) CXXCtorInitializer*[Initializers.size()];
5088       memcpy(baseOrMemberInitializers, Initializers.data(),
5089              Initializers.size() * sizeof(CXXCtorInitializer*));
5090       Constructor->setCtorInitializers(baseOrMemberInitializers);
5091     }
5092 
5093     // Let template instantiation know whether we had errors.
5094     if (AnyErrors)
5095       Constructor->setInvalidDecl();
5096 
5097     return false;
5098   }
5099 
5100   BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5101 
5102   // We need to build the initializer AST according to order of construction
5103   // and not what user specified in the Initializers list.
5104   CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5105   if (!ClassDecl)
5106     return true;
5107 
5108   bool HadError = false;
5109 
5110   for (unsigned i = 0; i < Initializers.size(); i++) {
5111     CXXCtorInitializer *Member = Initializers[i];
5112 
5113     if (Member->isBaseInitializer())
5114       Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5115     else {
5116       Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5117 
5118       if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5119         for (auto *C : F->chain()) {
5120           FieldDecl *FD = dyn_cast<FieldDecl>(C);
5121           if (FD && FD->getParent()->isUnion())
5122             Info.ActiveUnionMember.insert(std::make_pair(
5123                 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5124         }
5125       } else if (FieldDecl *FD = Member->getMember()) {
5126         if (FD->getParent()->isUnion())
5127           Info.ActiveUnionMember.insert(std::make_pair(
5128               FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5129       }
5130     }
5131   }
5132 
5133   // Keep track of the direct virtual bases.
5134   llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5135   for (auto &I : ClassDecl->bases()) {
5136     if (I.isVirtual())
5137       DirectVBases.insert(&I);
5138   }
5139 
5140   // Push virtual bases before others.
5141   for (auto &VBase : ClassDecl->vbases()) {
5142     if (CXXCtorInitializer *Value
5143         = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5144       // [class.base.init]p7, per DR257:
5145       //   A mem-initializer where the mem-initializer-id names a virtual base
5146       //   class is ignored during execution of a constructor of any class that
5147       //   is not the most derived class.
5148       if (ClassDecl->isAbstract()) {
5149         // FIXME: Provide a fixit to remove the base specifier. This requires
5150         // tracking the location of the associated comma for a base specifier.
5151         Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5152           << VBase.getType() << ClassDecl;
5153         DiagnoseAbstractType(ClassDecl);
5154       }
5155 
5156       Info.AllToInit.push_back(Value);
5157     } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5158       // [class.base.init]p8, per DR257:
5159       //   If a given [...] base class is not named by a mem-initializer-id
5160       //   [...] and the entity is not a virtual base class of an abstract
5161       //   class, then [...] the entity is default-initialized.
5162       bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5163       CXXCtorInitializer *CXXBaseInit;
5164       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5165                                        &VBase, IsInheritedVirtualBase,
5166                                        CXXBaseInit)) {
5167         HadError = true;
5168         continue;
5169       }
5170 
5171       Info.AllToInit.push_back(CXXBaseInit);
5172     }
5173   }
5174 
5175   // Non-virtual bases.
5176   for (auto &Base : ClassDecl->bases()) {
5177     // Virtuals are in the virtual base list and already constructed.
5178     if (Base.isVirtual())
5179       continue;
5180 
5181     if (CXXCtorInitializer *Value
5182           = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5183       Info.AllToInit.push_back(Value);
5184     } else if (!AnyErrors) {
5185       CXXCtorInitializer *CXXBaseInit;
5186       if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5187                                        &Base, /*IsInheritedVirtualBase=*/false,
5188                                        CXXBaseInit)) {
5189         HadError = true;
5190         continue;
5191       }
5192 
5193       Info.AllToInit.push_back(CXXBaseInit);
5194     }
5195   }
5196 
5197   // Fields.
5198   for (auto *Mem : ClassDecl->decls()) {
5199     if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5200       // C++ [class.bit]p2:
5201       //   A declaration for a bit-field that omits the identifier declares an
5202       //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
5203       //   initialized.
5204       if (F->isUnnamedBitfield())
5205         continue;
5206 
5207       // If we're not generating the implicit copy/move constructor, then we'll
5208       // handle anonymous struct/union fields based on their individual
5209       // indirect fields.
5210       if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5211         continue;
5212 
5213       if (CollectFieldInitializer(*this, Info, F))
5214         HadError = true;
5215       continue;
5216     }
5217 
5218     // Beyond this point, we only consider default initialization.
5219     if (Info.isImplicitCopyOrMove())
5220       continue;
5221 
5222     if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5223       if (F->getType()->isIncompleteArrayType()) {
5224         assert(ClassDecl->hasFlexibleArrayMember() &&
5225                "Incomplete array type is not valid");
5226         continue;
5227       }
5228 
5229       // Initialize each field of an anonymous struct individually.
5230       if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5231         HadError = true;
5232 
5233       continue;
5234     }
5235   }
5236 
5237   unsigned NumInitializers = Info.AllToInit.size();
5238   if (NumInitializers > 0) {
5239     Constructor->setNumCtorInitializers(NumInitializers);
5240     CXXCtorInitializer **baseOrMemberInitializers =
5241       new (Context) CXXCtorInitializer*[NumInitializers];
5242     memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5243            NumInitializers * sizeof(CXXCtorInitializer*));
5244     Constructor->setCtorInitializers(baseOrMemberInitializers);
5245 
5246     // Constructors implicitly reference the base and member
5247     // destructors.
5248     MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5249                                            Constructor->getParent());
5250   }
5251 
5252   return HadError;
5253 }
5254 
5255 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5256   if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5257     const RecordDecl *RD = RT->getDecl();
5258     if (RD->isAnonymousStructOrUnion()) {
5259       for (auto *Field : RD->fields())
5260         PopulateKeysForFields(Field, IdealInits);
5261       return;
5262     }
5263   }
5264   IdealInits.push_back(Field->getCanonicalDecl());
5265 }
5266 
5267 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5268   return Context.getCanonicalType(BaseType).getTypePtr();
5269 }
5270 
5271 static const void *GetKeyForMember(ASTContext &Context,
5272                                    CXXCtorInitializer *Member) {
5273   if (!Member->isAnyMemberInitializer())
5274     return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5275 
5276   return Member->getAnyMember()->getCanonicalDecl();
5277 }
5278 
5279 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5280                                  const CXXCtorInitializer *Previous,
5281                                  const CXXCtorInitializer *Current) {
5282   if (Previous->isAnyMemberInitializer())
5283     Diag << 0 << Previous->getAnyMember();
5284   else
5285     Diag << 1 << Previous->getTypeSourceInfo()->getType();
5286 
5287   if (Current->isAnyMemberInitializer())
5288     Diag << 0 << Current->getAnyMember();
5289   else
5290     Diag << 1 << Current->getTypeSourceInfo()->getType();
5291 }
5292 
5293 static void DiagnoseBaseOrMemInitializerOrder(
5294     Sema &SemaRef, const CXXConstructorDecl *Constructor,
5295     ArrayRef<CXXCtorInitializer *> Inits) {
5296   if (Constructor->getDeclContext()->isDependentContext())
5297     return;
5298 
5299   // Don't check initializers order unless the warning is enabled at the
5300   // location of at least one initializer.
5301   bool ShouldCheckOrder = false;
5302   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5303     CXXCtorInitializer *Init = Inits[InitIndex];
5304     if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5305                                  Init->getSourceLocation())) {
5306       ShouldCheckOrder = true;
5307       break;
5308     }
5309   }
5310   if (!ShouldCheckOrder)
5311     return;
5312 
5313   // Build the list of bases and members in the order that they'll
5314   // actually be initialized.  The explicit initializers should be in
5315   // this same order but may be missing things.
5316   SmallVector<const void*, 32> IdealInitKeys;
5317 
5318   const CXXRecordDecl *ClassDecl = Constructor->getParent();
5319 
5320   // 1. Virtual bases.
5321   for (const auto &VBase : ClassDecl->vbases())
5322     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5323 
5324   // 2. Non-virtual bases.
5325   for (const auto &Base : ClassDecl->bases()) {
5326     if (Base.isVirtual())
5327       continue;
5328     IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5329   }
5330 
5331   // 3. Direct fields.
5332   for (auto *Field : ClassDecl->fields()) {
5333     if (Field->isUnnamedBitfield())
5334       continue;
5335 
5336     PopulateKeysForFields(Field, IdealInitKeys);
5337   }
5338 
5339   unsigned NumIdealInits = IdealInitKeys.size();
5340   unsigned IdealIndex = 0;
5341 
5342   // Track initializers that are in an incorrect order for either a warning or
5343   // note if multiple ones occur.
5344   SmallVector<unsigned> WarnIndexes;
5345   // Correlates the index of an initializer in the init-list to the index of
5346   // the field/base in the class.
5347   SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5348 
5349   for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5350     const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5351 
5352     // Scan forward to try to find this initializer in the idealized
5353     // initializers list.
5354     for (; IdealIndex != NumIdealInits; ++IdealIndex)
5355       if (InitKey == IdealInitKeys[IdealIndex])
5356         break;
5357 
5358     // If we didn't find this initializer, it must be because we
5359     // scanned past it on a previous iteration.  That can only
5360     // happen if we're out of order;  emit a warning.
5361     if (IdealIndex == NumIdealInits && InitIndex) {
5362       WarnIndexes.push_back(InitIndex);
5363 
5364       // Move back to the initializer's location in the ideal list.
5365       for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5366         if (InitKey == IdealInitKeys[IdealIndex])
5367           break;
5368 
5369       assert(IdealIndex < NumIdealInits &&
5370              "initializer not found in initializer list");
5371     }
5372     CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5373   }
5374 
5375   if (WarnIndexes.empty())
5376     return;
5377 
5378   // Sort based on the ideal order, first in the pair.
5379   llvm::sort(CorrelatedInitOrder,
5380              [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; });
5381 
5382   // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5383   // emit the diagnostic before we can try adding notes.
5384   {
5385     Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5386         Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5387         WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5388                                 : diag::warn_some_initializers_out_of_order);
5389 
5390     for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5391       if (CorrelatedInitOrder[I].second == I)
5392         continue;
5393       // Ideally we would be using InsertFromRange here, but clang doesn't
5394       // appear to handle InsertFromRange correctly when the source range is
5395       // modified by another fix-it.
5396       D << FixItHint::CreateReplacement(
5397           Inits[I]->getSourceRange(),
5398           Lexer::getSourceText(
5399               CharSourceRange::getTokenRange(
5400                   Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5401               SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5402     }
5403 
5404     // If there is only 1 item out of order, the warning expects the name and
5405     // type of each being added to it.
5406     if (WarnIndexes.size() == 1) {
5407       AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5408                            Inits[WarnIndexes.front()]);
5409       return;
5410     }
5411   }
5412   // More than 1 item to warn, create notes letting the user know which ones
5413   // are bad.
5414   for (unsigned WarnIndex : WarnIndexes) {
5415     const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5416     auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5417                           diag::note_initializer_out_of_order);
5418     AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5419     D << PrevInit->getSourceRange();
5420   }
5421 }
5422 
5423 namespace {
5424 bool CheckRedundantInit(Sema &S,
5425                         CXXCtorInitializer *Init,
5426                         CXXCtorInitializer *&PrevInit) {
5427   if (!PrevInit) {
5428     PrevInit = Init;
5429     return false;
5430   }
5431 
5432   if (FieldDecl *Field = Init->getAnyMember())
5433     S.Diag(Init->getSourceLocation(),
5434            diag::err_multiple_mem_initialization)
5435       << Field->getDeclName()
5436       << Init->getSourceRange();
5437   else {
5438     const Type *BaseClass = Init->getBaseClass();
5439     assert(BaseClass && "neither field nor base");
5440     S.Diag(Init->getSourceLocation(),
5441            diag::err_multiple_base_initialization)
5442       << QualType(BaseClass, 0)
5443       << Init->getSourceRange();
5444   }
5445   S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5446     << 0 << PrevInit->getSourceRange();
5447 
5448   return true;
5449 }
5450 
5451 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5452 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5453 
5454 bool CheckRedundantUnionInit(Sema &S,
5455                              CXXCtorInitializer *Init,
5456                              RedundantUnionMap &Unions) {
5457   FieldDecl *Field = Init->getAnyMember();
5458   RecordDecl *Parent = Field->getParent();
5459   NamedDecl *Child = Field;
5460 
5461   while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5462     if (Parent->isUnion()) {
5463       UnionEntry &En = Unions[Parent];
5464       if (En.first && En.first != Child) {
5465         S.Diag(Init->getSourceLocation(),
5466                diag::err_multiple_mem_union_initialization)
5467           << Field->getDeclName()
5468           << Init->getSourceRange();
5469         S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5470           << 0 << En.second->getSourceRange();
5471         return true;
5472       }
5473       if (!En.first) {
5474         En.first = Child;
5475         En.second = Init;
5476       }
5477       if (!Parent->isAnonymousStructOrUnion())
5478         return false;
5479     }
5480 
5481     Child = Parent;
5482     Parent = cast<RecordDecl>(Parent->getDeclContext());
5483   }
5484 
5485   return false;
5486 }
5487 } // namespace
5488 
5489 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5490 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5491                                 SourceLocation ColonLoc,
5492                                 ArrayRef<CXXCtorInitializer*> MemInits,
5493                                 bool AnyErrors) {
5494   if (!ConstructorDecl)
5495     return;
5496 
5497   AdjustDeclIfTemplate(ConstructorDecl);
5498 
5499   CXXConstructorDecl *Constructor
5500     = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5501 
5502   if (!Constructor) {
5503     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5504     return;
5505   }
5506 
5507   // Mapping for the duplicate initializers check.
5508   // For member initializers, this is keyed with a FieldDecl*.
5509   // For base initializers, this is keyed with a Type*.
5510   llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5511 
5512   // Mapping for the inconsistent anonymous-union initializers check.
5513   RedundantUnionMap MemberUnions;
5514 
5515   bool HadError = false;
5516   for (unsigned i = 0; i < MemInits.size(); i++) {
5517     CXXCtorInitializer *Init = MemInits[i];
5518 
5519     // Set the source order index.
5520     Init->setSourceOrder(i);
5521 
5522     if (Init->isAnyMemberInitializer()) {
5523       const void *Key = GetKeyForMember(Context, Init);
5524       if (CheckRedundantInit(*this, Init, Members[Key]) ||
5525           CheckRedundantUnionInit(*this, Init, MemberUnions))
5526         HadError = true;
5527     } else if (Init->isBaseInitializer()) {
5528       const void *Key = GetKeyForMember(Context, Init);
5529       if (CheckRedundantInit(*this, Init, Members[Key]))
5530         HadError = true;
5531     } else {
5532       assert(Init->isDelegatingInitializer());
5533       // This must be the only initializer
5534       if (MemInits.size() != 1) {
5535         Diag(Init->getSourceLocation(),
5536              diag::err_delegating_initializer_alone)
5537           << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5538         // We will treat this as being the only initializer.
5539       }
5540       SetDelegatingInitializer(Constructor, MemInits[i]);
5541       // Return immediately as the initializer is set.
5542       return;
5543     }
5544   }
5545 
5546   if (HadError)
5547     return;
5548 
5549   DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5550 
5551   SetCtorInitializers(Constructor, AnyErrors, MemInits);
5552 
5553   DiagnoseUninitializedFields(*this, Constructor);
5554 }
5555 
5556 void
5557 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5558                                              CXXRecordDecl *ClassDecl) {
5559   // Ignore dependent contexts. Also ignore unions, since their members never
5560   // have destructors implicitly called.
5561   if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5562     return;
5563 
5564   // FIXME: all the access-control diagnostics are positioned on the
5565   // field/base declaration.  That's probably good; that said, the
5566   // user might reasonably want to know why the destructor is being
5567   // emitted, and we currently don't say.
5568 
5569   // Non-static data members.
5570   for (auto *Field : ClassDecl->fields()) {
5571     if (Field->isInvalidDecl())
5572       continue;
5573 
5574     // Don't destroy incomplete or zero-length arrays.
5575     if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5576       continue;
5577 
5578     QualType FieldType = Context.getBaseElementType(Field->getType());
5579 
5580     const RecordType* RT = FieldType->getAs<RecordType>();
5581     if (!RT)
5582       continue;
5583 
5584     CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5585     if (FieldClassDecl->isInvalidDecl())
5586       continue;
5587     if (FieldClassDecl->hasIrrelevantDestructor())
5588       continue;
5589     // The destructor for an implicit anonymous union member is never invoked.
5590     if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5591       continue;
5592 
5593     CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5594     assert(Dtor && "No dtor found for FieldClassDecl!");
5595     CheckDestructorAccess(Field->getLocation(), Dtor,
5596                           PDiag(diag::err_access_dtor_field)
5597                             << Field->getDeclName()
5598                             << FieldType);
5599 
5600     MarkFunctionReferenced(Location, Dtor);
5601     DiagnoseUseOfDecl(Dtor, Location);
5602   }
5603 
5604   // We only potentially invoke the destructors of potentially constructed
5605   // subobjects.
5606   bool VisitVirtualBases = !ClassDecl->isAbstract();
5607 
5608   // If the destructor exists and has already been marked used in the MS ABI,
5609   // then virtual base destructors have already been checked and marked used.
5610   // Skip checking them again to avoid duplicate diagnostics.
5611   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5612     CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5613     if (Dtor && Dtor->isUsed())
5614       VisitVirtualBases = false;
5615   }
5616 
5617   llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5618 
5619   // Bases.
5620   for (const auto &Base : ClassDecl->bases()) {
5621     const RecordType *RT = Base.getType()->getAs<RecordType>();
5622     if (!RT)
5623       continue;
5624 
5625     // Remember direct virtual bases.
5626     if (Base.isVirtual()) {
5627       if (!VisitVirtualBases)
5628         continue;
5629       DirectVirtualBases.insert(RT);
5630     }
5631 
5632     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5633     // If our base class is invalid, we probably can't get its dtor anyway.
5634     if (BaseClassDecl->isInvalidDecl())
5635       continue;
5636     if (BaseClassDecl->hasIrrelevantDestructor())
5637       continue;
5638 
5639     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5640     assert(Dtor && "No dtor found for BaseClassDecl!");
5641 
5642     // FIXME: caret should be on the start of the class name
5643     CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5644                           PDiag(diag::err_access_dtor_base)
5645                               << Base.getType() << Base.getSourceRange(),
5646                           Context.getTypeDeclType(ClassDecl));
5647 
5648     MarkFunctionReferenced(Location, Dtor);
5649     DiagnoseUseOfDecl(Dtor, Location);
5650   }
5651 
5652   if (VisitVirtualBases)
5653     MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5654                                          &DirectVirtualBases);
5655 }
5656 
5657 void Sema::MarkVirtualBaseDestructorsReferenced(
5658     SourceLocation Location, CXXRecordDecl *ClassDecl,
5659     llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5660   // Virtual bases.
5661   for (const auto &VBase : ClassDecl->vbases()) {
5662     // Bases are always records in a well-formed non-dependent class.
5663     const RecordType *RT = VBase.getType()->castAs<RecordType>();
5664 
5665     // Ignore already visited direct virtual bases.
5666     if (DirectVirtualBases && DirectVirtualBases->count(RT))
5667       continue;
5668 
5669     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5670     // If our base class is invalid, we probably can't get its dtor anyway.
5671     if (BaseClassDecl->isInvalidDecl())
5672       continue;
5673     if (BaseClassDecl->hasIrrelevantDestructor())
5674       continue;
5675 
5676     CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5677     assert(Dtor && "No dtor found for BaseClassDecl!");
5678     if (CheckDestructorAccess(
5679             ClassDecl->getLocation(), Dtor,
5680             PDiag(diag::err_access_dtor_vbase)
5681                 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5682             Context.getTypeDeclType(ClassDecl)) ==
5683         AR_accessible) {
5684       CheckDerivedToBaseConversion(
5685           Context.getTypeDeclType(ClassDecl), VBase.getType(),
5686           diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5687           SourceRange(), DeclarationName(), nullptr);
5688     }
5689 
5690     MarkFunctionReferenced(Location, Dtor);
5691     DiagnoseUseOfDecl(Dtor, Location);
5692   }
5693 }
5694 
5695 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5696   if (!CDtorDecl)
5697     return;
5698 
5699   if (CXXConstructorDecl *Constructor
5700       = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5701     SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5702     DiagnoseUninitializedFields(*this, Constructor);
5703   }
5704 }
5705 
5706 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5707   if (!getLangOpts().CPlusPlus)
5708     return false;
5709 
5710   const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5711   if (!RD)
5712     return false;
5713 
5714   // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5715   // class template specialization here, but doing so breaks a lot of code.
5716 
5717   // We can't answer whether something is abstract until it has a
5718   // definition. If it's currently being defined, we'll walk back
5719   // over all the declarations when we have a full definition.
5720   const CXXRecordDecl *Def = RD->getDefinition();
5721   if (!Def || Def->isBeingDefined())
5722     return false;
5723 
5724   return RD->isAbstract();
5725 }
5726 
5727 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5728                                   TypeDiagnoser &Diagnoser) {
5729   if (!isAbstractType(Loc, T))
5730     return false;
5731 
5732   T = Context.getBaseElementType(T);
5733   Diagnoser.diagnose(*this, Loc, T);
5734   DiagnoseAbstractType(T->getAsCXXRecordDecl());
5735   return true;
5736 }
5737 
5738 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5739   // Check if we've already emitted the list of pure virtual functions
5740   // for this class.
5741   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5742     return;
5743 
5744   // If the diagnostic is suppressed, don't emit the notes. We're only
5745   // going to emit them once, so try to attach them to a diagnostic we're
5746   // actually going to show.
5747   if (Diags.isLastDiagnosticIgnored())
5748     return;
5749 
5750   CXXFinalOverriderMap FinalOverriders;
5751   RD->getFinalOverriders(FinalOverriders);
5752 
5753   // Keep a set of seen pure methods so we won't diagnose the same method
5754   // more than once.
5755   llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5756 
5757   for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5758                                    MEnd = FinalOverriders.end();
5759        M != MEnd;
5760        ++M) {
5761     for (OverridingMethods::iterator SO = M->second.begin(),
5762                                   SOEnd = M->second.end();
5763          SO != SOEnd; ++SO) {
5764       // C++ [class.abstract]p4:
5765       //   A class is abstract if it contains or inherits at least one
5766       //   pure virtual function for which the final overrider is pure
5767       //   virtual.
5768 
5769       //
5770       if (SO->second.size() != 1)
5771         continue;
5772 
5773       if (!SO->second.front().Method->isPure())
5774         continue;
5775 
5776       if (!SeenPureMethods.insert(SO->second.front().Method).second)
5777         continue;
5778 
5779       Diag(SO->second.front().Method->getLocation(),
5780            diag::note_pure_virtual_function)
5781         << SO->second.front().Method->getDeclName() << RD->getDeclName();
5782     }
5783   }
5784 
5785   if (!PureVirtualClassDiagSet)
5786     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5787   PureVirtualClassDiagSet->insert(RD);
5788 }
5789 
5790 namespace {
5791 struct AbstractUsageInfo {
5792   Sema &S;
5793   CXXRecordDecl *Record;
5794   CanQualType AbstractType;
5795   bool Invalid;
5796 
5797   AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5798     : S(S), Record(Record),
5799       AbstractType(S.Context.getCanonicalType(
5800                    S.Context.getTypeDeclType(Record))),
5801       Invalid(false) {}
5802 
5803   void DiagnoseAbstractType() {
5804     if (Invalid) return;
5805     S.DiagnoseAbstractType(Record);
5806     Invalid = true;
5807   }
5808 
5809   void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5810 };
5811 
5812 struct CheckAbstractUsage {
5813   AbstractUsageInfo &Info;
5814   const NamedDecl *Ctx;
5815 
5816   CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5817     : Info(Info), Ctx(Ctx) {}
5818 
5819   void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5820     switch (TL.getTypeLocClass()) {
5821 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5822 #define TYPELOC(CLASS, PARENT) \
5823     case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5824 #include "clang/AST/TypeLocNodes.def"
5825     }
5826   }
5827 
5828   void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5829     Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5830     for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5831       if (!TL.getParam(I))
5832         continue;
5833 
5834       TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5835       if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5836     }
5837   }
5838 
5839   void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5840     Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5841   }
5842 
5843   void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5844     // Visit the type parameters from a permissive context.
5845     for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5846       TemplateArgumentLoc TAL = TL.getArgLoc(I);
5847       if (TAL.getArgument().getKind() == TemplateArgument::Type)
5848         if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5849           Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5850       // TODO: other template argument types?
5851     }
5852   }
5853 
5854   // Visit pointee types from a permissive context.
5855 #define CheckPolymorphic(Type) \
5856   void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5857     Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5858   }
5859   CheckPolymorphic(PointerTypeLoc)
5860   CheckPolymorphic(ReferenceTypeLoc)
5861   CheckPolymorphic(MemberPointerTypeLoc)
5862   CheckPolymorphic(BlockPointerTypeLoc)
5863   CheckPolymorphic(AtomicTypeLoc)
5864 
5865   /// Handle all the types we haven't given a more specific
5866   /// implementation for above.
5867   void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5868     // Every other kind of type that we haven't called out already
5869     // that has an inner type is either (1) sugar or (2) contains that
5870     // inner type in some way as a subobject.
5871     if (TypeLoc Next = TL.getNextTypeLoc())
5872       return Visit(Next, Sel);
5873 
5874     // If there's no inner type and we're in a permissive context,
5875     // don't diagnose.
5876     if (Sel == Sema::AbstractNone) return;
5877 
5878     // Check whether the type matches the abstract type.
5879     QualType T = TL.getType();
5880     if (T->isArrayType()) {
5881       Sel = Sema::AbstractArrayType;
5882       T = Info.S.Context.getBaseElementType(T);
5883     }
5884     CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5885     if (CT != Info.AbstractType) return;
5886 
5887     // It matched; do some magic.
5888     // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
5889     if (Sel == Sema::AbstractArrayType) {
5890       Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5891         << T << TL.getSourceRange();
5892     } else {
5893       Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5894         << Sel << T << TL.getSourceRange();
5895     }
5896     Info.DiagnoseAbstractType();
5897   }
5898 };
5899 
5900 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5901                                   Sema::AbstractDiagSelID Sel) {
5902   CheckAbstractUsage(*this, D).Visit(TL, Sel);
5903 }
5904 
5905 }
5906 
5907 /// Check for invalid uses of an abstract type in a function declaration.
5908 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5909                                     FunctionDecl *FD) {
5910   // No need to do the check on definitions, which require that
5911   // the return/param types be complete.
5912   if (FD->doesThisDeclarationHaveABody())
5913     return;
5914 
5915   // For safety's sake, just ignore it if we don't have type source
5916   // information.  This should never happen for non-implicit methods,
5917   // but...
5918   if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5919     Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone);
5920 }
5921 
5922 /// Check for invalid uses of an abstract type in a variable0 declaration.
5923 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5924                                     VarDecl *VD) {
5925   // No need to do the check on definitions, which require that
5926   // the type is complete.
5927   if (VD->isThisDeclarationADefinition())
5928     return;
5929 
5930   Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(),
5931                  Sema::AbstractVariableType);
5932 }
5933 
5934 /// Check for invalid uses of an abstract type within a class definition.
5935 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5936                                     CXXRecordDecl *RD) {
5937   for (auto *D : RD->decls()) {
5938     if (D->isImplicit()) continue;
5939 
5940     // Step through friends to the befriended declaration.
5941     if (auto *FD = dyn_cast<FriendDecl>(D)) {
5942       D = FD->getFriendDecl();
5943       if (!D) continue;
5944     }
5945 
5946     // Functions and function templates.
5947     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5948       CheckAbstractClassUsage(Info, FD);
5949     } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
5950       CheckAbstractClassUsage(Info, FTD->getTemplatedDecl());
5951 
5952     // Fields and static variables.
5953     } else if (auto *FD = dyn_cast<FieldDecl>(D)) {
5954       if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5955         Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5956     } else if (auto *VD = dyn_cast<VarDecl>(D)) {
5957       CheckAbstractClassUsage(Info, VD);
5958     } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) {
5959       CheckAbstractClassUsage(Info, VTD->getTemplatedDecl());
5960 
5961     // Nested classes and class templates.
5962     } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5963       CheckAbstractClassUsage(Info, RD);
5964     } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) {
5965       CheckAbstractClassUsage(Info, CTD->getTemplatedDecl());
5966     }
5967   }
5968 }
5969 
5970 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5971   Attr *ClassAttr = getDLLAttr(Class);
5972   if (!ClassAttr)
5973     return;
5974 
5975   assert(ClassAttr->getKind() == attr::DLLExport);
5976 
5977   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5978 
5979   if (TSK == TSK_ExplicitInstantiationDeclaration)
5980     // Don't go any further if this is just an explicit instantiation
5981     // declaration.
5982     return;
5983 
5984   // Add a context note to explain how we got to any diagnostics produced below.
5985   struct MarkingClassDllexported {
5986     Sema &S;
5987     MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5988                             SourceLocation AttrLoc)
5989         : S(S) {
5990       Sema::CodeSynthesisContext Ctx;
5991       Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5992       Ctx.PointOfInstantiation = AttrLoc;
5993       Ctx.Entity = Class;
5994       S.pushCodeSynthesisContext(Ctx);
5995     }
5996     ~MarkingClassDllexported() {
5997       S.popCodeSynthesisContext();
5998     }
5999   } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6000 
6001   if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
6002     S.MarkVTableUsed(Class->getLocation(), Class, true);
6003 
6004   for (Decl *Member : Class->decls()) {
6005     // Skip members that were not marked exported.
6006     if (!Member->hasAttr<DLLExportAttr>())
6007       continue;
6008 
6009     // Defined static variables that are members of an exported base
6010     // class must be marked export too.
6011     auto *VD = dyn_cast<VarDecl>(Member);
6012     if (VD && VD->getStorageClass() == SC_Static &&
6013         TSK == TSK_ImplicitInstantiation)
6014       S.MarkVariableReferenced(VD->getLocation(), VD);
6015 
6016     auto *MD = dyn_cast<CXXMethodDecl>(Member);
6017     if (!MD)
6018       continue;
6019 
6020     if (MD->isUserProvided()) {
6021       // Instantiate non-default class member functions ...
6022 
6023       // .. except for certain kinds of template specializations.
6024       if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6025         continue;
6026 
6027       // If this is an MS ABI dllexport default constructor, instantiate any
6028       // default arguments.
6029       if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6030         auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6031         if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6032           S.InstantiateDefaultCtorDefaultArgs(CD);
6033         }
6034       }
6035 
6036       S.MarkFunctionReferenced(Class->getLocation(), MD);
6037 
6038       // The function will be passed to the consumer when its definition is
6039       // encountered.
6040     } else if (MD->isExplicitlyDefaulted()) {
6041       // Synthesize and instantiate explicitly defaulted methods.
6042       S.MarkFunctionReferenced(Class->getLocation(), MD);
6043 
6044       if (TSK != TSK_ExplicitInstantiationDefinition) {
6045         // Except for explicit instantiation defs, we will not see the
6046         // definition again later, so pass it to the consumer now.
6047         S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6048       }
6049     } else if (!MD->isTrivial() ||
6050                MD->isCopyAssignmentOperator() ||
6051                MD->isMoveAssignmentOperator()) {
6052       // Synthesize and instantiate non-trivial implicit methods, and the copy
6053       // and move assignment operators. The latter are exported even if they
6054       // are trivial, because the address of an operator can be taken and
6055       // should compare equal across libraries.
6056       S.MarkFunctionReferenced(Class->getLocation(), MD);
6057 
6058       // There is no later point when we will see the definition of this
6059       // function, so pass it to the consumer now.
6060       S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6061     }
6062   }
6063 }
6064 
6065 static void checkForMultipleExportedDefaultConstructors(Sema &S,
6066                                                         CXXRecordDecl *Class) {
6067   // Only the MS ABI has default constructor closures, so we don't need to do
6068   // this semantic checking anywhere else.
6069   if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6070     return;
6071 
6072   CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6073   for (Decl *Member : Class->decls()) {
6074     // Look for exported default constructors.
6075     auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6076     if (!CD || !CD->isDefaultConstructor())
6077       continue;
6078     auto *Attr = CD->getAttr<DLLExportAttr>();
6079     if (!Attr)
6080       continue;
6081 
6082     // If the class is non-dependent, mark the default arguments as ODR-used so
6083     // that we can properly codegen the constructor closure.
6084     if (!Class->isDependentContext()) {
6085       for (ParmVarDecl *PD : CD->parameters()) {
6086         (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6087         S.DiscardCleanupsInEvaluationContext();
6088       }
6089     }
6090 
6091     if (LastExportedDefaultCtor) {
6092       S.Diag(LastExportedDefaultCtor->getLocation(),
6093              diag::err_attribute_dll_ambiguous_default_ctor)
6094           << Class;
6095       S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6096           << CD->getDeclName();
6097       return;
6098     }
6099     LastExportedDefaultCtor = CD;
6100   }
6101 }
6102 
6103 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6104                                                        CXXRecordDecl *Class) {
6105   bool ErrorReported = false;
6106   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6107                                                      ClassTemplateDecl *TD) {
6108     if (ErrorReported)
6109       return;
6110     S.Diag(TD->getLocation(),
6111            diag::err_cuda_device_builtin_surftex_cls_template)
6112         << /*surface*/ 0 << TD;
6113     ErrorReported = true;
6114   };
6115 
6116   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6117   if (!TD) {
6118     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6119     if (!SD) {
6120       S.Diag(Class->getLocation(),
6121              diag::err_cuda_device_builtin_surftex_ref_decl)
6122           << /*surface*/ 0 << Class;
6123       S.Diag(Class->getLocation(),
6124              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6125           << Class;
6126       return;
6127     }
6128     TD = SD->getSpecializedTemplate();
6129   }
6130 
6131   TemplateParameterList *Params = TD->getTemplateParameters();
6132   unsigned N = Params->size();
6133 
6134   if (N != 2) {
6135     reportIllegalClassTemplate(S, TD);
6136     S.Diag(TD->getLocation(),
6137            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6138         << TD << 2;
6139   }
6140   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6141     reportIllegalClassTemplate(S, TD);
6142     S.Diag(TD->getLocation(),
6143            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6144         << TD << /*1st*/ 0 << /*type*/ 0;
6145   }
6146   if (N > 1) {
6147     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6148     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6149       reportIllegalClassTemplate(S, TD);
6150       S.Diag(TD->getLocation(),
6151              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6152           << TD << /*2nd*/ 1 << /*integer*/ 1;
6153     }
6154   }
6155 }
6156 
6157 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6158                                                        CXXRecordDecl *Class) {
6159   bool ErrorReported = false;
6160   auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6161                                                      ClassTemplateDecl *TD) {
6162     if (ErrorReported)
6163       return;
6164     S.Diag(TD->getLocation(),
6165            diag::err_cuda_device_builtin_surftex_cls_template)
6166         << /*texture*/ 1 << TD;
6167     ErrorReported = true;
6168   };
6169 
6170   ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6171   if (!TD) {
6172     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6173     if (!SD) {
6174       S.Diag(Class->getLocation(),
6175              diag::err_cuda_device_builtin_surftex_ref_decl)
6176           << /*texture*/ 1 << Class;
6177       S.Diag(Class->getLocation(),
6178              diag::note_cuda_device_builtin_surftex_should_be_template_class)
6179           << Class;
6180       return;
6181     }
6182     TD = SD->getSpecializedTemplate();
6183   }
6184 
6185   TemplateParameterList *Params = TD->getTemplateParameters();
6186   unsigned N = Params->size();
6187 
6188   if (N != 3) {
6189     reportIllegalClassTemplate(S, TD);
6190     S.Diag(TD->getLocation(),
6191            diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6192         << TD << 3;
6193   }
6194   if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6195     reportIllegalClassTemplate(S, TD);
6196     S.Diag(TD->getLocation(),
6197            diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6198         << TD << /*1st*/ 0 << /*type*/ 0;
6199   }
6200   if (N > 1) {
6201     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6202     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6203       reportIllegalClassTemplate(S, TD);
6204       S.Diag(TD->getLocation(),
6205              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6206           << TD << /*2nd*/ 1 << /*integer*/ 1;
6207     }
6208   }
6209   if (N > 2) {
6210     auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6211     if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6212       reportIllegalClassTemplate(S, TD);
6213       S.Diag(TD->getLocation(),
6214              diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6215           << TD << /*3rd*/ 2 << /*integer*/ 1;
6216     }
6217   }
6218 }
6219 
6220 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6221   // Mark any compiler-generated routines with the implicit code_seg attribute.
6222   for (auto *Method : Class->methods()) {
6223     if (Method->isUserProvided())
6224       continue;
6225     if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6226       Method->addAttr(A);
6227   }
6228 }
6229 
6230 /// Check class-level dllimport/dllexport attribute.
6231 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6232   Attr *ClassAttr = getDLLAttr(Class);
6233 
6234   // MSVC inherits DLL attributes to partial class template specializations.
6235   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6236     if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6237       if (Attr *TemplateAttr =
6238               getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6239         auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6240         A->setInherited(true);
6241         ClassAttr = A;
6242       }
6243     }
6244   }
6245 
6246   if (!ClassAttr)
6247     return;
6248 
6249   if (!Class->isExternallyVisible()) {
6250     Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6251         << Class << ClassAttr;
6252     return;
6253   }
6254 
6255   if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6256       !ClassAttr->isInherited()) {
6257     // Diagnose dll attributes on members of class with dll attribute.
6258     for (Decl *Member : Class->decls()) {
6259       if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6260         continue;
6261       InheritableAttr *MemberAttr = getDLLAttr(Member);
6262       if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6263         continue;
6264 
6265       Diag(MemberAttr->getLocation(),
6266              diag::err_attribute_dll_member_of_dll_class)
6267           << MemberAttr << ClassAttr;
6268       Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6269       Member->setInvalidDecl();
6270     }
6271   }
6272 
6273   if (Class->getDescribedClassTemplate())
6274     // Don't inherit dll attribute until the template is instantiated.
6275     return;
6276 
6277   // The class is either imported or exported.
6278   const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6279 
6280   // Check if this was a dllimport attribute propagated from a derived class to
6281   // a base class template specialization. We don't apply these attributes to
6282   // static data members.
6283   const bool PropagatedImport =
6284       !ClassExported &&
6285       cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6286 
6287   TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6288 
6289   // Ignore explicit dllexport on explicit class template instantiation
6290   // declarations, except in MinGW mode.
6291   if (ClassExported && !ClassAttr->isInherited() &&
6292       TSK == TSK_ExplicitInstantiationDeclaration &&
6293       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6294     Class->dropAttr<DLLExportAttr>();
6295     return;
6296   }
6297 
6298   // Force declaration of implicit members so they can inherit the attribute.
6299   ForceDeclarationOfImplicitMembers(Class);
6300 
6301   // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6302   // seem to be true in practice?
6303 
6304   for (Decl *Member : Class->decls()) {
6305     VarDecl *VD = dyn_cast<VarDecl>(Member);
6306     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6307 
6308     // Only methods and static fields inherit the attributes.
6309     if (!VD && !MD)
6310       continue;
6311 
6312     if (MD) {
6313       // Don't process deleted methods.
6314       if (MD->isDeleted())
6315         continue;
6316 
6317       if (MD->isInlined()) {
6318         // MinGW does not import or export inline methods. But do it for
6319         // template instantiations.
6320         if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6321             TSK != TSK_ExplicitInstantiationDeclaration &&
6322             TSK != TSK_ExplicitInstantiationDefinition)
6323           continue;
6324 
6325         // MSVC versions before 2015 don't export the move assignment operators
6326         // and move constructor, so don't attempt to import/export them if
6327         // we have a definition.
6328         auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6329         if ((MD->isMoveAssignmentOperator() ||
6330              (Ctor && Ctor->isMoveConstructor())) &&
6331             !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6332           continue;
6333 
6334         // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6335         // operator is exported anyway.
6336         if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6337             (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6338           continue;
6339       }
6340     }
6341 
6342     // Don't apply dllimport attributes to static data members of class template
6343     // instantiations when the attribute is propagated from a derived class.
6344     if (VD && PropagatedImport)
6345       continue;
6346 
6347     if (!cast<NamedDecl>(Member)->isExternallyVisible())
6348       continue;
6349 
6350     if (!getDLLAttr(Member)) {
6351       InheritableAttr *NewAttr = nullptr;
6352 
6353       // Do not export/import inline function when -fno-dllexport-inlines is
6354       // passed. But add attribute for later local static var check.
6355       if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6356           TSK != TSK_ExplicitInstantiationDeclaration &&
6357           TSK != TSK_ExplicitInstantiationDefinition) {
6358         if (ClassExported) {
6359           NewAttr = ::new (getASTContext())
6360               DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6361         } else {
6362           NewAttr = ::new (getASTContext())
6363               DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6364         }
6365       } else {
6366         NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6367       }
6368 
6369       NewAttr->setInherited(true);
6370       Member->addAttr(NewAttr);
6371 
6372       if (MD) {
6373         // Propagate DLLAttr to friend re-declarations of MD that have already
6374         // been constructed.
6375         for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6376              FD = FD->getPreviousDecl()) {
6377           if (FD->getFriendObjectKind() == Decl::FOK_None)
6378             continue;
6379           assert(!getDLLAttr(FD) &&
6380                  "friend re-decl should not already have a DLLAttr");
6381           NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6382           NewAttr->setInherited(true);
6383           FD->addAttr(NewAttr);
6384         }
6385       }
6386     }
6387   }
6388 
6389   if (ClassExported)
6390     DelayedDllExportClasses.push_back(Class);
6391 }
6392 
6393 /// Perform propagation of DLL attributes from a derived class to a
6394 /// templated base class for MS compatibility.
6395 void Sema::propagateDLLAttrToBaseClassTemplate(
6396     CXXRecordDecl *Class, Attr *ClassAttr,
6397     ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6398   if (getDLLAttr(
6399           BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6400     // If the base class template has a DLL attribute, don't try to change it.
6401     return;
6402   }
6403 
6404   auto TSK = BaseTemplateSpec->getSpecializationKind();
6405   if (!getDLLAttr(BaseTemplateSpec) &&
6406       (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6407        TSK == TSK_ImplicitInstantiation)) {
6408     // The template hasn't been instantiated yet (or it has, but only as an
6409     // explicit instantiation declaration or implicit instantiation, which means
6410     // we haven't codegenned any members yet), so propagate the attribute.
6411     auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6412     NewAttr->setInherited(true);
6413     BaseTemplateSpec->addAttr(NewAttr);
6414 
6415     // If this was an import, mark that we propagated it from a derived class to
6416     // a base class template specialization.
6417     if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6418       ImportAttr->setPropagatedToBaseTemplate();
6419 
6420     // If the template is already instantiated, checkDLLAttributeRedeclaration()
6421     // needs to be run again to work see the new attribute. Otherwise this will
6422     // get run whenever the template is instantiated.
6423     if (TSK != TSK_Undeclared)
6424       checkClassLevelDLLAttribute(BaseTemplateSpec);
6425 
6426     return;
6427   }
6428 
6429   if (getDLLAttr(BaseTemplateSpec)) {
6430     // The template has already been specialized or instantiated with an
6431     // attribute, explicitly or through propagation. We should not try to change
6432     // it.
6433     return;
6434   }
6435 
6436   // The template was previously instantiated or explicitly specialized without
6437   // a dll attribute, It's too late for us to add an attribute, so warn that
6438   // this is unsupported.
6439   Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6440       << BaseTemplateSpec->isExplicitSpecialization();
6441   Diag(ClassAttr->getLocation(), diag::note_attribute);
6442   if (BaseTemplateSpec->isExplicitSpecialization()) {
6443     Diag(BaseTemplateSpec->getLocation(),
6444            diag::note_template_class_explicit_specialization_was_here)
6445         << BaseTemplateSpec;
6446   } else {
6447     Diag(BaseTemplateSpec->getPointOfInstantiation(),
6448            diag::note_template_class_instantiation_was_here)
6449         << BaseTemplateSpec;
6450   }
6451 }
6452 
6453 /// Determine the kind of defaulting that would be done for a given function.
6454 ///
6455 /// If the function is both a default constructor and a copy / move constructor
6456 /// (due to having a default argument for the first parameter), this picks
6457 /// CXXDefaultConstructor.
6458 ///
6459 /// FIXME: Check that case is properly handled by all callers.
6460 Sema::DefaultedFunctionKind
6461 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6462   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6463     if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6464       if (Ctor->isDefaultConstructor())
6465         return Sema::CXXDefaultConstructor;
6466 
6467       if (Ctor->isCopyConstructor())
6468         return Sema::CXXCopyConstructor;
6469 
6470       if (Ctor->isMoveConstructor())
6471         return Sema::CXXMoveConstructor;
6472     }
6473 
6474     if (MD->isCopyAssignmentOperator())
6475       return Sema::CXXCopyAssignment;
6476 
6477     if (MD->isMoveAssignmentOperator())
6478       return Sema::CXXMoveAssignment;
6479 
6480     if (isa<CXXDestructorDecl>(FD))
6481       return Sema::CXXDestructor;
6482   }
6483 
6484   switch (FD->getDeclName().getCXXOverloadedOperator()) {
6485   case OO_EqualEqual:
6486     return DefaultedComparisonKind::Equal;
6487 
6488   case OO_ExclaimEqual:
6489     return DefaultedComparisonKind::NotEqual;
6490 
6491   case OO_Spaceship:
6492     // No point allowing this if <=> doesn't exist in the current language mode.
6493     if (!getLangOpts().CPlusPlus20)
6494       break;
6495     return DefaultedComparisonKind::ThreeWay;
6496 
6497   case OO_Less:
6498   case OO_LessEqual:
6499   case OO_Greater:
6500   case OO_GreaterEqual:
6501     // No point allowing this if <=> doesn't exist in the current language mode.
6502     if (!getLangOpts().CPlusPlus20)
6503       break;
6504     return DefaultedComparisonKind::Relational;
6505 
6506   default:
6507     break;
6508   }
6509 
6510   // Not defaultable.
6511   return DefaultedFunctionKind();
6512 }
6513 
6514 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6515                                     SourceLocation DefaultLoc) {
6516   Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6517   if (DFK.isComparison())
6518     return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6519 
6520   switch (DFK.asSpecialMember()) {
6521   case Sema::CXXDefaultConstructor:
6522     S.DefineImplicitDefaultConstructor(DefaultLoc,
6523                                        cast<CXXConstructorDecl>(FD));
6524     break;
6525   case Sema::CXXCopyConstructor:
6526     S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6527     break;
6528   case Sema::CXXCopyAssignment:
6529     S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6530     break;
6531   case Sema::CXXDestructor:
6532     S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6533     break;
6534   case Sema::CXXMoveConstructor:
6535     S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6536     break;
6537   case Sema::CXXMoveAssignment:
6538     S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6539     break;
6540   case Sema::CXXInvalid:
6541     llvm_unreachable("Invalid special member.");
6542   }
6543 }
6544 
6545 /// Determine whether a type is permitted to be passed or returned in
6546 /// registers, per C++ [class.temporary]p3.
6547 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6548                                TargetInfo::CallingConvKind CCK) {
6549   if (D->isDependentType() || D->isInvalidDecl())
6550     return false;
6551 
6552   // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6553   // The PS4 platform ABI follows the behavior of Clang 3.2.
6554   if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6555     return !D->hasNonTrivialDestructorForCall() &&
6556            !D->hasNonTrivialCopyConstructorForCall();
6557 
6558   if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6559     bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6560     bool DtorIsTrivialForCall = false;
6561 
6562     // If a class has at least one non-deleted, trivial copy constructor, it
6563     // is passed according to the C ABI. Otherwise, it is passed indirectly.
6564     //
6565     // Note: This permits classes with non-trivial copy or move ctors to be
6566     // passed in registers, so long as they *also* have a trivial copy ctor,
6567     // which is non-conforming.
6568     if (D->needsImplicitCopyConstructor()) {
6569       if (!D->defaultedCopyConstructorIsDeleted()) {
6570         if (D->hasTrivialCopyConstructor())
6571           CopyCtorIsTrivial = true;
6572         if (D->hasTrivialCopyConstructorForCall())
6573           CopyCtorIsTrivialForCall = true;
6574       }
6575     } else {
6576       for (const CXXConstructorDecl *CD : D->ctors()) {
6577         if (CD->isCopyConstructor() && !CD->isDeleted()) {
6578           if (CD->isTrivial())
6579             CopyCtorIsTrivial = true;
6580           if (CD->isTrivialForCall())
6581             CopyCtorIsTrivialForCall = true;
6582         }
6583       }
6584     }
6585 
6586     if (D->needsImplicitDestructor()) {
6587       if (!D->defaultedDestructorIsDeleted() &&
6588           D->hasTrivialDestructorForCall())
6589         DtorIsTrivialForCall = true;
6590     } else if (const auto *DD = D->getDestructor()) {
6591       if (!DD->isDeleted() && DD->isTrivialForCall())
6592         DtorIsTrivialForCall = true;
6593     }
6594 
6595     // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6596     if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6597       return true;
6598 
6599     // If a class has a destructor, we'd really like to pass it indirectly
6600     // because it allows us to elide copies.  Unfortunately, MSVC makes that
6601     // impossible for small types, which it will pass in a single register or
6602     // stack slot. Most objects with dtors are large-ish, so handle that early.
6603     // We can't call out all large objects as being indirect because there are
6604     // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6605     // how we pass large POD types.
6606 
6607     // Note: This permits small classes with nontrivial destructors to be
6608     // passed in registers, which is non-conforming.
6609     bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6610     uint64_t TypeSize = isAArch64 ? 128 : 64;
6611 
6612     if (CopyCtorIsTrivial &&
6613         S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6614       return true;
6615     return false;
6616   }
6617 
6618   // Per C++ [class.temporary]p3, the relevant condition is:
6619   //   each copy constructor, move constructor, and destructor of X is
6620   //   either trivial or deleted, and X has at least one non-deleted copy
6621   //   or move constructor
6622   bool HasNonDeletedCopyOrMove = false;
6623 
6624   if (D->needsImplicitCopyConstructor() &&
6625       !D->defaultedCopyConstructorIsDeleted()) {
6626     if (!D->hasTrivialCopyConstructorForCall())
6627       return false;
6628     HasNonDeletedCopyOrMove = true;
6629   }
6630 
6631   if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6632       !D->defaultedMoveConstructorIsDeleted()) {
6633     if (!D->hasTrivialMoveConstructorForCall())
6634       return false;
6635     HasNonDeletedCopyOrMove = true;
6636   }
6637 
6638   if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6639       !D->hasTrivialDestructorForCall())
6640     return false;
6641 
6642   for (const CXXMethodDecl *MD : D->methods()) {
6643     if (MD->isDeleted())
6644       continue;
6645 
6646     auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6647     if (CD && CD->isCopyOrMoveConstructor())
6648       HasNonDeletedCopyOrMove = true;
6649     else if (!isa<CXXDestructorDecl>(MD))
6650       continue;
6651 
6652     if (!MD->isTrivialForCall())
6653       return false;
6654   }
6655 
6656   return HasNonDeletedCopyOrMove;
6657 }
6658 
6659 /// Report an error regarding overriding, along with any relevant
6660 /// overridden methods.
6661 ///
6662 /// \param DiagID the primary error to report.
6663 /// \param MD the overriding method.
6664 static bool
6665 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6666                 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6667   bool IssuedDiagnostic = false;
6668   for (const CXXMethodDecl *O : MD->overridden_methods()) {
6669     if (Report(O)) {
6670       if (!IssuedDiagnostic) {
6671         S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6672         IssuedDiagnostic = true;
6673       }
6674       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6675     }
6676   }
6677   return IssuedDiagnostic;
6678 }
6679 
6680 /// Perform semantic checks on a class definition that has been
6681 /// completing, introducing implicitly-declared members, checking for
6682 /// abstract types, etc.
6683 ///
6684 /// \param S The scope in which the class was parsed. Null if we didn't just
6685 ///        parse a class definition.
6686 /// \param Record The completed class.
6687 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6688   if (!Record)
6689     return;
6690 
6691   if (Record->isAbstract() && !Record->isInvalidDecl()) {
6692     AbstractUsageInfo Info(*this, Record);
6693     CheckAbstractClassUsage(Info, Record);
6694   }
6695 
6696   // If this is not an aggregate type and has no user-declared constructor,
6697   // complain about any non-static data members of reference or const scalar
6698   // type, since they will never get initializers.
6699   if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6700       !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6701       !Record->isLambda()) {
6702     bool Complained = false;
6703     for (const auto *F : Record->fields()) {
6704       if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6705         continue;
6706 
6707       if (F->getType()->isReferenceType() ||
6708           (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6709         if (!Complained) {
6710           Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6711             << Record->getTagKind() << Record;
6712           Complained = true;
6713         }
6714 
6715         Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6716           << F->getType()->isReferenceType()
6717           << F->getDeclName();
6718       }
6719     }
6720   }
6721 
6722   if (Record->getIdentifier()) {
6723     // C++ [class.mem]p13:
6724     //   If T is the name of a class, then each of the following shall have a
6725     //   name different from T:
6726     //     - every member of every anonymous union that is a member of class T.
6727     //
6728     // C++ [class.mem]p14:
6729     //   In addition, if class T has a user-declared constructor (12.1), every
6730     //   non-static data member of class T shall have a name different from T.
6731     DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6732     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6733          ++I) {
6734       NamedDecl *D = (*I)->getUnderlyingDecl();
6735       if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6736            Record->hasUserDeclaredConstructor()) ||
6737           isa<IndirectFieldDecl>(D)) {
6738         Diag((*I)->getLocation(), diag::err_member_name_of_class)
6739           << D->getDeclName();
6740         break;
6741       }
6742     }
6743   }
6744 
6745   // Warn if the class has virtual methods but non-virtual public destructor.
6746   if (Record->isPolymorphic() && !Record->isDependentType()) {
6747     CXXDestructorDecl *dtor = Record->getDestructor();
6748     if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6749         !Record->hasAttr<FinalAttr>())
6750       Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6751            diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6752   }
6753 
6754   if (Record->isAbstract()) {
6755     if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6756       Diag(Record->getLocation(), diag::warn_abstract_final_class)
6757         << FA->isSpelledAsSealed();
6758       DiagnoseAbstractType(Record);
6759     }
6760   }
6761 
6762   // Warn if the class has a final destructor but is not itself marked final.
6763   if (!Record->hasAttr<FinalAttr>()) {
6764     if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6765       if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6766         Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6767             << FA->isSpelledAsSealed()
6768             << FixItHint::CreateInsertion(
6769                    getLocForEndOfToken(Record->getLocation()),
6770                    (FA->isSpelledAsSealed() ? " sealed" : " final"));
6771         Diag(Record->getLocation(),
6772              diag::note_final_dtor_non_final_class_silence)
6773             << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6774       }
6775     }
6776   }
6777 
6778   // See if trivial_abi has to be dropped.
6779   if (Record->hasAttr<TrivialABIAttr>())
6780     checkIllFormedTrivialABIStruct(*Record);
6781 
6782   // Set HasTrivialSpecialMemberForCall if the record has attribute
6783   // "trivial_abi".
6784   bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6785 
6786   if (HasTrivialABI)
6787     Record->setHasTrivialSpecialMemberForCall();
6788 
6789   // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6790   // We check these last because they can depend on the properties of the
6791   // primary comparison functions (==, <=>).
6792   llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6793 
6794   // Perform checks that can't be done until we know all the properties of a
6795   // member function (whether it's defaulted, deleted, virtual, overriding,
6796   // ...).
6797   auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6798     // A static function cannot override anything.
6799     if (MD->getStorageClass() == SC_Static) {
6800       if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6801                           [](const CXXMethodDecl *) { return true; }))
6802         return;
6803     }
6804 
6805     // A deleted function cannot override a non-deleted function and vice
6806     // versa.
6807     if (ReportOverrides(*this,
6808                         MD->isDeleted() ? diag::err_deleted_override
6809                                         : diag::err_non_deleted_override,
6810                         MD, [&](const CXXMethodDecl *V) {
6811                           return MD->isDeleted() != V->isDeleted();
6812                         })) {
6813       if (MD->isDefaulted() && MD->isDeleted())
6814         // Explain why this defaulted function was deleted.
6815         DiagnoseDeletedDefaultedFunction(MD);
6816       return;
6817     }
6818 
6819     // A consteval function cannot override a non-consteval function and vice
6820     // versa.
6821     if (ReportOverrides(*this,
6822                         MD->isConsteval() ? diag::err_consteval_override
6823                                           : diag::err_non_consteval_override,
6824                         MD, [&](const CXXMethodDecl *V) {
6825                           return MD->isConsteval() != V->isConsteval();
6826                         })) {
6827       if (MD->isDefaulted() && MD->isDeleted())
6828         // Explain why this defaulted function was deleted.
6829         DiagnoseDeletedDefaultedFunction(MD);
6830       return;
6831     }
6832   };
6833 
6834   auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6835     if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6836       return false;
6837 
6838     DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6839     if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6840         DFK.asComparison() == DefaultedComparisonKind::Relational) {
6841       DefaultedSecondaryComparisons.push_back(FD);
6842       return true;
6843     }
6844 
6845     CheckExplicitlyDefaultedFunction(S, FD);
6846     return false;
6847   };
6848 
6849   auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6850     // Check whether the explicitly-defaulted members are valid.
6851     bool Incomplete = CheckForDefaultedFunction(M);
6852 
6853     // Skip the rest of the checks for a member of a dependent class.
6854     if (Record->isDependentType())
6855       return;
6856 
6857     // For an explicitly defaulted or deleted special member, we defer
6858     // determining triviality until the class is complete. That time is now!
6859     CXXSpecialMember CSM = getSpecialMember(M);
6860     if (!M->isImplicit() && !M->isUserProvided()) {
6861       if (CSM != CXXInvalid) {
6862         M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6863         // Inform the class that we've finished declaring this member.
6864         Record->finishedDefaultedOrDeletedMember(M);
6865         M->setTrivialForCall(
6866             HasTrivialABI ||
6867             SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6868         Record->setTrivialForCallFlags(M);
6869       }
6870     }
6871 
6872     // Set triviality for the purpose of calls if this is a user-provided
6873     // copy/move constructor or destructor.
6874     if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6875          CSM == CXXDestructor) && M->isUserProvided()) {
6876       M->setTrivialForCall(HasTrivialABI);
6877       Record->setTrivialForCallFlags(M);
6878     }
6879 
6880     if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6881         M->hasAttr<DLLExportAttr>()) {
6882       if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6883           M->isTrivial() &&
6884           (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6885            CSM == CXXDestructor))
6886         M->dropAttr<DLLExportAttr>();
6887 
6888       if (M->hasAttr<DLLExportAttr>()) {
6889         // Define after any fields with in-class initializers have been parsed.
6890         DelayedDllExportMemberFunctions.push_back(M);
6891       }
6892     }
6893 
6894     // Define defaulted constexpr virtual functions that override a base class
6895     // function right away.
6896     // FIXME: We can defer doing this until the vtable is marked as used.
6897     if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6898       DefineDefaultedFunction(*this, M, M->getLocation());
6899 
6900     if (!Incomplete)
6901       CheckCompletedMemberFunction(M);
6902   };
6903 
6904   // Check the destructor before any other member function. We need to
6905   // determine whether it's trivial in order to determine whether the claas
6906   // type is a literal type, which is a prerequisite for determining whether
6907   // other special member functions are valid and whether they're implicitly
6908   // 'constexpr'.
6909   if (CXXDestructorDecl *Dtor = Record->getDestructor())
6910     CompleteMemberFunction(Dtor);
6911 
6912   bool HasMethodWithOverrideControl = false,
6913        HasOverridingMethodWithoutOverrideControl = false;
6914   for (auto *D : Record->decls()) {
6915     if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6916       // FIXME: We could do this check for dependent types with non-dependent
6917       // bases.
6918       if (!Record->isDependentType()) {
6919         // See if a method overloads virtual methods in a base
6920         // class without overriding any.
6921         if (!M->isStatic())
6922           DiagnoseHiddenVirtualMethods(M);
6923         if (M->hasAttr<OverrideAttr>())
6924           HasMethodWithOverrideControl = true;
6925         else if (M->size_overridden_methods() > 0)
6926           HasOverridingMethodWithoutOverrideControl = true;
6927       }
6928 
6929       if (!isa<CXXDestructorDecl>(M))
6930         CompleteMemberFunction(M);
6931     } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6932       CheckForDefaultedFunction(
6933           dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6934     }
6935   }
6936 
6937   if (HasOverridingMethodWithoutOverrideControl) {
6938     bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6939     for (auto *M : Record->methods())
6940       DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6941   }
6942 
6943   // Check the defaulted secondary comparisons after any other member functions.
6944   for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6945     CheckExplicitlyDefaultedFunction(S, FD);
6946 
6947     // If this is a member function, we deferred checking it until now.
6948     if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6949       CheckCompletedMemberFunction(MD);
6950   }
6951 
6952   // ms_struct is a request to use the same ABI rules as MSVC.  Check
6953   // whether this class uses any C++ features that are implemented
6954   // completely differently in MSVC, and if so, emit a diagnostic.
6955   // That diagnostic defaults to an error, but we allow projects to
6956   // map it down to a warning (or ignore it).  It's a fairly common
6957   // practice among users of the ms_struct pragma to mass-annotate
6958   // headers, sweeping up a bunch of types that the project doesn't
6959   // really rely on MSVC-compatible layout for.  We must therefore
6960   // support "ms_struct except for C++ stuff" as a secondary ABI.
6961   // Don't emit this diagnostic if the feature was enabled as a
6962   // language option (as opposed to via a pragma or attribute), as
6963   // the option -mms-bitfields otherwise essentially makes it impossible
6964   // to build C++ code, unless this diagnostic is turned off.
6965   if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6966       (Record->isPolymorphic() || Record->getNumBases())) {
6967     Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6968   }
6969 
6970   checkClassLevelDLLAttribute(Record);
6971   checkClassLevelCodeSegAttribute(Record);
6972 
6973   bool ClangABICompat4 =
6974       Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6975   TargetInfo::CallingConvKind CCK =
6976       Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6977   bool CanPass = canPassInRegisters(*this, Record, CCK);
6978 
6979   // Do not change ArgPassingRestrictions if it has already been set to
6980   // APK_CanNeverPassInRegs.
6981   if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6982     Record->setArgPassingRestrictions(CanPass
6983                                           ? RecordDecl::APK_CanPassInRegs
6984                                           : RecordDecl::APK_CannotPassInRegs);
6985 
6986   // If canPassInRegisters returns true despite the record having a non-trivial
6987   // destructor, the record is destructed in the callee. This happens only when
6988   // the record or one of its subobjects has a field annotated with trivial_abi
6989   // or a field qualified with ObjC __strong/__weak.
6990   if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6991     Record->setParamDestroyedInCallee(true);
6992   else if (Record->hasNonTrivialDestructor())
6993     Record->setParamDestroyedInCallee(CanPass);
6994 
6995   if (getLangOpts().ForceEmitVTables) {
6996     // If we want to emit all the vtables, we need to mark it as used.  This
6997     // is especially required for cases like vtable assumption loads.
6998     MarkVTableUsed(Record->getInnerLocStart(), Record);
6999   }
7000 
7001   if (getLangOpts().CUDA) {
7002     if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7003       checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
7004     else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7005       checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
7006   }
7007 }
7008 
7009 /// Look up the special member function that would be called by a special
7010 /// member function for a subobject of class type.
7011 ///
7012 /// \param Class The class type of the subobject.
7013 /// \param CSM The kind of special member function.
7014 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7015 /// \param ConstRHS True if this is a copy operation with a const object
7016 ///        on its RHS, that is, if the argument to the outer special member
7017 ///        function is 'const' and this is not a field marked 'mutable'.
7018 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7019     Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7020     unsigned FieldQuals, bool ConstRHS) {
7021   unsigned LHSQuals = 0;
7022   if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7023     LHSQuals = FieldQuals;
7024 
7025   unsigned RHSQuals = FieldQuals;
7026   if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7027     RHSQuals = 0;
7028   else if (ConstRHS)
7029     RHSQuals |= Qualifiers::Const;
7030 
7031   return S.LookupSpecialMember(Class, CSM,
7032                                RHSQuals & Qualifiers::Const,
7033                                RHSQuals & Qualifiers::Volatile,
7034                                false,
7035                                LHSQuals & Qualifiers::Const,
7036                                LHSQuals & Qualifiers::Volatile);
7037 }
7038 
7039 class Sema::InheritedConstructorInfo {
7040   Sema &S;
7041   SourceLocation UseLoc;
7042 
7043   /// A mapping from the base classes through which the constructor was
7044   /// inherited to the using shadow declaration in that base class (or a null
7045   /// pointer if the constructor was declared in that base class).
7046   llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7047       InheritedFromBases;
7048 
7049 public:
7050   InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7051                            ConstructorUsingShadowDecl *Shadow)
7052       : S(S), UseLoc(UseLoc) {
7053     bool DiagnosedMultipleConstructedBases = false;
7054     CXXRecordDecl *ConstructedBase = nullptr;
7055     BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7056 
7057     // Find the set of such base class subobjects and check that there's a
7058     // unique constructed subobject.
7059     for (auto *D : Shadow->redecls()) {
7060       auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7061       auto *DNominatedBase = DShadow->getNominatedBaseClass();
7062       auto *DConstructedBase = DShadow->getConstructedBaseClass();
7063 
7064       InheritedFromBases.insert(
7065           std::make_pair(DNominatedBase->getCanonicalDecl(),
7066                          DShadow->getNominatedBaseClassShadowDecl()));
7067       if (DShadow->constructsVirtualBase())
7068         InheritedFromBases.insert(
7069             std::make_pair(DConstructedBase->getCanonicalDecl(),
7070                            DShadow->getConstructedBaseClassShadowDecl()));
7071       else
7072         assert(DNominatedBase == DConstructedBase);
7073 
7074       // [class.inhctor.init]p2:
7075       //   If the constructor was inherited from multiple base class subobjects
7076       //   of type B, the program is ill-formed.
7077       if (!ConstructedBase) {
7078         ConstructedBase = DConstructedBase;
7079         ConstructedBaseIntroducer = D->getIntroducer();
7080       } else if (ConstructedBase != DConstructedBase &&
7081                  !Shadow->isInvalidDecl()) {
7082         if (!DiagnosedMultipleConstructedBases) {
7083           S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7084               << Shadow->getTargetDecl();
7085           S.Diag(ConstructedBaseIntroducer->getLocation(),
7086                  diag::note_ambiguous_inherited_constructor_using)
7087               << ConstructedBase;
7088           DiagnosedMultipleConstructedBases = true;
7089         }
7090         S.Diag(D->getIntroducer()->getLocation(),
7091                diag::note_ambiguous_inherited_constructor_using)
7092             << DConstructedBase;
7093       }
7094     }
7095 
7096     if (DiagnosedMultipleConstructedBases)
7097       Shadow->setInvalidDecl();
7098   }
7099 
7100   /// Find the constructor to use for inherited construction of a base class,
7101   /// and whether that base class constructor inherits the constructor from a
7102   /// virtual base class (in which case it won't actually invoke it).
7103   std::pair<CXXConstructorDecl *, bool>
7104   findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7105     auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7106     if (It == InheritedFromBases.end())
7107       return std::make_pair(nullptr, false);
7108 
7109     // This is an intermediary class.
7110     if (It->second)
7111       return std::make_pair(
7112           S.findInheritingConstructor(UseLoc, Ctor, It->second),
7113           It->second->constructsVirtualBase());
7114 
7115     // This is the base class from which the constructor was inherited.
7116     return std::make_pair(Ctor, false);
7117   }
7118 };
7119 
7120 /// Is the special member function which would be selected to perform the
7121 /// specified operation on the specified class type a constexpr constructor?
7122 static bool
7123 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7124                          Sema::CXXSpecialMember CSM, unsigned Quals,
7125                          bool ConstRHS,
7126                          CXXConstructorDecl *InheritedCtor = nullptr,
7127                          Sema::InheritedConstructorInfo *Inherited = nullptr) {
7128   // If we're inheriting a constructor, see if we need to call it for this base
7129   // class.
7130   if (InheritedCtor) {
7131     assert(CSM == Sema::CXXDefaultConstructor);
7132     auto BaseCtor =
7133         Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7134     if (BaseCtor)
7135       return BaseCtor->isConstexpr();
7136   }
7137 
7138   if (CSM == Sema::CXXDefaultConstructor)
7139     return ClassDecl->hasConstexprDefaultConstructor();
7140   if (CSM == Sema::CXXDestructor)
7141     return ClassDecl->hasConstexprDestructor();
7142 
7143   Sema::SpecialMemberOverloadResult SMOR =
7144       lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7145   if (!SMOR.getMethod())
7146     // A constructor we wouldn't select can't be "involved in initializing"
7147     // anything.
7148     return true;
7149   return SMOR.getMethod()->isConstexpr();
7150 }
7151 
7152 /// Determine whether the specified special member function would be constexpr
7153 /// if it were implicitly defined.
7154 static bool defaultedSpecialMemberIsConstexpr(
7155     Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7156     bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7157     Sema::InheritedConstructorInfo *Inherited = nullptr) {
7158   if (!S.getLangOpts().CPlusPlus11)
7159     return false;
7160 
7161   // C++11 [dcl.constexpr]p4:
7162   // In the definition of a constexpr constructor [...]
7163   bool Ctor = true;
7164   switch (CSM) {
7165   case Sema::CXXDefaultConstructor:
7166     if (Inherited)
7167       break;
7168     // Since default constructor lookup is essentially trivial (and cannot
7169     // involve, for instance, template instantiation), we compute whether a
7170     // defaulted default constructor is constexpr directly within CXXRecordDecl.
7171     //
7172     // This is important for performance; we need to know whether the default
7173     // constructor is constexpr to determine whether the type is a literal type.
7174     return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7175 
7176   case Sema::CXXCopyConstructor:
7177   case Sema::CXXMoveConstructor:
7178     // For copy or move constructors, we need to perform overload resolution.
7179     break;
7180 
7181   case Sema::CXXCopyAssignment:
7182   case Sema::CXXMoveAssignment:
7183     if (!S.getLangOpts().CPlusPlus14)
7184       return false;
7185     // In C++1y, we need to perform overload resolution.
7186     Ctor = false;
7187     break;
7188 
7189   case Sema::CXXDestructor:
7190     return ClassDecl->defaultedDestructorIsConstexpr();
7191 
7192   case Sema::CXXInvalid:
7193     return false;
7194   }
7195 
7196   //   -- if the class is a non-empty union, or for each non-empty anonymous
7197   //      union member of a non-union class, exactly one non-static data member
7198   //      shall be initialized; [DR1359]
7199   //
7200   // If we squint, this is guaranteed, since exactly one non-static data member
7201   // will be initialized (if the constructor isn't deleted), we just don't know
7202   // which one.
7203   if (Ctor && ClassDecl->isUnion())
7204     return CSM == Sema::CXXDefaultConstructor
7205                ? ClassDecl->hasInClassInitializer() ||
7206                      !ClassDecl->hasVariantMembers()
7207                : true;
7208 
7209   //   -- the class shall not have any virtual base classes;
7210   if (Ctor && ClassDecl->getNumVBases())
7211     return false;
7212 
7213   // C++1y [class.copy]p26:
7214   //   -- [the class] is a literal type, and
7215   if (!Ctor && !ClassDecl->isLiteral())
7216     return false;
7217 
7218   //   -- every constructor involved in initializing [...] base class
7219   //      sub-objects shall be a constexpr constructor;
7220   //   -- the assignment operator selected to copy/move each direct base
7221   //      class is a constexpr function, and
7222   for (const auto &B : ClassDecl->bases()) {
7223     const RecordType *BaseType = B.getType()->getAs<RecordType>();
7224     if (!BaseType) continue;
7225 
7226     CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7227     if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7228                                   InheritedCtor, Inherited))
7229       return false;
7230   }
7231 
7232   //   -- every constructor involved in initializing non-static data members
7233   //      [...] shall be a constexpr constructor;
7234   //   -- every non-static data member and base class sub-object shall be
7235   //      initialized
7236   //   -- for each non-static data member of X that is of class type (or array
7237   //      thereof), the assignment operator selected to copy/move that member is
7238   //      a constexpr function
7239   for (const auto *F : ClassDecl->fields()) {
7240     if (F->isInvalidDecl())
7241       continue;
7242     if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7243       continue;
7244     QualType BaseType = S.Context.getBaseElementType(F->getType());
7245     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7246       CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7247       if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7248                                     BaseType.getCVRQualifiers(),
7249                                     ConstArg && !F->isMutable()))
7250         return false;
7251     } else if (CSM == Sema::CXXDefaultConstructor) {
7252       return false;
7253     }
7254   }
7255 
7256   // All OK, it's constexpr!
7257   return true;
7258 }
7259 
7260 namespace {
7261 /// RAII object to register a defaulted function as having its exception
7262 /// specification computed.
7263 struct ComputingExceptionSpec {
7264   Sema &S;
7265 
7266   ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7267       : S(S) {
7268     Sema::CodeSynthesisContext Ctx;
7269     Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7270     Ctx.PointOfInstantiation = Loc;
7271     Ctx.Entity = FD;
7272     S.pushCodeSynthesisContext(Ctx);
7273   }
7274   ~ComputingExceptionSpec() {
7275     S.popCodeSynthesisContext();
7276   }
7277 };
7278 }
7279 
7280 static Sema::ImplicitExceptionSpecification
7281 ComputeDefaultedSpecialMemberExceptionSpec(
7282     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7283     Sema::InheritedConstructorInfo *ICI);
7284 
7285 static Sema::ImplicitExceptionSpecification
7286 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7287                                         FunctionDecl *FD,
7288                                         Sema::DefaultedComparisonKind DCK);
7289 
7290 static Sema::ImplicitExceptionSpecification
7291 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7292   auto DFK = S.getDefaultedFunctionKind(FD);
7293   if (DFK.isSpecialMember())
7294     return ComputeDefaultedSpecialMemberExceptionSpec(
7295         S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7296   if (DFK.isComparison())
7297     return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7298                                                    DFK.asComparison());
7299 
7300   auto *CD = cast<CXXConstructorDecl>(FD);
7301   assert(CD->getInheritedConstructor() &&
7302          "only defaulted functions and inherited constructors have implicit "
7303          "exception specs");
7304   Sema::InheritedConstructorInfo ICI(
7305       S, Loc, CD->getInheritedConstructor().getShadowDecl());
7306   return ComputeDefaultedSpecialMemberExceptionSpec(
7307       S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7308 }
7309 
7310 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7311                                                             CXXMethodDecl *MD) {
7312   FunctionProtoType::ExtProtoInfo EPI;
7313 
7314   // Build an exception specification pointing back at this member.
7315   EPI.ExceptionSpec.Type = EST_Unevaluated;
7316   EPI.ExceptionSpec.SourceDecl = MD;
7317 
7318   // Set the calling convention to the default for C++ instance methods.
7319   EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7320       S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7321                                             /*IsCXXMethod=*/true));
7322   return EPI;
7323 }
7324 
7325 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7326   const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7327   if (FPT->getExceptionSpecType() != EST_Unevaluated)
7328     return;
7329 
7330   // Evaluate the exception specification.
7331   auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7332   auto ESI = IES.getExceptionSpec();
7333 
7334   // Update the type of the special member to use it.
7335   UpdateExceptionSpec(FD, ESI);
7336 }
7337 
7338 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7339   assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7340 
7341   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7342   if (!DefKind) {
7343     assert(FD->getDeclContext()->isDependentContext());
7344     return;
7345   }
7346 
7347   if (DefKind.isComparison())
7348     UnusedPrivateFields.clear();
7349 
7350   if (DefKind.isSpecialMember()
7351           ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7352                                                   DefKind.asSpecialMember())
7353           : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7354     FD->setInvalidDecl();
7355 }
7356 
7357 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7358                                                  CXXSpecialMember CSM) {
7359   CXXRecordDecl *RD = MD->getParent();
7360 
7361   assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7362          "not an explicitly-defaulted special member");
7363 
7364   // Defer all checking for special members of a dependent type.
7365   if (RD->isDependentType())
7366     return false;
7367 
7368   // Whether this was the first-declared instance of the constructor.
7369   // This affects whether we implicitly add an exception spec and constexpr.
7370   bool First = MD == MD->getCanonicalDecl();
7371 
7372   bool HadError = false;
7373 
7374   // C++11 [dcl.fct.def.default]p1:
7375   //   A function that is explicitly defaulted shall
7376   //     -- be a special member function [...] (checked elsewhere),
7377   //     -- have the same type (except for ref-qualifiers, and except that a
7378   //        copy operation can take a non-const reference) as an implicit
7379   //        declaration, and
7380   //     -- not have default arguments.
7381   // C++2a changes the second bullet to instead delete the function if it's
7382   // defaulted on its first declaration, unless it's "an assignment operator,
7383   // and its return type differs or its parameter type is not a reference".
7384   bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7385   bool ShouldDeleteForTypeMismatch = false;
7386   unsigned ExpectedParams = 1;
7387   if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7388     ExpectedParams = 0;
7389   if (MD->getNumParams() != ExpectedParams) {
7390     // This checks for default arguments: a copy or move constructor with a
7391     // default argument is classified as a default constructor, and assignment
7392     // operations and destructors can't have default arguments.
7393     Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7394       << CSM << MD->getSourceRange();
7395     HadError = true;
7396   } else if (MD->isVariadic()) {
7397     if (DeleteOnTypeMismatch)
7398       ShouldDeleteForTypeMismatch = true;
7399     else {
7400       Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7401         << CSM << MD->getSourceRange();
7402       HadError = true;
7403     }
7404   }
7405 
7406   const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7407 
7408   bool CanHaveConstParam = false;
7409   if (CSM == CXXCopyConstructor)
7410     CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7411   else if (CSM == CXXCopyAssignment)
7412     CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7413 
7414   QualType ReturnType = Context.VoidTy;
7415   if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7416     // Check for return type matching.
7417     ReturnType = Type->getReturnType();
7418 
7419     QualType DeclType = Context.getTypeDeclType(RD);
7420     DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7421     QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7422 
7423     if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7424       Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7425         << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7426       HadError = true;
7427     }
7428 
7429     // A defaulted special member cannot have cv-qualifiers.
7430     if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7431       if (DeleteOnTypeMismatch)
7432         ShouldDeleteForTypeMismatch = true;
7433       else {
7434         Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7435           << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7436         HadError = true;
7437       }
7438     }
7439   }
7440 
7441   // Check for parameter type matching.
7442   QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7443   bool HasConstParam = false;
7444   if (ExpectedParams && ArgType->isReferenceType()) {
7445     // Argument must be reference to possibly-const T.
7446     QualType ReferentType = ArgType->getPointeeType();
7447     HasConstParam = ReferentType.isConstQualified();
7448 
7449     if (ReferentType.isVolatileQualified()) {
7450       if (DeleteOnTypeMismatch)
7451         ShouldDeleteForTypeMismatch = true;
7452       else {
7453         Diag(MD->getLocation(),
7454              diag::err_defaulted_special_member_volatile_param) << CSM;
7455         HadError = true;
7456       }
7457     }
7458 
7459     if (HasConstParam && !CanHaveConstParam) {
7460       if (DeleteOnTypeMismatch)
7461         ShouldDeleteForTypeMismatch = true;
7462       else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7463         Diag(MD->getLocation(),
7464              diag::err_defaulted_special_member_copy_const_param)
7465           << (CSM == CXXCopyAssignment);
7466         // FIXME: Explain why this special member can't be const.
7467         HadError = true;
7468       } else {
7469         Diag(MD->getLocation(),
7470              diag::err_defaulted_special_member_move_const_param)
7471           << (CSM == CXXMoveAssignment);
7472         HadError = true;
7473       }
7474     }
7475   } else if (ExpectedParams) {
7476     // A copy assignment operator can take its argument by value, but a
7477     // defaulted one cannot.
7478     assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7479     Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7480     HadError = true;
7481   }
7482 
7483   // C++11 [dcl.fct.def.default]p2:
7484   //   An explicitly-defaulted function may be declared constexpr only if it
7485   //   would have been implicitly declared as constexpr,
7486   // Do not apply this rule to members of class templates, since core issue 1358
7487   // makes such functions always instantiate to constexpr functions. For
7488   // functions which cannot be constexpr (for non-constructors in C++11 and for
7489   // destructors in C++14 and C++17), this is checked elsewhere.
7490   //
7491   // FIXME: This should not apply if the member is deleted.
7492   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7493                                                      HasConstParam);
7494   if ((getLangOpts().CPlusPlus20 ||
7495        (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7496                                   : isa<CXXConstructorDecl>(MD))) &&
7497       MD->isConstexpr() && !Constexpr &&
7498       MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7499     Diag(MD->getBeginLoc(), MD->isConsteval()
7500                                 ? diag::err_incorrect_defaulted_consteval
7501                                 : diag::err_incorrect_defaulted_constexpr)
7502         << CSM;
7503     // FIXME: Explain why the special member can't be constexpr.
7504     HadError = true;
7505   }
7506 
7507   if (First) {
7508     // C++2a [dcl.fct.def.default]p3:
7509     //   If a function is explicitly defaulted on its first declaration, it is
7510     //   implicitly considered to be constexpr if the implicit declaration
7511     //   would be.
7512     MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7513                                           ? ConstexprSpecKind::Consteval
7514                                           : ConstexprSpecKind::Constexpr)
7515                                    : ConstexprSpecKind::Unspecified);
7516 
7517     if (!Type->hasExceptionSpec()) {
7518       // C++2a [except.spec]p3:
7519       //   If a declaration of a function does not have a noexcept-specifier
7520       //   [and] is defaulted on its first declaration, [...] the exception
7521       //   specification is as specified below
7522       FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7523       EPI.ExceptionSpec.Type = EST_Unevaluated;
7524       EPI.ExceptionSpec.SourceDecl = MD;
7525       MD->setType(Context.getFunctionType(ReturnType,
7526                                           llvm::makeArrayRef(&ArgType,
7527                                                              ExpectedParams),
7528                                           EPI));
7529     }
7530   }
7531 
7532   if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7533     if (First) {
7534       SetDeclDeleted(MD, MD->getLocation());
7535       if (!inTemplateInstantiation() && !HadError) {
7536         Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7537         if (ShouldDeleteForTypeMismatch) {
7538           Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7539         } else {
7540           ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7541         }
7542       }
7543       if (ShouldDeleteForTypeMismatch && !HadError) {
7544         Diag(MD->getLocation(),
7545              diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7546       }
7547     } else {
7548       // C++11 [dcl.fct.def.default]p4:
7549       //   [For a] user-provided explicitly-defaulted function [...] if such a
7550       //   function is implicitly defined as deleted, the program is ill-formed.
7551       Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7552       assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7553       ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7554       HadError = true;
7555     }
7556   }
7557 
7558   return HadError;
7559 }
7560 
7561 namespace {
7562 /// Helper class for building and checking a defaulted comparison.
7563 ///
7564 /// Defaulted functions are built in two phases:
7565 ///
7566 ///  * First, the set of operations that the function will perform are
7567 ///    identified, and some of them are checked. If any of the checked
7568 ///    operations is invalid in certain ways, the comparison function is
7569 ///    defined as deleted and no body is built.
7570 ///  * Then, if the function is not defined as deleted, the body is built.
7571 ///
7572 /// This is accomplished by performing two visitation steps over the eventual
7573 /// body of the function.
7574 template<typename Derived, typename ResultList, typename Result,
7575          typename Subobject>
7576 class DefaultedComparisonVisitor {
7577 public:
7578   using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7579 
7580   DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7581                              DefaultedComparisonKind DCK)
7582       : S(S), RD(RD), FD(FD), DCK(DCK) {
7583     if (auto *Info = FD->getDefaultedFunctionInfo()) {
7584       // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7585       // UnresolvedSet to avoid this copy.
7586       Fns.assign(Info->getUnqualifiedLookups().begin(),
7587                  Info->getUnqualifiedLookups().end());
7588     }
7589   }
7590 
7591   ResultList visit() {
7592     // The type of an lvalue naming a parameter of this function.
7593     QualType ParamLvalType =
7594         FD->getParamDecl(0)->getType().getNonReferenceType();
7595 
7596     ResultList Results;
7597 
7598     switch (DCK) {
7599     case DefaultedComparisonKind::None:
7600       llvm_unreachable("not a defaulted comparison");
7601 
7602     case DefaultedComparisonKind::Equal:
7603     case DefaultedComparisonKind::ThreeWay:
7604       getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7605       return Results;
7606 
7607     case DefaultedComparisonKind::NotEqual:
7608     case DefaultedComparisonKind::Relational:
7609       Results.add(getDerived().visitExpandedSubobject(
7610           ParamLvalType, getDerived().getCompleteObject()));
7611       return Results;
7612     }
7613     llvm_unreachable("");
7614   }
7615 
7616 protected:
7617   Derived &getDerived() { return static_cast<Derived&>(*this); }
7618 
7619   /// Visit the expanded list of subobjects of the given type, as specified in
7620   /// C++2a [class.compare.default].
7621   ///
7622   /// \return \c true if the ResultList object said we're done, \c false if not.
7623   bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7624                        Qualifiers Quals) {
7625     // C++2a [class.compare.default]p4:
7626     //   The direct base class subobjects of C
7627     for (CXXBaseSpecifier &Base : Record->bases())
7628       if (Results.add(getDerived().visitSubobject(
7629               S.Context.getQualifiedType(Base.getType(), Quals),
7630               getDerived().getBase(&Base))))
7631         return true;
7632 
7633     //   followed by the non-static data members of C
7634     for (FieldDecl *Field : Record->fields()) {
7635       // Recursively expand anonymous structs.
7636       if (Field->isAnonymousStructOrUnion()) {
7637         if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7638                             Quals))
7639           return true;
7640         continue;
7641       }
7642 
7643       // Figure out the type of an lvalue denoting this field.
7644       Qualifiers FieldQuals = Quals;
7645       if (Field->isMutable())
7646         FieldQuals.removeConst();
7647       QualType FieldType =
7648           S.Context.getQualifiedType(Field->getType(), FieldQuals);
7649 
7650       if (Results.add(getDerived().visitSubobject(
7651               FieldType, getDerived().getField(Field))))
7652         return true;
7653     }
7654 
7655     //   form a list of subobjects.
7656     return false;
7657   }
7658 
7659   Result visitSubobject(QualType Type, Subobject Subobj) {
7660     //   In that list, any subobject of array type is recursively expanded
7661     const ArrayType *AT = S.Context.getAsArrayType(Type);
7662     if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7663       return getDerived().visitSubobjectArray(CAT->getElementType(),
7664                                               CAT->getSize(), Subobj);
7665     return getDerived().visitExpandedSubobject(Type, Subobj);
7666   }
7667 
7668   Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7669                              Subobject Subobj) {
7670     return getDerived().visitSubobject(Type, Subobj);
7671   }
7672 
7673 protected:
7674   Sema &S;
7675   CXXRecordDecl *RD;
7676   FunctionDecl *FD;
7677   DefaultedComparisonKind DCK;
7678   UnresolvedSet<16> Fns;
7679 };
7680 
7681 /// Information about a defaulted comparison, as determined by
7682 /// DefaultedComparisonAnalyzer.
7683 struct DefaultedComparisonInfo {
7684   bool Deleted = false;
7685   bool Constexpr = true;
7686   ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7687 
7688   static DefaultedComparisonInfo deleted() {
7689     DefaultedComparisonInfo Deleted;
7690     Deleted.Deleted = true;
7691     return Deleted;
7692   }
7693 
7694   bool add(const DefaultedComparisonInfo &R) {
7695     Deleted |= R.Deleted;
7696     Constexpr &= R.Constexpr;
7697     Category = commonComparisonType(Category, R.Category);
7698     return Deleted;
7699   }
7700 };
7701 
7702 /// An element in the expanded list of subobjects of a defaulted comparison, as
7703 /// specified in C++2a [class.compare.default]p4.
7704 struct DefaultedComparisonSubobject {
7705   enum { CompleteObject, Member, Base } Kind;
7706   NamedDecl *Decl;
7707   SourceLocation Loc;
7708 };
7709 
7710 /// A visitor over the notional body of a defaulted comparison that determines
7711 /// whether that body would be deleted or constexpr.
7712 class DefaultedComparisonAnalyzer
7713     : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7714                                         DefaultedComparisonInfo,
7715                                         DefaultedComparisonInfo,
7716                                         DefaultedComparisonSubobject> {
7717 public:
7718   enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7719 
7720 private:
7721   DiagnosticKind Diagnose;
7722 
7723 public:
7724   using Base = DefaultedComparisonVisitor;
7725   using Result = DefaultedComparisonInfo;
7726   using Subobject = DefaultedComparisonSubobject;
7727 
7728   friend Base;
7729 
7730   DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7731                               DefaultedComparisonKind DCK,
7732                               DiagnosticKind Diagnose = NoDiagnostics)
7733       : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7734 
7735   Result visit() {
7736     if ((DCK == DefaultedComparisonKind::Equal ||
7737          DCK == DefaultedComparisonKind::ThreeWay) &&
7738         RD->hasVariantMembers()) {
7739       // C++2a [class.compare.default]p2 [P2002R0]:
7740       //   A defaulted comparison operator function for class C is defined as
7741       //   deleted if [...] C has variant members.
7742       if (Diagnose == ExplainDeleted) {
7743         S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7744           << FD << RD->isUnion() << RD;
7745       }
7746       return Result::deleted();
7747     }
7748 
7749     return Base::visit();
7750   }
7751 
7752 private:
7753   Subobject getCompleteObject() {
7754     return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7755   }
7756 
7757   Subobject getBase(CXXBaseSpecifier *Base) {
7758     return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7759                      Base->getBaseTypeLoc()};
7760   }
7761 
7762   Subobject getField(FieldDecl *Field) {
7763     return Subobject{Subobject::Member, Field, Field->getLocation()};
7764   }
7765 
7766   Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7767     // C++2a [class.compare.default]p2 [P2002R0]:
7768     //   A defaulted <=> or == operator function for class C is defined as
7769     //   deleted if any non-static data member of C is of reference type
7770     if (Type->isReferenceType()) {
7771       if (Diagnose == ExplainDeleted) {
7772         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7773             << FD << RD;
7774       }
7775       return Result::deleted();
7776     }
7777 
7778     // [...] Let xi be an lvalue denoting the ith element [...]
7779     OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7780     Expr *Args[] = {&Xi, &Xi};
7781 
7782     // All operators start by trying to apply that same operator recursively.
7783     OverloadedOperatorKind OO = FD->getOverloadedOperator();
7784     assert(OO != OO_None && "not an overloaded operator!");
7785     return visitBinaryOperator(OO, Args, Subobj);
7786   }
7787 
7788   Result
7789   visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7790                       Subobject Subobj,
7791                       OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7792     // Note that there is no need to consider rewritten candidates here if
7793     // we've already found there is no viable 'operator<=>' candidate (and are
7794     // considering synthesizing a '<=>' from '==' and '<').
7795     OverloadCandidateSet CandidateSet(
7796         FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7797         OverloadCandidateSet::OperatorRewriteInfo(
7798             OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7799 
7800     /// C++2a [class.compare.default]p1 [P2002R0]:
7801     ///   [...] the defaulted function itself is never a candidate for overload
7802     ///   resolution [...]
7803     CandidateSet.exclude(FD);
7804 
7805     if (Args[0]->getType()->isOverloadableType())
7806       S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7807     else
7808       // FIXME: We determine whether this is a valid expression by checking to
7809       // see if there's a viable builtin operator candidate for it. That isn't
7810       // really what the rules ask us to do, but should give the right results.
7811       S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7812 
7813     Result R;
7814 
7815     OverloadCandidateSet::iterator Best;
7816     switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7817     case OR_Success: {
7818       // C++2a [class.compare.secondary]p2 [P2002R0]:
7819       //   The operator function [...] is defined as deleted if [...] the
7820       //   candidate selected by overload resolution is not a rewritten
7821       //   candidate.
7822       if ((DCK == DefaultedComparisonKind::NotEqual ||
7823            DCK == DefaultedComparisonKind::Relational) &&
7824           !Best->RewriteKind) {
7825         if (Diagnose == ExplainDeleted) {
7826           if (Best->Function) {
7827             S.Diag(Best->Function->getLocation(),
7828                    diag::note_defaulted_comparison_not_rewritten_callee)
7829                 << FD;
7830           } else {
7831             assert(Best->Conversions.size() == 2 &&
7832                    Best->Conversions[0].isUserDefined() &&
7833                    "non-user-defined conversion from class to built-in "
7834                    "comparison");
7835             S.Diag(Best->Conversions[0]
7836                        .UserDefined.FoundConversionFunction.getDecl()
7837                        ->getLocation(),
7838                    diag::note_defaulted_comparison_not_rewritten_conversion)
7839                 << FD;
7840           }
7841         }
7842         return Result::deleted();
7843       }
7844 
7845       // Throughout C++2a [class.compare]: if overload resolution does not
7846       // result in a usable function, the candidate function is defined as
7847       // deleted. This requires that we selected an accessible function.
7848       //
7849       // Note that this only considers the access of the function when named
7850       // within the type of the subobject, and not the access path for any
7851       // derived-to-base conversion.
7852       CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7853       if (ArgClass && Best->FoundDecl.getDecl() &&
7854           Best->FoundDecl.getDecl()->isCXXClassMember()) {
7855         QualType ObjectType = Subobj.Kind == Subobject::Member
7856                                   ? Args[0]->getType()
7857                                   : S.Context.getRecordType(RD);
7858         if (!S.isMemberAccessibleForDeletion(
7859                 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7860                 Diagnose == ExplainDeleted
7861                     ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7862                           << FD << Subobj.Kind << Subobj.Decl
7863                     : S.PDiag()))
7864           return Result::deleted();
7865       }
7866 
7867       bool NeedsDeducing =
7868           OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7869 
7870       if (FunctionDecl *BestFD = Best->Function) {
7871         // C++2a [class.compare.default]p3 [P2002R0]:
7872         //   A defaulted comparison function is constexpr-compatible if
7873         //   [...] no overlod resolution performed [...] results in a
7874         //   non-constexpr function.
7875         assert(!BestFD->isDeleted() && "wrong overload resolution result");
7876         // If it's not constexpr, explain why not.
7877         if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7878           if (Subobj.Kind != Subobject::CompleteObject)
7879             S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7880               << Subobj.Kind << Subobj.Decl;
7881           S.Diag(BestFD->getLocation(),
7882                  diag::note_defaulted_comparison_not_constexpr_here);
7883           // Bail out after explaining; we don't want any more notes.
7884           return Result::deleted();
7885         }
7886         R.Constexpr &= BestFD->isConstexpr();
7887 
7888         if (NeedsDeducing) {
7889           // If any callee has an undeduced return type, deduce it now.
7890           // FIXME: It's not clear how a failure here should be handled. For
7891           // now, we produce an eager diagnostic, because that is forward
7892           // compatible with most (all?) other reasonable options.
7893           if (BestFD->getReturnType()->isUndeducedType() &&
7894               S.DeduceReturnType(BestFD, FD->getLocation(),
7895                                  /*Diagnose=*/false)) {
7896             // Don't produce a duplicate error when asked to explain why the
7897             // comparison is deleted: we diagnosed that when initially checking
7898             // the defaulted operator.
7899             if (Diagnose == NoDiagnostics) {
7900               S.Diag(
7901                   FD->getLocation(),
7902                   diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7903                   << Subobj.Kind << Subobj.Decl;
7904               S.Diag(
7905                   Subobj.Loc,
7906                   diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7907                   << Subobj.Kind << Subobj.Decl;
7908               S.Diag(BestFD->getLocation(),
7909                      diag::note_defaulted_comparison_cannot_deduce_callee)
7910                   << Subobj.Kind << Subobj.Decl;
7911             }
7912             return Result::deleted();
7913           }
7914           auto *Info = S.Context.CompCategories.lookupInfoForType(
7915               BestFD->getCallResultType());
7916           if (!Info) {
7917             if (Diagnose == ExplainDeleted) {
7918               S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7919                   << Subobj.Kind << Subobj.Decl
7920                   << BestFD->getCallResultType().withoutLocalFastQualifiers();
7921               S.Diag(BestFD->getLocation(),
7922                      diag::note_defaulted_comparison_cannot_deduce_callee)
7923                   << Subobj.Kind << Subobj.Decl;
7924             }
7925             return Result::deleted();
7926           }
7927           R.Category = Info->Kind;
7928         }
7929       } else {
7930         QualType T = Best->BuiltinParamTypes[0];
7931         assert(T == Best->BuiltinParamTypes[1] &&
7932                "builtin comparison for different types?");
7933         assert(Best->BuiltinParamTypes[2].isNull() &&
7934                "invalid builtin comparison");
7935 
7936         if (NeedsDeducing) {
7937           Optional<ComparisonCategoryType> Cat =
7938               getComparisonCategoryForBuiltinCmp(T);
7939           assert(Cat && "no category for builtin comparison?");
7940           R.Category = *Cat;
7941         }
7942       }
7943 
7944       // Note that we might be rewriting to a different operator. That call is
7945       // not considered until we come to actually build the comparison function.
7946       break;
7947     }
7948 
7949     case OR_Ambiguous:
7950       if (Diagnose == ExplainDeleted) {
7951         unsigned Kind = 0;
7952         if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7953           Kind = OO == OO_EqualEqual ? 1 : 2;
7954         CandidateSet.NoteCandidates(
7955             PartialDiagnosticAt(
7956                 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7957                                 << FD << Kind << Subobj.Kind << Subobj.Decl),
7958             S, OCD_AmbiguousCandidates, Args);
7959       }
7960       R = Result::deleted();
7961       break;
7962 
7963     case OR_Deleted:
7964       if (Diagnose == ExplainDeleted) {
7965         if ((DCK == DefaultedComparisonKind::NotEqual ||
7966              DCK == DefaultedComparisonKind::Relational) &&
7967             !Best->RewriteKind) {
7968           S.Diag(Best->Function->getLocation(),
7969                  diag::note_defaulted_comparison_not_rewritten_callee)
7970               << FD;
7971         } else {
7972           S.Diag(Subobj.Loc,
7973                  diag::note_defaulted_comparison_calls_deleted)
7974               << FD << Subobj.Kind << Subobj.Decl;
7975           S.NoteDeletedFunction(Best->Function);
7976         }
7977       }
7978       R = Result::deleted();
7979       break;
7980 
7981     case OR_No_Viable_Function:
7982       // If there's no usable candidate, we're done unless we can rewrite a
7983       // '<=>' in terms of '==' and '<'.
7984       if (OO == OO_Spaceship &&
7985           S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7986         // For any kind of comparison category return type, we need a usable
7987         // '==' and a usable '<'.
7988         if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7989                                        &CandidateSet)))
7990           R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7991         break;
7992       }
7993 
7994       if (Diagnose == ExplainDeleted) {
7995         S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7996             << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl;
7997 
7998         // For a three-way comparison, list both the candidates for the
7999         // original operator and the candidates for the synthesized operator.
8000         if (SpaceshipCandidates) {
8001           SpaceshipCandidates->NoteCandidates(
8002               S, Args,
8003               SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
8004                                                       Args, FD->getLocation()));
8005           S.Diag(Subobj.Loc,
8006                  diag::note_defaulted_comparison_no_viable_function_synthesized)
8007               << (OO == OO_EqualEqual ? 0 : 1);
8008         }
8009 
8010         CandidateSet.NoteCandidates(
8011             S, Args,
8012             CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
8013                                             FD->getLocation()));
8014       }
8015       R = Result::deleted();
8016       break;
8017     }
8018 
8019     return R;
8020   }
8021 };
8022 
8023 /// A list of statements.
8024 struct StmtListResult {
8025   bool IsInvalid = false;
8026   llvm::SmallVector<Stmt*, 16> Stmts;
8027 
8028   bool add(const StmtResult &S) {
8029     IsInvalid |= S.isInvalid();
8030     if (IsInvalid)
8031       return true;
8032     Stmts.push_back(S.get());
8033     return false;
8034   }
8035 };
8036 
8037 /// A visitor over the notional body of a defaulted comparison that synthesizes
8038 /// the actual body.
8039 class DefaultedComparisonSynthesizer
8040     : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8041                                         StmtListResult, StmtResult,
8042                                         std::pair<ExprResult, ExprResult>> {
8043   SourceLocation Loc;
8044   unsigned ArrayDepth = 0;
8045 
8046 public:
8047   using Base = DefaultedComparisonVisitor;
8048   using ExprPair = std::pair<ExprResult, ExprResult>;
8049 
8050   friend Base;
8051 
8052   DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8053                                  DefaultedComparisonKind DCK,
8054                                  SourceLocation BodyLoc)
8055       : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8056 
8057   /// Build a suitable function body for this defaulted comparison operator.
8058   StmtResult build() {
8059     Sema::CompoundScopeRAII CompoundScope(S);
8060 
8061     StmtListResult Stmts = visit();
8062     if (Stmts.IsInvalid)
8063       return StmtError();
8064 
8065     ExprResult RetVal;
8066     switch (DCK) {
8067     case DefaultedComparisonKind::None:
8068       llvm_unreachable("not a defaulted comparison");
8069 
8070     case DefaultedComparisonKind::Equal: {
8071       // C++2a [class.eq]p3:
8072       //   [...] compar[e] the corresponding elements [...] until the first
8073       //   index i where xi == yi yields [...] false. If no such index exists,
8074       //   V is true. Otherwise, V is false.
8075       //
8076       // Join the comparisons with '&&'s and return the result. Use a right
8077       // fold (traversing the conditions right-to-left), because that
8078       // short-circuits more naturally.
8079       auto OldStmts = std::move(Stmts.Stmts);
8080       Stmts.Stmts.clear();
8081       ExprResult CmpSoFar;
8082       // Finish a particular comparison chain.
8083       auto FinishCmp = [&] {
8084         if (Expr *Prior = CmpSoFar.get()) {
8085           // Convert the last expression to 'return ...;'
8086           if (RetVal.isUnset() && Stmts.Stmts.empty())
8087             RetVal = CmpSoFar;
8088           // Convert any prior comparison to 'if (!(...)) return false;'
8089           else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8090             return true;
8091           CmpSoFar = ExprResult();
8092         }
8093         return false;
8094       };
8095       for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8096         Expr *E = dyn_cast<Expr>(EAsStmt);
8097         if (!E) {
8098           // Found an array comparison.
8099           if (FinishCmp() || Stmts.add(EAsStmt))
8100             return StmtError();
8101           continue;
8102         }
8103 
8104         if (CmpSoFar.isUnset()) {
8105           CmpSoFar = E;
8106           continue;
8107         }
8108         CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8109         if (CmpSoFar.isInvalid())
8110           return StmtError();
8111       }
8112       if (FinishCmp())
8113         return StmtError();
8114       std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8115       //   If no such index exists, V is true.
8116       if (RetVal.isUnset())
8117         RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8118       break;
8119     }
8120 
8121     case DefaultedComparisonKind::ThreeWay: {
8122       // Per C++2a [class.spaceship]p3, as a fallback add:
8123       // return static_cast<R>(std::strong_ordering::equal);
8124       QualType StrongOrdering = S.CheckComparisonCategoryType(
8125           ComparisonCategoryType::StrongOrdering, Loc,
8126           Sema::ComparisonCategoryUsage::DefaultedOperator);
8127       if (StrongOrdering.isNull())
8128         return StmtError();
8129       VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8130                              .getValueInfo(ComparisonCategoryResult::Equal)
8131                              ->VD;
8132       RetVal = getDecl(EqualVD);
8133       if (RetVal.isInvalid())
8134         return StmtError();
8135       RetVal = buildStaticCastToR(RetVal.get());
8136       break;
8137     }
8138 
8139     case DefaultedComparisonKind::NotEqual:
8140     case DefaultedComparisonKind::Relational:
8141       RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8142       break;
8143     }
8144 
8145     // Build the final return statement.
8146     if (RetVal.isInvalid())
8147       return StmtError();
8148     StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8149     if (ReturnStmt.isInvalid())
8150       return StmtError();
8151     Stmts.Stmts.push_back(ReturnStmt.get());
8152 
8153     return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8154   }
8155 
8156 private:
8157   ExprResult getDecl(ValueDecl *VD) {
8158     return S.BuildDeclarationNameExpr(
8159         CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8160   }
8161 
8162   ExprResult getParam(unsigned I) {
8163     ParmVarDecl *PD = FD->getParamDecl(I);
8164     return getDecl(PD);
8165   }
8166 
8167   ExprPair getCompleteObject() {
8168     unsigned Param = 0;
8169     ExprResult LHS;
8170     if (isa<CXXMethodDecl>(FD)) {
8171       // LHS is '*this'.
8172       LHS = S.ActOnCXXThis(Loc);
8173       if (!LHS.isInvalid())
8174         LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8175     } else {
8176       LHS = getParam(Param++);
8177     }
8178     ExprResult RHS = getParam(Param++);
8179     assert(Param == FD->getNumParams());
8180     return {LHS, RHS};
8181   }
8182 
8183   ExprPair getBase(CXXBaseSpecifier *Base) {
8184     ExprPair Obj = getCompleteObject();
8185     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8186       return {ExprError(), ExprError()};
8187     CXXCastPath Path = {Base};
8188     return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8189                                 CK_DerivedToBase, VK_LValue, &Path),
8190             S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8191                                 CK_DerivedToBase, VK_LValue, &Path)};
8192   }
8193 
8194   ExprPair getField(FieldDecl *Field) {
8195     ExprPair Obj = getCompleteObject();
8196     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8197       return {ExprError(), ExprError()};
8198 
8199     DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8200     DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8201     return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8202                                       CXXScopeSpec(), Field, Found, NameInfo),
8203             S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8204                                       CXXScopeSpec(), Field, Found, NameInfo)};
8205   }
8206 
8207   // FIXME: When expanding a subobject, register a note in the code synthesis
8208   // stack to say which subobject we're comparing.
8209 
8210   StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8211     if (Cond.isInvalid())
8212       return StmtError();
8213 
8214     ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8215     if (NotCond.isInvalid())
8216       return StmtError();
8217 
8218     ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8219     assert(!False.isInvalid() && "should never fail");
8220     StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8221     if (ReturnFalse.isInvalid())
8222       return StmtError();
8223 
8224     return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr,
8225                          S.ActOnCondition(nullptr, Loc, NotCond.get(),
8226                                           Sema::ConditionKind::Boolean),
8227                          Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8228   }
8229 
8230   StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8231                                  ExprPair Subobj) {
8232     QualType SizeType = S.Context.getSizeType();
8233     Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8234 
8235     // Build 'size_t i$n = 0'.
8236     IdentifierInfo *IterationVarName = nullptr;
8237     {
8238       SmallString<8> Str;
8239       llvm::raw_svector_ostream OS(Str);
8240       OS << "i" << ArrayDepth;
8241       IterationVarName = &S.Context.Idents.get(OS.str());
8242     }
8243     VarDecl *IterationVar = VarDecl::Create(
8244         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8245         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8246     llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8247     IterationVar->setInit(
8248         IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8249     Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8250 
8251     auto IterRef = [&] {
8252       ExprResult Ref = S.BuildDeclarationNameExpr(
8253           CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8254           IterationVar);
8255       assert(!Ref.isInvalid() && "can't reference our own variable?");
8256       return Ref.get();
8257     };
8258 
8259     // Build 'i$n != Size'.
8260     ExprResult Cond = S.CreateBuiltinBinOp(
8261         Loc, BO_NE, IterRef(),
8262         IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8263     assert(!Cond.isInvalid() && "should never fail");
8264 
8265     // Build '++i$n'.
8266     ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8267     assert(!Inc.isInvalid() && "should never fail");
8268 
8269     // Build 'a[i$n]' and 'b[i$n]'.
8270     auto Index = [&](ExprResult E) {
8271       if (E.isInvalid())
8272         return ExprError();
8273       return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8274     };
8275     Subobj.first = Index(Subobj.first);
8276     Subobj.second = Index(Subobj.second);
8277 
8278     // Compare the array elements.
8279     ++ArrayDepth;
8280     StmtResult Substmt = visitSubobject(Type, Subobj);
8281     --ArrayDepth;
8282 
8283     if (Substmt.isInvalid())
8284       return StmtError();
8285 
8286     // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8287     // For outer levels or for an 'operator<=>' we already have a suitable
8288     // statement that returns as necessary.
8289     if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8290       assert(DCK == DefaultedComparisonKind::Equal &&
8291              "should have non-expression statement");
8292       Substmt = buildIfNotCondReturnFalse(ElemCmp);
8293       if (Substmt.isInvalid())
8294         return StmtError();
8295     }
8296 
8297     // Build 'for (...) ...'
8298     return S.ActOnForStmt(Loc, Loc, Init,
8299                           S.ActOnCondition(nullptr, Loc, Cond.get(),
8300                                            Sema::ConditionKind::Boolean),
8301                           S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8302                           Substmt.get());
8303   }
8304 
8305   StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8306     if (Obj.first.isInvalid() || Obj.second.isInvalid())
8307       return StmtError();
8308 
8309     OverloadedOperatorKind OO = FD->getOverloadedOperator();
8310     BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8311     ExprResult Op;
8312     if (Type->isOverloadableType())
8313       Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8314                                    Obj.second.get(), /*PerformADL=*/true,
8315                                    /*AllowRewrittenCandidates=*/true, FD);
8316     else
8317       Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8318     if (Op.isInvalid())
8319       return StmtError();
8320 
8321     switch (DCK) {
8322     case DefaultedComparisonKind::None:
8323       llvm_unreachable("not a defaulted comparison");
8324 
8325     case DefaultedComparisonKind::Equal:
8326       // Per C++2a [class.eq]p2, each comparison is individually contextually
8327       // converted to bool.
8328       Op = S.PerformContextuallyConvertToBool(Op.get());
8329       if (Op.isInvalid())
8330         return StmtError();
8331       return Op.get();
8332 
8333     case DefaultedComparisonKind::ThreeWay: {
8334       // Per C++2a [class.spaceship]p3, form:
8335       //   if (R cmp = static_cast<R>(op); cmp != 0)
8336       //     return cmp;
8337       QualType R = FD->getReturnType();
8338       Op = buildStaticCastToR(Op.get());
8339       if (Op.isInvalid())
8340         return StmtError();
8341 
8342       // R cmp = ...;
8343       IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8344       VarDecl *VD =
8345           VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8346                           S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8347       S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8348       Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8349 
8350       // cmp != 0
8351       ExprResult VDRef = getDecl(VD);
8352       if (VDRef.isInvalid())
8353         return StmtError();
8354       llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8355       Expr *Zero =
8356           IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8357       ExprResult Comp;
8358       if (VDRef.get()->getType()->isOverloadableType())
8359         Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8360                                        true, FD);
8361       else
8362         Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8363       if (Comp.isInvalid())
8364         return StmtError();
8365       Sema::ConditionResult Cond = S.ActOnCondition(
8366           nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8367       if (Cond.isInvalid())
8368         return StmtError();
8369 
8370       // return cmp;
8371       VDRef = getDecl(VD);
8372       if (VDRef.isInvalid())
8373         return StmtError();
8374       StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8375       if (ReturnStmt.isInvalid())
8376         return StmtError();
8377 
8378       // if (...)
8379       return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond,
8380                            Loc, ReturnStmt.get(),
8381                            /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8382     }
8383 
8384     case DefaultedComparisonKind::NotEqual:
8385     case DefaultedComparisonKind::Relational:
8386       // C++2a [class.compare.secondary]p2:
8387       //   Otherwise, the operator function yields x @ y.
8388       return Op.get();
8389     }
8390     llvm_unreachable("");
8391   }
8392 
8393   /// Build "static_cast<R>(E)".
8394   ExprResult buildStaticCastToR(Expr *E) {
8395     QualType R = FD->getReturnType();
8396     assert(!R->isUndeducedType() && "type should have been deduced already");
8397 
8398     // Don't bother forming a no-op cast in the common case.
8399     if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8400       return E;
8401     return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8402                                S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8403                                SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8404   }
8405 };
8406 }
8407 
8408 /// Perform the unqualified lookups that might be needed to form a defaulted
8409 /// comparison function for the given operator.
8410 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8411                                                   UnresolvedSetImpl &Operators,
8412                                                   OverloadedOperatorKind Op) {
8413   auto Lookup = [&](OverloadedOperatorKind OO) {
8414     Self.LookupOverloadedOperatorName(OO, S, Operators);
8415   };
8416 
8417   // Every defaulted operator looks up itself.
8418   Lookup(Op);
8419   // ... and the rewritten form of itself, if any.
8420   if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8421     Lookup(ExtraOp);
8422 
8423   // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8424   // synthesize a three-way comparison from '<' and '=='. In a dependent
8425   // context, we also need to look up '==' in case we implicitly declare a
8426   // defaulted 'operator=='.
8427   if (Op == OO_Spaceship) {
8428     Lookup(OO_ExclaimEqual);
8429     Lookup(OO_Less);
8430     Lookup(OO_EqualEqual);
8431   }
8432 }
8433 
8434 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8435                                               DefaultedComparisonKind DCK) {
8436   assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8437 
8438   // Perform any unqualified lookups we're going to need to default this
8439   // function.
8440   if (S) {
8441     UnresolvedSet<32> Operators;
8442     lookupOperatorsForDefaultedComparison(*this, S, Operators,
8443                                           FD->getOverloadedOperator());
8444     FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8445         Context, Operators.pairs()));
8446   }
8447 
8448   // C++2a [class.compare.default]p1:
8449   //   A defaulted comparison operator function for some class C shall be a
8450   //   non-template function declared in the member-specification of C that is
8451   //    -- a non-static const member of C having one parameter of type
8452   //       const C&, or
8453   //    -- a friend of C having two parameters of type const C& or two
8454   //       parameters of type C.
8455 
8456   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8457   bool IsMethod = isa<CXXMethodDecl>(FD);
8458   if (IsMethod) {
8459     auto *MD = cast<CXXMethodDecl>(FD);
8460     assert(!MD->isStatic() && "comparison function cannot be a static member");
8461 
8462     // If we're out-of-class, this is the class we're comparing.
8463     if (!RD)
8464       RD = MD->getParent();
8465 
8466     if (!MD->isConst()) {
8467       SourceLocation InsertLoc;
8468       if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8469         InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8470       // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8471       // corresponding defaulted 'operator<=>' already.
8472       if (!MD->isImplicit()) {
8473         Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8474             << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8475       }
8476 
8477       // Add the 'const' to the type to recover.
8478       const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8479       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8480       EPI.TypeQuals.addConst();
8481       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8482                                           FPT->getParamTypes(), EPI));
8483     }
8484   }
8485 
8486   if (FD->getNumParams() != (IsMethod ? 1 : 2)) {
8487     // Let's not worry about using a variadic template pack here -- who would do
8488     // such a thing?
8489     Diag(FD->getLocation(), diag::err_defaulted_comparison_num_args)
8490         << int(IsMethod) << int(DCK);
8491     return true;
8492   }
8493 
8494   const ParmVarDecl *KnownParm = nullptr;
8495   for (const ParmVarDecl *Param : FD->parameters()) {
8496     QualType ParmTy = Param->getType();
8497     if (ParmTy->isDependentType())
8498       continue;
8499     if (!KnownParm) {
8500       auto CTy = ParmTy;
8501       // Is it `T const &`?
8502       bool Ok = !IsMethod;
8503       QualType ExpectedTy;
8504       if (RD)
8505         ExpectedTy = Context.getRecordType(RD);
8506       if (auto *Ref = CTy->getAs<ReferenceType>()) {
8507         CTy = Ref->getPointeeType();
8508         if (RD)
8509           ExpectedTy.addConst();
8510         Ok = true;
8511       }
8512 
8513       // Is T a class?
8514       if (!Ok) {
8515       } else if (RD) {
8516         if (!RD->isDependentType() && !Context.hasSameType(CTy, ExpectedTy))
8517           Ok = false;
8518       } else if (auto *CRD = CTy->getAsRecordDecl()) {
8519         RD = cast<CXXRecordDecl>(CRD);
8520       } else {
8521         Ok = false;
8522       }
8523 
8524       if (Ok) {
8525         KnownParm = Param;
8526       } else {
8527         // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8528         // corresponding defaulted 'operator<=>' already.
8529         if (!FD->isImplicit()) {
8530           if (RD) {
8531             QualType PlainTy = Context.getRecordType(RD);
8532             QualType RefTy =
8533                 Context.getLValueReferenceType(PlainTy.withConst());
8534             Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8535                 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
8536                 << Param->getSourceRange();
8537           } else {
8538             assert(!IsMethod && "should know expected type for method");
8539             Diag(FD->getLocation(),
8540                  diag::err_defaulted_comparison_param_unknown)
8541                 << int(DCK) << ParmTy << Param->getSourceRange();
8542           }
8543         }
8544         return true;
8545       }
8546     } else if (!Context.hasSameType(KnownParm->getType(), ParmTy)) {
8547       Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8548           << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
8549           << ParmTy << Param->getSourceRange();
8550       return true;
8551     }
8552   }
8553 
8554   assert(RD && "must have determined class");
8555   if (IsMethod) {
8556   } else if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
8557     // In-class, must be a friend decl.
8558     assert(FD->getFriendObjectKind() && "expected a friend declaration");
8559   } else {
8560     // Out of class, require the defaulted comparison to be a friend (of a
8561     // complete type).
8562     if (RequireCompleteType(FD->getLocation(), Context.getRecordType(RD),
8563                             diag::err_defaulted_comparison_not_friend, int(DCK),
8564                             int(1)))
8565       return true;
8566 
8567     if (llvm::find_if(RD->friends(), [&](const FriendDecl *F) {
8568           return FD->getCanonicalDecl() ==
8569                  F->getFriendDecl()->getCanonicalDecl();
8570         }) == RD->friends().end()) {
8571       Diag(FD->getLocation(), diag::err_defaulted_comparison_not_friend)
8572           << int(DCK) << int(0) << RD;
8573       Diag(RD->getCanonicalDecl()->getLocation(), diag::note_declared_at);
8574       return true;
8575     }
8576   }
8577 
8578   // C++2a [class.eq]p1, [class.rel]p1:
8579   //   A [defaulted comparison other than <=>] shall have a declared return
8580   //   type bool.
8581   if (DCK != DefaultedComparisonKind::ThreeWay &&
8582       !FD->getDeclaredReturnType()->isDependentType() &&
8583       !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8584     Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8585         << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8586         << FD->getReturnTypeSourceRange();
8587     return true;
8588   }
8589   // C++2a [class.spaceship]p2 [P2002R0]:
8590   //   Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8591   //   R shall not contain a placeholder type.
8592   if (DCK == DefaultedComparisonKind::ThreeWay &&
8593       FD->getDeclaredReturnType()->getContainedDeducedType() &&
8594       !Context.hasSameType(FD->getDeclaredReturnType(),
8595                            Context.getAutoDeductType())) {
8596     Diag(FD->getLocation(),
8597          diag::err_defaulted_comparison_deduced_return_type_not_auto)
8598         << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8599         << FD->getReturnTypeSourceRange();
8600     return true;
8601   }
8602 
8603   // For a defaulted function in a dependent class, defer all remaining checks
8604   // until instantiation.
8605   if (RD->isDependentType())
8606     return false;
8607 
8608   // Determine whether the function should be defined as deleted.
8609   DefaultedComparisonInfo Info =
8610       DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8611 
8612   bool First = FD == FD->getCanonicalDecl();
8613 
8614   // If we want to delete the function, then do so; there's nothing else to
8615   // check in that case.
8616   if (Info.Deleted) {
8617     if (!First) {
8618       // C++11 [dcl.fct.def.default]p4:
8619       //   [For a] user-provided explicitly-defaulted function [...] if such a
8620       //   function is implicitly defined as deleted, the program is ill-formed.
8621       //
8622       // This is really just a consequence of the general rule that you can
8623       // only delete a function on its first declaration.
8624       Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8625           << FD->isImplicit() << (int)DCK;
8626       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8627                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8628           .visit();
8629       return true;
8630     }
8631 
8632     SetDeclDeleted(FD, FD->getLocation());
8633     if (!inTemplateInstantiation() && !FD->isImplicit()) {
8634       Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8635           << (int)DCK;
8636       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8637                                   DefaultedComparisonAnalyzer::ExplainDeleted)
8638           .visit();
8639     }
8640     return false;
8641   }
8642 
8643   // C++2a [class.spaceship]p2:
8644   //   The return type is deduced as the common comparison type of R0, R1, ...
8645   if (DCK == DefaultedComparisonKind::ThreeWay &&
8646       FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8647     SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8648     if (RetLoc.isInvalid())
8649       RetLoc = FD->getBeginLoc();
8650     // FIXME: Should we really care whether we have the complete type and the
8651     // 'enumerator' constants here? A forward declaration seems sufficient.
8652     QualType Cat = CheckComparisonCategoryType(
8653         Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8654     if (Cat.isNull())
8655       return true;
8656     Context.adjustDeducedFunctionResultType(
8657         FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8658   }
8659 
8660   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8661   //   An explicitly-defaulted function that is not defined as deleted may be
8662   //   declared constexpr or consteval only if it is constexpr-compatible.
8663   // C++2a [class.compare.default]p3 [P2002R0]:
8664   //   A defaulted comparison function is constexpr-compatible if it satisfies
8665   //   the requirements for a constexpr function [...]
8666   // The only relevant requirements are that the parameter and return types are
8667   // literal types. The remaining conditions are checked by the analyzer.
8668   if (FD->isConstexpr()) {
8669     if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8670         CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8671         !Info.Constexpr) {
8672       Diag(FD->getBeginLoc(),
8673            diag::err_incorrect_defaulted_comparison_constexpr)
8674           << FD->isImplicit() << (int)DCK << FD->isConsteval();
8675       DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8676                                   DefaultedComparisonAnalyzer::ExplainConstexpr)
8677           .visit();
8678     }
8679   }
8680 
8681   // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8682   //   If a constexpr-compatible function is explicitly defaulted on its first
8683   //   declaration, it is implicitly considered to be constexpr.
8684   // FIXME: Only applying this to the first declaration seems problematic, as
8685   // simple reorderings can affect the meaning of the program.
8686   if (First && !FD->isConstexpr() && Info.Constexpr)
8687     FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8688 
8689   // C++2a [except.spec]p3:
8690   //   If a declaration of a function does not have a noexcept-specifier
8691   //   [and] is defaulted on its first declaration, [...] the exception
8692   //   specification is as specified below
8693   if (FD->getExceptionSpecType() == EST_None) {
8694     auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8695     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8696     EPI.ExceptionSpec.Type = EST_Unevaluated;
8697     EPI.ExceptionSpec.SourceDecl = FD;
8698     FD->setType(Context.getFunctionType(FPT->getReturnType(),
8699                                         FPT->getParamTypes(), EPI));
8700   }
8701 
8702   return false;
8703 }
8704 
8705 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8706                                              FunctionDecl *Spaceship) {
8707   Sema::CodeSynthesisContext Ctx;
8708   Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8709   Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8710   Ctx.Entity = Spaceship;
8711   pushCodeSynthesisContext(Ctx);
8712 
8713   if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8714     EqualEqual->setImplicit();
8715 
8716   popCodeSynthesisContext();
8717 }
8718 
8719 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8720                                      DefaultedComparisonKind DCK) {
8721   assert(FD->isDefaulted() && !FD->isDeleted() &&
8722          !FD->doesThisDeclarationHaveABody());
8723   if (FD->willHaveBody() || FD->isInvalidDecl())
8724     return;
8725 
8726   SynthesizedFunctionScope Scope(*this, FD);
8727 
8728   // Add a context note for diagnostics produced after this point.
8729   Scope.addContextNote(UseLoc);
8730 
8731   {
8732     // Build and set up the function body.
8733     // The first parameter has type maybe-ref-to maybe-const T, use that to get
8734     // the type of the class being compared.
8735     auto PT = FD->getParamDecl(0)->getType();
8736     CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
8737     SourceLocation BodyLoc =
8738         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8739     StmtResult Body =
8740         DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8741     if (Body.isInvalid()) {
8742       FD->setInvalidDecl();
8743       return;
8744     }
8745     FD->setBody(Body.get());
8746     FD->markUsed(Context);
8747   }
8748 
8749   // The exception specification is needed because we are defining the
8750   // function. Note that this will reuse the body we just built.
8751   ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8752 
8753   if (ASTMutationListener *L = getASTMutationListener())
8754     L->CompletedImplicitDefinition(FD);
8755 }
8756 
8757 static Sema::ImplicitExceptionSpecification
8758 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8759                                         FunctionDecl *FD,
8760                                         Sema::DefaultedComparisonKind DCK) {
8761   ComputingExceptionSpec CES(S, FD, Loc);
8762   Sema::ImplicitExceptionSpecification ExceptSpec(S);
8763 
8764   if (FD->isInvalidDecl())
8765     return ExceptSpec;
8766 
8767   // The common case is that we just defined the comparison function. In that
8768   // case, just look at whether the body can throw.
8769   if (FD->hasBody()) {
8770     ExceptSpec.CalledStmt(FD->getBody());
8771   } else {
8772     // Otherwise, build a body so we can check it. This should ideally only
8773     // happen when we're not actually marking the function referenced. (This is
8774     // only really important for efficiency: we don't want to build and throw
8775     // away bodies for comparison functions more than we strictly need to.)
8776 
8777     // Pretend to synthesize the function body in an unevaluated context.
8778     // Note that we can't actually just go ahead and define the function here:
8779     // we are not permitted to mark its callees as referenced.
8780     Sema::SynthesizedFunctionScope Scope(S, FD);
8781     EnterExpressionEvaluationContext Context(
8782         S, Sema::ExpressionEvaluationContext::Unevaluated);
8783 
8784     CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8785     SourceLocation BodyLoc =
8786         FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8787     StmtResult Body =
8788         DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8789     if (!Body.isInvalid())
8790       ExceptSpec.CalledStmt(Body.get());
8791 
8792     // FIXME: Can we hold onto this body and just transform it to potentially
8793     // evaluated when we're asked to define the function rather than rebuilding
8794     // it? Either that, or we should only build the bits of the body that we
8795     // need (the expressions, not the statements).
8796   }
8797 
8798   return ExceptSpec;
8799 }
8800 
8801 void Sema::CheckDelayedMemberExceptionSpecs() {
8802   decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8803   decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8804 
8805   std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8806   std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8807 
8808   // Perform any deferred checking of exception specifications for virtual
8809   // destructors.
8810   for (auto &Check : Overriding)
8811     CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8812 
8813   // Perform any deferred checking of exception specifications for befriended
8814   // special members.
8815   for (auto &Check : Equivalent)
8816     CheckEquivalentExceptionSpec(Check.second, Check.first);
8817 }
8818 
8819 namespace {
8820 /// CRTP base class for visiting operations performed by a special member
8821 /// function (or inherited constructor).
8822 template<typename Derived>
8823 struct SpecialMemberVisitor {
8824   Sema &S;
8825   CXXMethodDecl *MD;
8826   Sema::CXXSpecialMember CSM;
8827   Sema::InheritedConstructorInfo *ICI;
8828 
8829   // Properties of the special member, computed for convenience.
8830   bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8831 
8832   SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8833                        Sema::InheritedConstructorInfo *ICI)
8834       : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8835     switch (CSM) {
8836     case Sema::CXXDefaultConstructor:
8837     case Sema::CXXCopyConstructor:
8838     case Sema::CXXMoveConstructor:
8839       IsConstructor = true;
8840       break;
8841     case Sema::CXXCopyAssignment:
8842     case Sema::CXXMoveAssignment:
8843       IsAssignment = true;
8844       break;
8845     case Sema::CXXDestructor:
8846       break;
8847     case Sema::CXXInvalid:
8848       llvm_unreachable("invalid special member kind");
8849     }
8850 
8851     if (MD->getNumParams()) {
8852       if (const ReferenceType *RT =
8853               MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8854         ConstArg = RT->getPointeeType().isConstQualified();
8855     }
8856   }
8857 
8858   Derived &getDerived() { return static_cast<Derived&>(*this); }
8859 
8860   /// Is this a "move" special member?
8861   bool isMove() const {
8862     return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8863   }
8864 
8865   /// Look up the corresponding special member in the given class.
8866   Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8867                                              unsigned Quals, bool IsMutable) {
8868     return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8869                                        ConstArg && !IsMutable);
8870   }
8871 
8872   /// Look up the constructor for the specified base class to see if it's
8873   /// overridden due to this being an inherited constructor.
8874   Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8875     if (!ICI)
8876       return {};
8877     assert(CSM == Sema::CXXDefaultConstructor);
8878     auto *BaseCtor =
8879       cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8880     if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8881       return MD;
8882     return {};
8883   }
8884 
8885   /// A base or member subobject.
8886   typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8887 
8888   /// Get the location to use for a subobject in diagnostics.
8889   static SourceLocation getSubobjectLoc(Subobject Subobj) {
8890     // FIXME: For an indirect virtual base, the direct base leading to
8891     // the indirect virtual base would be a more useful choice.
8892     if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8893       return B->getBaseTypeLoc();
8894     else
8895       return Subobj.get<FieldDecl*>()->getLocation();
8896   }
8897 
8898   enum BasesToVisit {
8899     /// Visit all non-virtual (direct) bases.
8900     VisitNonVirtualBases,
8901     /// Visit all direct bases, virtual or not.
8902     VisitDirectBases,
8903     /// Visit all non-virtual bases, and all virtual bases if the class
8904     /// is not abstract.
8905     VisitPotentiallyConstructedBases,
8906     /// Visit all direct or virtual bases.
8907     VisitAllBases
8908   };
8909 
8910   // Visit the bases and members of the class.
8911   bool visit(BasesToVisit Bases) {
8912     CXXRecordDecl *RD = MD->getParent();
8913 
8914     if (Bases == VisitPotentiallyConstructedBases)
8915       Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8916 
8917     for (auto &B : RD->bases())
8918       if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8919           getDerived().visitBase(&B))
8920         return true;
8921 
8922     if (Bases == VisitAllBases)
8923       for (auto &B : RD->vbases())
8924         if (getDerived().visitBase(&B))
8925           return true;
8926 
8927     for (auto *F : RD->fields())
8928       if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8929           getDerived().visitField(F))
8930         return true;
8931 
8932     return false;
8933   }
8934 };
8935 }
8936 
8937 namespace {
8938 struct SpecialMemberDeletionInfo
8939     : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8940   bool Diagnose;
8941 
8942   SourceLocation Loc;
8943 
8944   bool AllFieldsAreConst;
8945 
8946   SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8947                             Sema::CXXSpecialMember CSM,
8948                             Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8949       : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8950         Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8951 
8952   bool inUnion() const { return MD->getParent()->isUnion(); }
8953 
8954   Sema::CXXSpecialMember getEffectiveCSM() {
8955     return ICI ? Sema::CXXInvalid : CSM;
8956   }
8957 
8958   bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8959 
8960   bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8961   bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8962 
8963   bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8964   bool shouldDeleteForField(FieldDecl *FD);
8965   bool shouldDeleteForAllConstMembers();
8966 
8967   bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8968                                      unsigned Quals);
8969   bool shouldDeleteForSubobjectCall(Subobject Subobj,
8970                                     Sema::SpecialMemberOverloadResult SMOR,
8971                                     bool IsDtorCallInCtor);
8972 
8973   bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8974 };
8975 }
8976 
8977 /// Is the given special member inaccessible when used on the given
8978 /// sub-object.
8979 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8980                                              CXXMethodDecl *target) {
8981   /// If we're operating on a base class, the object type is the
8982   /// type of this special member.
8983   QualType objectTy;
8984   AccessSpecifier access = target->getAccess();
8985   if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8986     objectTy = S.Context.getTypeDeclType(MD->getParent());
8987     access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8988 
8989   // If we're operating on a field, the object type is the type of the field.
8990   } else {
8991     objectTy = S.Context.getTypeDeclType(target->getParent());
8992   }
8993 
8994   return S.isMemberAccessibleForDeletion(
8995       target->getParent(), DeclAccessPair::make(target, access), objectTy);
8996 }
8997 
8998 /// Check whether we should delete a special member due to the implicit
8999 /// definition containing a call to a special member of a subobject.
9000 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9001     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9002     bool IsDtorCallInCtor) {
9003   CXXMethodDecl *Decl = SMOR.getMethod();
9004   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9005 
9006   int DiagKind = -1;
9007 
9008   if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
9009     DiagKind = !Decl ? 0 : 1;
9010   else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9011     DiagKind = 2;
9012   else if (!isAccessible(Subobj, Decl))
9013     DiagKind = 3;
9014   else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9015            !Decl->isTrivial()) {
9016     // A member of a union must have a trivial corresponding special member.
9017     // As a weird special case, a destructor call from a union's constructor
9018     // must be accessible and non-deleted, but need not be trivial. Such a
9019     // destructor is never actually called, but is semantically checked as
9020     // if it were.
9021     DiagKind = 4;
9022   }
9023 
9024   if (DiagKind == -1)
9025     return false;
9026 
9027   if (Diagnose) {
9028     if (Field) {
9029       S.Diag(Field->getLocation(),
9030              diag::note_deleted_special_member_class_subobject)
9031         << getEffectiveCSM() << MD->getParent() << /*IsField*/true
9032         << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
9033     } else {
9034       CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
9035       S.Diag(Base->getBeginLoc(),
9036              diag::note_deleted_special_member_class_subobject)
9037           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9038           << Base->getType() << DiagKind << IsDtorCallInCtor
9039           << /*IsObjCPtr*/false;
9040     }
9041 
9042     if (DiagKind == 1)
9043       S.NoteDeletedFunction(Decl);
9044     // FIXME: Explain inaccessibility if DiagKind == 3.
9045   }
9046 
9047   return true;
9048 }
9049 
9050 /// Check whether we should delete a special member function due to having a
9051 /// direct or virtual base class or non-static data member of class type M.
9052 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9053     CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9054   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9055   bool IsMutable = Field && Field->isMutable();
9056 
9057   // C++11 [class.ctor]p5:
9058   // -- any direct or virtual base class, or non-static data member with no
9059   //    brace-or-equal-initializer, has class type M (or array thereof) and
9060   //    either M has no default constructor or overload resolution as applied
9061   //    to M's default constructor results in an ambiguity or in a function
9062   //    that is deleted or inaccessible
9063   // C++11 [class.copy]p11, C++11 [class.copy]p23:
9064   // -- a direct or virtual base class B that cannot be copied/moved because
9065   //    overload resolution, as applied to B's corresponding special member,
9066   //    results in an ambiguity or a function that is deleted or inaccessible
9067   //    from the defaulted special member
9068   // C++11 [class.dtor]p5:
9069   // -- any direct or virtual base class [...] has a type with a destructor
9070   //    that is deleted or inaccessible
9071   if (!(CSM == Sema::CXXDefaultConstructor &&
9072         Field && Field->hasInClassInitializer()) &&
9073       shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
9074                                    false))
9075     return true;
9076 
9077   // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9078   // -- any direct or virtual base class or non-static data member has a
9079   //    type with a destructor that is deleted or inaccessible
9080   if (IsConstructor) {
9081     Sema::SpecialMemberOverloadResult SMOR =
9082         S.LookupSpecialMember(Class, Sema::CXXDestructor,
9083                               false, false, false, false, false);
9084     if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
9085       return true;
9086   }
9087 
9088   return false;
9089 }
9090 
9091 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9092     FieldDecl *FD, QualType FieldType) {
9093   // The defaulted special functions are defined as deleted if this is a variant
9094   // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9095   // type under ARC.
9096   if (!FieldType.hasNonTrivialObjCLifetime())
9097     return false;
9098 
9099   // Don't make the defaulted default constructor defined as deleted if the
9100   // member has an in-class initializer.
9101   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9102     return false;
9103 
9104   if (Diagnose) {
9105     auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9106     S.Diag(FD->getLocation(),
9107            diag::note_deleted_special_member_class_subobject)
9108         << getEffectiveCSM() << ParentClass << /*IsField*/true
9109         << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9110   }
9111 
9112   return true;
9113 }
9114 
9115 /// Check whether we should delete a special member function due to the class
9116 /// having a particular direct or virtual base class.
9117 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9118   CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9119   // If program is correct, BaseClass cannot be null, but if it is, the error
9120   // must be reported elsewhere.
9121   if (!BaseClass)
9122     return false;
9123   // If we have an inheriting constructor, check whether we're calling an
9124   // inherited constructor instead of a default constructor.
9125   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9126   if (auto *BaseCtor = SMOR.getMethod()) {
9127     // Note that we do not check access along this path; other than that,
9128     // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9129     // FIXME: Check that the base has a usable destructor! Sink this into
9130     // shouldDeleteForClassSubobject.
9131     if (BaseCtor->isDeleted() && Diagnose) {
9132       S.Diag(Base->getBeginLoc(),
9133              diag::note_deleted_special_member_class_subobject)
9134           << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9135           << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9136           << /*IsObjCPtr*/false;
9137       S.NoteDeletedFunction(BaseCtor);
9138     }
9139     return BaseCtor->isDeleted();
9140   }
9141   return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9142 }
9143 
9144 /// Check whether we should delete a special member function due to the class
9145 /// having a particular non-static data member.
9146 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9147   QualType FieldType = S.Context.getBaseElementType(FD->getType());
9148   CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9149 
9150   if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9151     return true;
9152 
9153   if (CSM == Sema::CXXDefaultConstructor) {
9154     // For a default constructor, all references must be initialized in-class
9155     // and, if a union, it must have a non-const member.
9156     if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9157       if (Diagnose)
9158         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9159           << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9160       return true;
9161     }
9162     // C++11 [class.ctor]p5: any non-variant non-static data member of
9163     // const-qualified type (or array thereof) with no
9164     // brace-or-equal-initializer does not have a user-provided default
9165     // constructor.
9166     if (!inUnion() && FieldType.isConstQualified() &&
9167         !FD->hasInClassInitializer() &&
9168         (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
9169       if (Diagnose)
9170         S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9171           << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9172       return true;
9173     }
9174 
9175     if (inUnion() && !FieldType.isConstQualified())
9176       AllFieldsAreConst = false;
9177   } else if (CSM == Sema::CXXCopyConstructor) {
9178     // For a copy constructor, data members must not be of rvalue reference
9179     // type.
9180     if (FieldType->isRValueReferenceType()) {
9181       if (Diagnose)
9182         S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9183           << MD->getParent() << FD << FieldType;
9184       return true;
9185     }
9186   } else if (IsAssignment) {
9187     // For an assignment operator, data members must not be of reference type.
9188     if (FieldType->isReferenceType()) {
9189       if (Diagnose)
9190         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9191           << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9192       return true;
9193     }
9194     if (!FieldRecord && FieldType.isConstQualified()) {
9195       // C++11 [class.copy]p23:
9196       // -- a non-static data member of const non-class type (or array thereof)
9197       if (Diagnose)
9198         S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9199           << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9200       return true;
9201     }
9202   }
9203 
9204   if (FieldRecord) {
9205     // Some additional restrictions exist on the variant members.
9206     if (!inUnion() && FieldRecord->isUnion() &&
9207         FieldRecord->isAnonymousStructOrUnion()) {
9208       bool AllVariantFieldsAreConst = true;
9209 
9210       // FIXME: Handle anonymous unions declared within anonymous unions.
9211       for (auto *UI : FieldRecord->fields()) {
9212         QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9213 
9214         if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9215           return true;
9216 
9217         if (!UnionFieldType.isConstQualified())
9218           AllVariantFieldsAreConst = false;
9219 
9220         CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9221         if (UnionFieldRecord &&
9222             shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9223                                           UnionFieldType.getCVRQualifiers()))
9224           return true;
9225       }
9226 
9227       // At least one member in each anonymous union must be non-const
9228       if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9229           !FieldRecord->field_empty()) {
9230         if (Diagnose)
9231           S.Diag(FieldRecord->getLocation(),
9232                  diag::note_deleted_default_ctor_all_const)
9233             << !!ICI << MD->getParent() << /*anonymous union*/1;
9234         return true;
9235       }
9236 
9237       // Don't check the implicit member of the anonymous union type.
9238       // This is technically non-conformant but supported, and we have a
9239       // diagnostic for this elsewhere.
9240       return false;
9241     }
9242 
9243     if (shouldDeleteForClassSubobject(FieldRecord, FD,
9244                                       FieldType.getCVRQualifiers()))
9245       return true;
9246   }
9247 
9248   return false;
9249 }
9250 
9251 /// C++11 [class.ctor] p5:
9252 ///   A defaulted default constructor for a class X is defined as deleted if
9253 /// X is a union and all of its variant members are of const-qualified type.
9254 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9255   // This is a silly definition, because it gives an empty union a deleted
9256   // default constructor. Don't do that.
9257   if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9258     bool AnyFields = false;
9259     for (auto *F : MD->getParent()->fields())
9260       if ((AnyFields = !F->isUnnamedBitfield()))
9261         break;
9262     if (!AnyFields)
9263       return false;
9264     if (Diagnose)
9265       S.Diag(MD->getParent()->getLocation(),
9266              diag::note_deleted_default_ctor_all_const)
9267         << !!ICI << MD->getParent() << /*not anonymous union*/0;
9268     return true;
9269   }
9270   return false;
9271 }
9272 
9273 /// Determine whether a defaulted special member function should be defined as
9274 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9275 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9276 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9277                                      InheritedConstructorInfo *ICI,
9278                                      bool Diagnose) {
9279   if (MD->isInvalidDecl())
9280     return false;
9281   CXXRecordDecl *RD = MD->getParent();
9282   assert(!RD->isDependentType() && "do deletion after instantiation");
9283   if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9284     return false;
9285 
9286   // C++11 [expr.lambda.prim]p19:
9287   //   The closure type associated with a lambda-expression has a
9288   //   deleted (8.4.3) default constructor and a deleted copy
9289   //   assignment operator.
9290   // C++2a adds back these operators if the lambda has no lambda-capture.
9291   if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9292       (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9293     if (Diagnose)
9294       Diag(RD->getLocation(), diag::note_lambda_decl);
9295     return true;
9296   }
9297 
9298   // For an anonymous struct or union, the copy and assignment special members
9299   // will never be used, so skip the check. For an anonymous union declared at
9300   // namespace scope, the constructor and destructor are used.
9301   if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9302       RD->isAnonymousStructOrUnion())
9303     return false;
9304 
9305   // C++11 [class.copy]p7, p18:
9306   //   If the class definition declares a move constructor or move assignment
9307   //   operator, an implicitly declared copy constructor or copy assignment
9308   //   operator is defined as deleted.
9309   if (MD->isImplicit() &&
9310       (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9311     CXXMethodDecl *UserDeclaredMove = nullptr;
9312 
9313     // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9314     // deletion of the corresponding copy operation, not both copy operations.
9315     // MSVC 2015 has adopted the standards conforming behavior.
9316     bool DeletesOnlyMatchingCopy =
9317         getLangOpts().MSVCCompat &&
9318         !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9319 
9320     if (RD->hasUserDeclaredMoveConstructor() &&
9321         (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9322       if (!Diagnose) return true;
9323 
9324       // Find any user-declared move constructor.
9325       for (auto *I : RD->ctors()) {
9326         if (I->isMoveConstructor()) {
9327           UserDeclaredMove = I;
9328           break;
9329         }
9330       }
9331       assert(UserDeclaredMove);
9332     } else if (RD->hasUserDeclaredMoveAssignment() &&
9333                (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9334       if (!Diagnose) return true;
9335 
9336       // Find any user-declared move assignment operator.
9337       for (auto *I : RD->methods()) {
9338         if (I->isMoveAssignmentOperator()) {
9339           UserDeclaredMove = I;
9340           break;
9341         }
9342       }
9343       assert(UserDeclaredMove);
9344     }
9345 
9346     if (UserDeclaredMove) {
9347       Diag(UserDeclaredMove->getLocation(),
9348            diag::note_deleted_copy_user_declared_move)
9349         << (CSM == CXXCopyAssignment) << RD
9350         << UserDeclaredMove->isMoveAssignmentOperator();
9351       return true;
9352     }
9353   }
9354 
9355   // Do access control from the special member function
9356   ContextRAII MethodContext(*this, MD);
9357 
9358   // C++11 [class.dtor]p5:
9359   // -- for a virtual destructor, lookup of the non-array deallocation function
9360   //    results in an ambiguity or in a function that is deleted or inaccessible
9361   if (CSM == CXXDestructor && MD->isVirtual()) {
9362     FunctionDecl *OperatorDelete = nullptr;
9363     DeclarationName Name =
9364       Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9365     if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9366                                  OperatorDelete, /*Diagnose*/false)) {
9367       if (Diagnose)
9368         Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9369       return true;
9370     }
9371   }
9372 
9373   SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9374 
9375   // Per DR1611, do not consider virtual bases of constructors of abstract
9376   // classes, since we are not going to construct them.
9377   // Per DR1658, do not consider virtual bases of destructors of abstract
9378   // classes either.
9379   // Per DR2180, for assignment operators we only assign (and thus only
9380   // consider) direct bases.
9381   if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9382                                  : SMI.VisitPotentiallyConstructedBases))
9383     return true;
9384 
9385   if (SMI.shouldDeleteForAllConstMembers())
9386     return true;
9387 
9388   if (getLangOpts().CUDA) {
9389     // We should delete the special member in CUDA mode if target inference
9390     // failed.
9391     // For inherited constructors (non-null ICI), CSM may be passed so that MD
9392     // is treated as certain special member, which may not reflect what special
9393     // member MD really is. However inferCUDATargetForImplicitSpecialMember
9394     // expects CSM to match MD, therefore recalculate CSM.
9395     assert(ICI || CSM == getSpecialMember(MD));
9396     auto RealCSM = CSM;
9397     if (ICI)
9398       RealCSM = getSpecialMember(MD);
9399 
9400     return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9401                                                    SMI.ConstArg, Diagnose);
9402   }
9403 
9404   return false;
9405 }
9406 
9407 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9408   DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9409   assert(DFK && "not a defaultable function");
9410   assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9411 
9412   if (DFK.isSpecialMember()) {
9413     ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9414                               nullptr, /*Diagnose=*/true);
9415   } else {
9416     DefaultedComparisonAnalyzer(
9417         *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9418         DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9419         .visit();
9420   }
9421 }
9422 
9423 /// Perform lookup for a special member of the specified kind, and determine
9424 /// whether it is trivial. If the triviality can be determined without the
9425 /// lookup, skip it. This is intended for use when determining whether a
9426 /// special member of a containing object is trivial, and thus does not ever
9427 /// perform overload resolution for default constructors.
9428 ///
9429 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9430 /// member that was most likely to be intended to be trivial, if any.
9431 ///
9432 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9433 /// determine whether the special member is trivial.
9434 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9435                                      Sema::CXXSpecialMember CSM, unsigned Quals,
9436                                      bool ConstRHS,
9437                                      Sema::TrivialABIHandling TAH,
9438                                      CXXMethodDecl **Selected) {
9439   if (Selected)
9440     *Selected = nullptr;
9441 
9442   switch (CSM) {
9443   case Sema::CXXInvalid:
9444     llvm_unreachable("not a special member");
9445 
9446   case Sema::CXXDefaultConstructor:
9447     // C++11 [class.ctor]p5:
9448     //   A default constructor is trivial if:
9449     //    - all the [direct subobjects] have trivial default constructors
9450     //
9451     // Note, no overload resolution is performed in this case.
9452     if (RD->hasTrivialDefaultConstructor())
9453       return true;
9454 
9455     if (Selected) {
9456       // If there's a default constructor which could have been trivial, dig it
9457       // out. Otherwise, if there's any user-provided default constructor, point
9458       // to that as an example of why there's not a trivial one.
9459       CXXConstructorDecl *DefCtor = nullptr;
9460       if (RD->needsImplicitDefaultConstructor())
9461         S.DeclareImplicitDefaultConstructor(RD);
9462       for (auto *CI : RD->ctors()) {
9463         if (!CI->isDefaultConstructor())
9464           continue;
9465         DefCtor = CI;
9466         if (!DefCtor->isUserProvided())
9467           break;
9468       }
9469 
9470       *Selected = DefCtor;
9471     }
9472 
9473     return false;
9474 
9475   case Sema::CXXDestructor:
9476     // C++11 [class.dtor]p5:
9477     //   A destructor is trivial if:
9478     //    - all the direct [subobjects] have trivial destructors
9479     if (RD->hasTrivialDestructor() ||
9480         (TAH == Sema::TAH_ConsiderTrivialABI &&
9481          RD->hasTrivialDestructorForCall()))
9482       return true;
9483 
9484     if (Selected) {
9485       if (RD->needsImplicitDestructor())
9486         S.DeclareImplicitDestructor(RD);
9487       *Selected = RD->getDestructor();
9488     }
9489 
9490     return false;
9491 
9492   case Sema::CXXCopyConstructor:
9493     // C++11 [class.copy]p12:
9494     //   A copy constructor is trivial if:
9495     //    - the constructor selected to copy each direct [subobject] is trivial
9496     if (RD->hasTrivialCopyConstructor() ||
9497         (TAH == Sema::TAH_ConsiderTrivialABI &&
9498          RD->hasTrivialCopyConstructorForCall())) {
9499       if (Quals == Qualifiers::Const)
9500         // We must either select the trivial copy constructor or reach an
9501         // ambiguity; no need to actually perform overload resolution.
9502         return true;
9503     } else if (!Selected) {
9504       return false;
9505     }
9506     // In C++98, we are not supposed to perform overload resolution here, but we
9507     // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9508     // cases like B as having a non-trivial copy constructor:
9509     //   struct A { template<typename T> A(T&); };
9510     //   struct B { mutable A a; };
9511     goto NeedOverloadResolution;
9512 
9513   case Sema::CXXCopyAssignment:
9514     // C++11 [class.copy]p25:
9515     //   A copy assignment operator is trivial if:
9516     //    - the assignment operator selected to copy each direct [subobject] is
9517     //      trivial
9518     if (RD->hasTrivialCopyAssignment()) {
9519       if (Quals == Qualifiers::Const)
9520         return true;
9521     } else if (!Selected) {
9522       return false;
9523     }
9524     // In C++98, we are not supposed to perform overload resolution here, but we
9525     // treat that as a language defect.
9526     goto NeedOverloadResolution;
9527 
9528   case Sema::CXXMoveConstructor:
9529   case Sema::CXXMoveAssignment:
9530   NeedOverloadResolution:
9531     Sema::SpecialMemberOverloadResult SMOR =
9532         lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9533 
9534     // The standard doesn't describe how to behave if the lookup is ambiguous.
9535     // We treat it as not making the member non-trivial, just like the standard
9536     // mandates for the default constructor. This should rarely matter, because
9537     // the member will also be deleted.
9538     if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9539       return true;
9540 
9541     if (!SMOR.getMethod()) {
9542       assert(SMOR.getKind() ==
9543              Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9544       return false;
9545     }
9546 
9547     // We deliberately don't check if we found a deleted special member. We're
9548     // not supposed to!
9549     if (Selected)
9550       *Selected = SMOR.getMethod();
9551 
9552     if (TAH == Sema::TAH_ConsiderTrivialABI &&
9553         (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9554       return SMOR.getMethod()->isTrivialForCall();
9555     return SMOR.getMethod()->isTrivial();
9556   }
9557 
9558   llvm_unreachable("unknown special method kind");
9559 }
9560 
9561 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9562   for (auto *CI : RD->ctors())
9563     if (!CI->isImplicit())
9564       return CI;
9565 
9566   // Look for constructor templates.
9567   typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9568   for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9569     if (CXXConstructorDecl *CD =
9570           dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9571       return CD;
9572   }
9573 
9574   return nullptr;
9575 }
9576 
9577 /// The kind of subobject we are checking for triviality. The values of this
9578 /// enumeration are used in diagnostics.
9579 enum TrivialSubobjectKind {
9580   /// The subobject is a base class.
9581   TSK_BaseClass,
9582   /// The subobject is a non-static data member.
9583   TSK_Field,
9584   /// The object is actually the complete object.
9585   TSK_CompleteObject
9586 };
9587 
9588 /// Check whether the special member selected for a given type would be trivial.
9589 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9590                                       QualType SubType, bool ConstRHS,
9591                                       Sema::CXXSpecialMember CSM,
9592                                       TrivialSubobjectKind Kind,
9593                                       Sema::TrivialABIHandling TAH, bool Diagnose) {
9594   CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9595   if (!SubRD)
9596     return true;
9597 
9598   CXXMethodDecl *Selected;
9599   if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9600                                ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9601     return true;
9602 
9603   if (Diagnose) {
9604     if (ConstRHS)
9605       SubType.addConst();
9606 
9607     if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9608       S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9609         << Kind << SubType.getUnqualifiedType();
9610       if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9611         S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9612     } else if (!Selected)
9613       S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9614         << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9615     else if (Selected->isUserProvided()) {
9616       if (Kind == TSK_CompleteObject)
9617         S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9618           << Kind << SubType.getUnqualifiedType() << CSM;
9619       else {
9620         S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9621           << Kind << SubType.getUnqualifiedType() << CSM;
9622         S.Diag(Selected->getLocation(), diag::note_declared_at);
9623       }
9624     } else {
9625       if (Kind != TSK_CompleteObject)
9626         S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9627           << Kind << SubType.getUnqualifiedType() << CSM;
9628 
9629       // Explain why the defaulted or deleted special member isn't trivial.
9630       S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9631                                Diagnose);
9632     }
9633   }
9634 
9635   return false;
9636 }
9637 
9638 /// Check whether the members of a class type allow a special member to be
9639 /// trivial.
9640 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9641                                      Sema::CXXSpecialMember CSM,
9642                                      bool ConstArg,
9643                                      Sema::TrivialABIHandling TAH,
9644                                      bool Diagnose) {
9645   for (const auto *FI : RD->fields()) {
9646     if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9647       continue;
9648 
9649     QualType FieldType = S.Context.getBaseElementType(FI->getType());
9650 
9651     // Pretend anonymous struct or union members are members of this class.
9652     if (FI->isAnonymousStructOrUnion()) {
9653       if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9654                                     CSM, ConstArg, TAH, Diagnose))
9655         return false;
9656       continue;
9657     }
9658 
9659     // C++11 [class.ctor]p5:
9660     //   A default constructor is trivial if [...]
9661     //    -- no non-static data member of its class has a
9662     //       brace-or-equal-initializer
9663     if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9664       if (Diagnose)
9665         S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9666             << FI;
9667       return false;
9668     }
9669 
9670     // Objective C ARC 4.3.5:
9671     //   [...] nontrivally ownership-qualified types are [...] not trivially
9672     //   default constructible, copy constructible, move constructible, copy
9673     //   assignable, move assignable, or destructible [...]
9674     if (FieldType.hasNonTrivialObjCLifetime()) {
9675       if (Diagnose)
9676         S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9677           << RD << FieldType.getObjCLifetime();
9678       return false;
9679     }
9680 
9681     bool ConstRHS = ConstArg && !FI->isMutable();
9682     if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9683                                    CSM, TSK_Field, TAH, Diagnose))
9684       return false;
9685   }
9686 
9687   return true;
9688 }
9689 
9690 /// Diagnose why the specified class does not have a trivial special member of
9691 /// the given kind.
9692 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9693   QualType Ty = Context.getRecordType(RD);
9694 
9695   bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9696   checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9697                             TSK_CompleteObject, TAH_IgnoreTrivialABI,
9698                             /*Diagnose*/true);
9699 }
9700 
9701 /// Determine whether a defaulted or deleted special member function is trivial,
9702 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9703 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9704 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9705                                   TrivialABIHandling TAH, bool Diagnose) {
9706   assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9707 
9708   CXXRecordDecl *RD = MD->getParent();
9709 
9710   bool ConstArg = false;
9711 
9712   // C++11 [class.copy]p12, p25: [DR1593]
9713   //   A [special member] is trivial if [...] its parameter-type-list is
9714   //   equivalent to the parameter-type-list of an implicit declaration [...]
9715   switch (CSM) {
9716   case CXXDefaultConstructor:
9717   case CXXDestructor:
9718     // Trivial default constructors and destructors cannot have parameters.
9719     break;
9720 
9721   case CXXCopyConstructor:
9722   case CXXCopyAssignment: {
9723     // Trivial copy operations always have const, non-volatile parameter types.
9724     ConstArg = true;
9725     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9726     const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9727     if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9728       if (Diagnose)
9729         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9730           << Param0->getSourceRange() << Param0->getType()
9731           << Context.getLValueReferenceType(
9732                Context.getRecordType(RD).withConst());
9733       return false;
9734     }
9735     break;
9736   }
9737 
9738   case CXXMoveConstructor:
9739   case CXXMoveAssignment: {
9740     // Trivial move operations always have non-cv-qualified parameters.
9741     const ParmVarDecl *Param0 = MD->getParamDecl(0);
9742     const RValueReferenceType *RT =
9743       Param0->getType()->getAs<RValueReferenceType>();
9744     if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9745       if (Diagnose)
9746         Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9747           << Param0->getSourceRange() << Param0->getType()
9748           << Context.getRValueReferenceType(Context.getRecordType(RD));
9749       return false;
9750     }
9751     break;
9752   }
9753 
9754   case CXXInvalid:
9755     llvm_unreachable("not a special member");
9756   }
9757 
9758   if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9759     if (Diagnose)
9760       Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9761            diag::note_nontrivial_default_arg)
9762         << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9763     return false;
9764   }
9765   if (MD->isVariadic()) {
9766     if (Diagnose)
9767       Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9768     return false;
9769   }
9770 
9771   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9772   //   A copy/move [constructor or assignment operator] is trivial if
9773   //    -- the [member] selected to copy/move each direct base class subobject
9774   //       is trivial
9775   //
9776   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9777   //   A [default constructor or destructor] is trivial if
9778   //    -- all the direct base classes have trivial [default constructors or
9779   //       destructors]
9780   for (const auto &BI : RD->bases())
9781     if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9782                                    ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9783       return false;
9784 
9785   // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9786   //   A copy/move [constructor or assignment operator] for a class X is
9787   //   trivial if
9788   //    -- for each non-static data member of X that is of class type (or array
9789   //       thereof), the constructor selected to copy/move that member is
9790   //       trivial
9791   //
9792   // C++11 [class.copy]p12, C++11 [class.copy]p25:
9793   //   A [default constructor or destructor] is trivial if
9794   //    -- for all of the non-static data members of its class that are of class
9795   //       type (or array thereof), each such class has a trivial [default
9796   //       constructor or destructor]
9797   if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9798     return false;
9799 
9800   // C++11 [class.dtor]p5:
9801   //   A destructor is trivial if [...]
9802   //    -- the destructor is not virtual
9803   if (CSM == CXXDestructor && MD->isVirtual()) {
9804     if (Diagnose)
9805       Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9806     return false;
9807   }
9808 
9809   // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9810   //   A [special member] for class X is trivial if [...]
9811   //    -- class X has no virtual functions and no virtual base classes
9812   if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9813     if (!Diagnose)
9814       return false;
9815 
9816     if (RD->getNumVBases()) {
9817       // Check for virtual bases. We already know that the corresponding
9818       // member in all bases is trivial, so vbases must all be direct.
9819       CXXBaseSpecifier &BS = *RD->vbases_begin();
9820       assert(BS.isVirtual());
9821       Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9822       return false;
9823     }
9824 
9825     // Must have a virtual method.
9826     for (const auto *MI : RD->methods()) {
9827       if (MI->isVirtual()) {
9828         SourceLocation MLoc = MI->getBeginLoc();
9829         Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9830         return false;
9831       }
9832     }
9833 
9834     llvm_unreachable("dynamic class with no vbases and no virtual functions");
9835   }
9836 
9837   // Looks like it's trivial!
9838   return true;
9839 }
9840 
9841 namespace {
9842 struct FindHiddenVirtualMethod {
9843   Sema *S;
9844   CXXMethodDecl *Method;
9845   llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9846   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9847 
9848 private:
9849   /// Check whether any most overridden method from MD in Methods
9850   static bool CheckMostOverridenMethods(
9851       const CXXMethodDecl *MD,
9852       const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9853     if (MD->size_overridden_methods() == 0)
9854       return Methods.count(MD->getCanonicalDecl());
9855     for (const CXXMethodDecl *O : MD->overridden_methods())
9856       if (CheckMostOverridenMethods(O, Methods))
9857         return true;
9858     return false;
9859   }
9860 
9861 public:
9862   /// Member lookup function that determines whether a given C++
9863   /// method overloads virtual methods in a base class without overriding any,
9864   /// to be used with CXXRecordDecl::lookupInBases().
9865   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9866     RecordDecl *BaseRecord =
9867         Specifier->getType()->castAs<RecordType>()->getDecl();
9868 
9869     DeclarationName Name = Method->getDeclName();
9870     assert(Name.getNameKind() == DeclarationName::Identifier);
9871 
9872     bool foundSameNameMethod = false;
9873     SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9874     for (Path.Decls = BaseRecord->lookup(Name).begin();
9875          Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9876       NamedDecl *D = *Path.Decls;
9877       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9878         MD = MD->getCanonicalDecl();
9879         foundSameNameMethod = true;
9880         // Interested only in hidden virtual methods.
9881         if (!MD->isVirtual())
9882           continue;
9883         // If the method we are checking overrides a method from its base
9884         // don't warn about the other overloaded methods. Clang deviates from
9885         // GCC by only diagnosing overloads of inherited virtual functions that
9886         // do not override any other virtual functions in the base. GCC's
9887         // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9888         // function from a base class. These cases may be better served by a
9889         // warning (not specific to virtual functions) on call sites when the
9890         // call would select a different function from the base class, were it
9891         // visible.
9892         // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9893         if (!S->IsOverload(Method, MD, false))
9894           return true;
9895         // Collect the overload only if its hidden.
9896         if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9897           overloadedMethods.push_back(MD);
9898       }
9899     }
9900 
9901     if (foundSameNameMethod)
9902       OverloadedMethods.append(overloadedMethods.begin(),
9903                                overloadedMethods.end());
9904     return foundSameNameMethod;
9905   }
9906 };
9907 } // end anonymous namespace
9908 
9909 /// Add the most overridden methods from MD to Methods
9910 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9911                         llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9912   if (MD->size_overridden_methods() == 0)
9913     Methods.insert(MD->getCanonicalDecl());
9914   else
9915     for (const CXXMethodDecl *O : MD->overridden_methods())
9916       AddMostOverridenMethods(O, Methods);
9917 }
9918 
9919 /// Check if a method overloads virtual methods in a base class without
9920 /// overriding any.
9921 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9922                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9923   if (!MD->getDeclName().isIdentifier())
9924     return;
9925 
9926   CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9927                      /*bool RecordPaths=*/false,
9928                      /*bool DetectVirtual=*/false);
9929   FindHiddenVirtualMethod FHVM;
9930   FHVM.Method = MD;
9931   FHVM.S = this;
9932 
9933   // Keep the base methods that were overridden or introduced in the subclass
9934   // by 'using' in a set. A base method not in this set is hidden.
9935   CXXRecordDecl *DC = MD->getParent();
9936   DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9937   for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9938     NamedDecl *ND = *I;
9939     if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9940       ND = shad->getTargetDecl();
9941     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9942       AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9943   }
9944 
9945   if (DC->lookupInBases(FHVM, Paths))
9946     OverloadedMethods = FHVM.OverloadedMethods;
9947 }
9948 
9949 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9950                           SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9951   for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9952     CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9953     PartialDiagnostic PD = PDiag(
9954          diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9955     HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9956     Diag(overloadedMD->getLocation(), PD);
9957   }
9958 }
9959 
9960 /// Diagnose methods which overload virtual methods in a base class
9961 /// without overriding any.
9962 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9963   if (MD->isInvalidDecl())
9964     return;
9965 
9966   if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9967     return;
9968 
9969   SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9970   FindHiddenVirtualMethods(MD, OverloadedMethods);
9971   if (!OverloadedMethods.empty()) {
9972     Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9973       << MD << (OverloadedMethods.size() > 1);
9974 
9975     NoteHiddenVirtualMethods(MD, OverloadedMethods);
9976   }
9977 }
9978 
9979 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9980   auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9981     // No diagnostics if this is a template instantiation.
9982     if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9983       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9984            diag::ext_cannot_use_trivial_abi) << &RD;
9985       Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9986            diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9987     }
9988     RD.dropAttr<TrivialABIAttr>();
9989   };
9990 
9991   // Ill-formed if the copy and move constructors are deleted.
9992   auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9993     // If the type is dependent, then assume it might have
9994     // implicit copy or move ctor because we won't know yet at this point.
9995     if (RD.isDependentType())
9996       return true;
9997     if (RD.needsImplicitCopyConstructor() &&
9998         !RD.defaultedCopyConstructorIsDeleted())
9999       return true;
10000     if (RD.needsImplicitMoveConstructor() &&
10001         !RD.defaultedMoveConstructorIsDeleted())
10002       return true;
10003     for (const CXXConstructorDecl *CD : RD.ctors())
10004       if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10005         return true;
10006     return false;
10007   };
10008 
10009   if (!HasNonDeletedCopyOrMoveConstructor()) {
10010     PrintDiagAndRemoveAttr(0);
10011     return;
10012   }
10013 
10014   // Ill-formed if the struct has virtual functions.
10015   if (RD.isPolymorphic()) {
10016     PrintDiagAndRemoveAttr(1);
10017     return;
10018   }
10019 
10020   for (const auto &B : RD.bases()) {
10021     // Ill-formed if the base class is non-trivial for the purpose of calls or a
10022     // virtual base.
10023     if (!B.getType()->isDependentType() &&
10024         !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10025       PrintDiagAndRemoveAttr(2);
10026       return;
10027     }
10028 
10029     if (B.isVirtual()) {
10030       PrintDiagAndRemoveAttr(3);
10031       return;
10032     }
10033   }
10034 
10035   for (const auto *FD : RD.fields()) {
10036     // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10037     // non-trivial for the purpose of calls.
10038     QualType FT = FD->getType();
10039     if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10040       PrintDiagAndRemoveAttr(4);
10041       return;
10042     }
10043 
10044     if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
10045       if (!RT->isDependentType() &&
10046           !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
10047         PrintDiagAndRemoveAttr(5);
10048         return;
10049       }
10050   }
10051 }
10052 
10053 void Sema::ActOnFinishCXXMemberSpecification(
10054     Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10055     SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10056   if (!TagDecl)
10057     return;
10058 
10059   AdjustDeclIfTemplate(TagDecl);
10060 
10061   for (const ParsedAttr &AL : AttrList) {
10062     if (AL.getKind() != ParsedAttr::AT_Visibility)
10063       continue;
10064     AL.setInvalid();
10065     Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
10066   }
10067 
10068   ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
10069               // strict aliasing violation!
10070               reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
10071               FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
10072 
10073   CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
10074 }
10075 
10076 /// Find the equality comparison functions that should be implicitly declared
10077 /// in a given class definition, per C++2a [class.compare.default]p3.
10078 static void findImplicitlyDeclaredEqualityComparisons(
10079     ASTContext &Ctx, CXXRecordDecl *RD,
10080     llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10081   DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
10082   if (!RD->lookup(EqEq).empty())
10083     // Member operator== explicitly declared: no implicit operator==s.
10084     return;
10085 
10086   // Traverse friends looking for an '==' or a '<=>'.
10087   for (FriendDecl *Friend : RD->friends()) {
10088     FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
10089     if (!FD) continue;
10090 
10091     if (FD->getOverloadedOperator() == OO_EqualEqual) {
10092       // Friend operator== explicitly declared: no implicit operator==s.
10093       Spaceships.clear();
10094       return;
10095     }
10096 
10097     if (FD->getOverloadedOperator() == OO_Spaceship &&
10098         FD->isExplicitlyDefaulted())
10099       Spaceships.push_back(FD);
10100   }
10101 
10102   // Look for members named 'operator<=>'.
10103   DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10104   for (NamedDecl *ND : RD->lookup(Cmp)) {
10105     // Note that we could find a non-function here (either a function template
10106     // or a using-declaration). Neither case results in an implicit
10107     // 'operator=='.
10108     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10109       if (FD->isExplicitlyDefaulted())
10110         Spaceships.push_back(FD);
10111   }
10112 }
10113 
10114 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10115 /// special functions, such as the default constructor, copy
10116 /// constructor, or destructor, to the given C++ class (C++
10117 /// [special]p1).  This routine can only be executed just before the
10118 /// definition of the class is complete.
10119 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10120   // Don't add implicit special members to templated classes.
10121   // FIXME: This means unqualified lookups for 'operator=' within a class
10122   // template don't work properly.
10123   if (!ClassDecl->isDependentType()) {
10124     if (ClassDecl->needsImplicitDefaultConstructor()) {
10125       ++getASTContext().NumImplicitDefaultConstructors;
10126 
10127       if (ClassDecl->hasInheritedConstructor())
10128         DeclareImplicitDefaultConstructor(ClassDecl);
10129     }
10130 
10131     if (ClassDecl->needsImplicitCopyConstructor()) {
10132       ++getASTContext().NumImplicitCopyConstructors;
10133 
10134       // If the properties or semantics of the copy constructor couldn't be
10135       // determined while the class was being declared, force a declaration
10136       // of it now.
10137       if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10138           ClassDecl->hasInheritedConstructor())
10139         DeclareImplicitCopyConstructor(ClassDecl);
10140       // For the MS ABI we need to know whether the copy ctor is deleted. A
10141       // prerequisite for deleting the implicit copy ctor is that the class has
10142       // a move ctor or move assignment that is either user-declared or whose
10143       // semantics are inherited from a subobject. FIXME: We should provide a
10144       // more direct way for CodeGen to ask whether the constructor was deleted.
10145       else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10146                (ClassDecl->hasUserDeclaredMoveConstructor() ||
10147                 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10148                 ClassDecl->hasUserDeclaredMoveAssignment() ||
10149                 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10150         DeclareImplicitCopyConstructor(ClassDecl);
10151     }
10152 
10153     if (getLangOpts().CPlusPlus11 &&
10154         ClassDecl->needsImplicitMoveConstructor()) {
10155       ++getASTContext().NumImplicitMoveConstructors;
10156 
10157       if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10158           ClassDecl->hasInheritedConstructor())
10159         DeclareImplicitMoveConstructor(ClassDecl);
10160     }
10161 
10162     if (ClassDecl->needsImplicitCopyAssignment()) {
10163       ++getASTContext().NumImplicitCopyAssignmentOperators;
10164 
10165       // If we have a dynamic class, then the copy assignment operator may be
10166       // virtual, so we have to declare it immediately. This ensures that, e.g.,
10167       // it shows up in the right place in the vtable and that we diagnose
10168       // problems with the implicit exception specification.
10169       if (ClassDecl->isDynamicClass() ||
10170           ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10171           ClassDecl->hasInheritedAssignment())
10172         DeclareImplicitCopyAssignment(ClassDecl);
10173     }
10174 
10175     if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10176       ++getASTContext().NumImplicitMoveAssignmentOperators;
10177 
10178       // Likewise for the move assignment operator.
10179       if (ClassDecl->isDynamicClass() ||
10180           ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10181           ClassDecl->hasInheritedAssignment())
10182         DeclareImplicitMoveAssignment(ClassDecl);
10183     }
10184 
10185     if (ClassDecl->needsImplicitDestructor()) {
10186       ++getASTContext().NumImplicitDestructors;
10187 
10188       // If we have a dynamic class, then the destructor may be virtual, so we
10189       // have to declare the destructor immediately. This ensures that, e.g., it
10190       // shows up in the right place in the vtable and that we diagnose problems
10191       // with the implicit exception specification.
10192       if (ClassDecl->isDynamicClass() ||
10193           ClassDecl->needsOverloadResolutionForDestructor())
10194         DeclareImplicitDestructor(ClassDecl);
10195     }
10196   }
10197 
10198   // C++2a [class.compare.default]p3:
10199   //   If the member-specification does not explicitly declare any member or
10200   //   friend named operator==, an == operator function is declared implicitly
10201   //   for each defaulted three-way comparison operator function defined in
10202   //   the member-specification
10203   // FIXME: Consider doing this lazily.
10204   // We do this during the initial parse for a class template, not during
10205   // instantiation, so that we can handle unqualified lookups for 'operator=='
10206   // when parsing the template.
10207   if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10208     llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10209     findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10210                                               DefaultedSpaceships);
10211     for (auto *FD : DefaultedSpaceships)
10212       DeclareImplicitEqualityComparison(ClassDecl, FD);
10213   }
10214 }
10215 
10216 unsigned
10217 Sema::ActOnReenterTemplateScope(Decl *D,
10218                                 llvm::function_ref<Scope *()> EnterScope) {
10219   if (!D)
10220     return 0;
10221   AdjustDeclIfTemplate(D);
10222 
10223   // In order to get name lookup right, reenter template scopes in order from
10224   // outermost to innermost.
10225   SmallVector<TemplateParameterList *, 4> ParameterLists;
10226   DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10227 
10228   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10229     for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10230       ParameterLists.push_back(DD->getTemplateParameterList(i));
10231 
10232     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10233       if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10234         ParameterLists.push_back(FTD->getTemplateParameters());
10235     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10236       LookupDC = VD->getDeclContext();
10237 
10238       if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10239         ParameterLists.push_back(VTD->getTemplateParameters());
10240       else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10241         ParameterLists.push_back(PSD->getTemplateParameters());
10242     }
10243   } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10244     for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10245       ParameterLists.push_back(TD->getTemplateParameterList(i));
10246 
10247     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10248       if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10249         ParameterLists.push_back(CTD->getTemplateParameters());
10250       else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10251         ParameterLists.push_back(PSD->getTemplateParameters());
10252     }
10253   }
10254   // FIXME: Alias declarations and concepts.
10255 
10256   unsigned Count = 0;
10257   Scope *InnermostTemplateScope = nullptr;
10258   for (TemplateParameterList *Params : ParameterLists) {
10259     // Ignore explicit specializations; they don't contribute to the template
10260     // depth.
10261     if (Params->size() == 0)
10262       continue;
10263 
10264     InnermostTemplateScope = EnterScope();
10265     for (NamedDecl *Param : *Params) {
10266       if (Param->getDeclName()) {
10267         InnermostTemplateScope->AddDecl(Param);
10268         IdResolver.AddDecl(Param);
10269       }
10270     }
10271     ++Count;
10272   }
10273 
10274   // Associate the new template scopes with the corresponding entities.
10275   if (InnermostTemplateScope) {
10276     assert(LookupDC && "no enclosing DeclContext for template lookup");
10277     EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10278   }
10279 
10280   return Count;
10281 }
10282 
10283 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10284   if (!RecordD) return;
10285   AdjustDeclIfTemplate(RecordD);
10286   CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10287   PushDeclContext(S, Record);
10288 }
10289 
10290 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10291   if (!RecordD) return;
10292   PopDeclContext();
10293 }
10294 
10295 /// This is used to implement the constant expression evaluation part of the
10296 /// attribute enable_if extension. There is nothing in standard C++ which would
10297 /// require reentering parameters.
10298 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10299   if (!Param)
10300     return;
10301 
10302   S->AddDecl(Param);
10303   if (Param->getDeclName())
10304     IdResolver.AddDecl(Param);
10305 }
10306 
10307 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10308 /// parsing a top-level (non-nested) C++ class, and we are now
10309 /// parsing those parts of the given Method declaration that could
10310 /// not be parsed earlier (C++ [class.mem]p2), such as default
10311 /// arguments. This action should enter the scope of the given
10312 /// Method declaration as if we had just parsed the qualified method
10313 /// name. However, it should not bring the parameters into scope;
10314 /// that will be performed by ActOnDelayedCXXMethodParameter.
10315 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10316 }
10317 
10318 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10319 /// C++ method declaration. We're (re-)introducing the given
10320 /// function parameter into scope for use in parsing later parts of
10321 /// the method declaration. For example, we could see an
10322 /// ActOnParamDefaultArgument event for this parameter.
10323 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10324   if (!ParamD)
10325     return;
10326 
10327   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10328 
10329   S->AddDecl(Param);
10330   if (Param->getDeclName())
10331     IdResolver.AddDecl(Param);
10332 }
10333 
10334 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10335 /// processing the delayed method declaration for Method. The method
10336 /// declaration is now considered finished. There may be a separate
10337 /// ActOnStartOfFunctionDef action later (not necessarily
10338 /// immediately!) for this method, if it was also defined inside the
10339 /// class body.
10340 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10341   if (!MethodD)
10342     return;
10343 
10344   AdjustDeclIfTemplate(MethodD);
10345 
10346   FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10347 
10348   // Now that we have our default arguments, check the constructor
10349   // again. It could produce additional diagnostics or affect whether
10350   // the class has implicitly-declared destructors, among other
10351   // things.
10352   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10353     CheckConstructor(Constructor);
10354 
10355   // Check the default arguments, which we may have added.
10356   if (!Method->isInvalidDecl())
10357     CheckCXXDefaultArguments(Method);
10358 }
10359 
10360 // Emit the given diagnostic for each non-address-space qualifier.
10361 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10362 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10363   const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10364   if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10365     bool DiagOccured = false;
10366     FTI.MethodQualifiers->forEachQualifier(
10367         [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10368                                    SourceLocation SL) {
10369           // This diagnostic should be emitted on any qualifier except an addr
10370           // space qualifier. However, forEachQualifier currently doesn't visit
10371           // addr space qualifiers, so there's no way to write this condition
10372           // right now; we just diagnose on everything.
10373           S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10374           DiagOccured = true;
10375         });
10376     if (DiagOccured)
10377       D.setInvalidType();
10378   }
10379 }
10380 
10381 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10382 /// the well-formedness of the constructor declarator @p D with type @p
10383 /// R. If there are any errors in the declarator, this routine will
10384 /// emit diagnostics and set the invalid bit to true.  In any case, the type
10385 /// will be updated to reflect a well-formed type for the constructor and
10386 /// returned.
10387 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10388                                           StorageClass &SC) {
10389   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10390 
10391   // C++ [class.ctor]p3:
10392   //   A constructor shall not be virtual (10.3) or static (9.4). A
10393   //   constructor can be invoked for a const, volatile or const
10394   //   volatile object. A constructor shall not be declared const,
10395   //   volatile, or const volatile (9.3.2).
10396   if (isVirtual) {
10397     if (!D.isInvalidType())
10398       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10399         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10400         << SourceRange(D.getIdentifierLoc());
10401     D.setInvalidType();
10402   }
10403   if (SC == SC_Static) {
10404     if (!D.isInvalidType())
10405       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10406         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10407         << SourceRange(D.getIdentifierLoc());
10408     D.setInvalidType();
10409     SC = SC_None;
10410   }
10411 
10412   if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10413     diagnoseIgnoredQualifiers(
10414         diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10415         D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10416         D.getDeclSpec().getRestrictSpecLoc(),
10417         D.getDeclSpec().getAtomicSpecLoc());
10418     D.setInvalidType();
10419   }
10420 
10421   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10422 
10423   // C++0x [class.ctor]p4:
10424   //   A constructor shall not be declared with a ref-qualifier.
10425   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10426   if (FTI.hasRefQualifier()) {
10427     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10428       << FTI.RefQualifierIsLValueRef
10429       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10430     D.setInvalidType();
10431   }
10432 
10433   // Rebuild the function type "R" without any type qualifiers (in
10434   // case any of the errors above fired) and with "void" as the
10435   // return type, since constructors don't have return types.
10436   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10437   if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10438     return R;
10439 
10440   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10441   EPI.TypeQuals = Qualifiers();
10442   EPI.RefQualifier = RQ_None;
10443 
10444   return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10445 }
10446 
10447 /// CheckConstructor - Checks a fully-formed constructor for
10448 /// well-formedness, issuing any diagnostics required. Returns true if
10449 /// the constructor declarator is invalid.
10450 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10451   CXXRecordDecl *ClassDecl
10452     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10453   if (!ClassDecl)
10454     return Constructor->setInvalidDecl();
10455 
10456   // C++ [class.copy]p3:
10457   //   A declaration of a constructor for a class X is ill-formed if
10458   //   its first parameter is of type (optionally cv-qualified) X and
10459   //   either there are no other parameters or else all other
10460   //   parameters have default arguments.
10461   if (!Constructor->isInvalidDecl() &&
10462       Constructor->hasOneParamOrDefaultArgs() &&
10463       Constructor->getTemplateSpecializationKind() !=
10464           TSK_ImplicitInstantiation) {
10465     QualType ParamType = Constructor->getParamDecl(0)->getType();
10466     QualType ClassTy = Context.getTagDeclType(ClassDecl);
10467     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10468       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10469       const char *ConstRef
10470         = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10471                                                         : " const &";
10472       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10473         << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10474 
10475       // FIXME: Rather that making the constructor invalid, we should endeavor
10476       // to fix the type.
10477       Constructor->setInvalidDecl();
10478     }
10479   }
10480 }
10481 
10482 /// CheckDestructor - Checks a fully-formed destructor definition for
10483 /// well-formedness, issuing any diagnostics required.  Returns true
10484 /// on error.
10485 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10486   CXXRecordDecl *RD = Destructor->getParent();
10487 
10488   if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10489     SourceLocation Loc;
10490 
10491     if (!Destructor->isImplicit())
10492       Loc = Destructor->getLocation();
10493     else
10494       Loc = RD->getLocation();
10495 
10496     // If we have a virtual destructor, look up the deallocation function
10497     if (FunctionDecl *OperatorDelete =
10498             FindDeallocationFunctionForDestructor(Loc, RD)) {
10499       Expr *ThisArg = nullptr;
10500 
10501       // If the notional 'delete this' expression requires a non-trivial
10502       // conversion from 'this' to the type of a destroying operator delete's
10503       // first parameter, perform that conversion now.
10504       if (OperatorDelete->isDestroyingOperatorDelete()) {
10505         QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10506         if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10507           // C++ [class.dtor]p13:
10508           //   ... as if for the expression 'delete this' appearing in a
10509           //   non-virtual destructor of the destructor's class.
10510           ContextRAII SwitchContext(*this, Destructor);
10511           ExprResult This =
10512               ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10513           assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10514           This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10515           if (This.isInvalid()) {
10516             // FIXME: Register this as a context note so that it comes out
10517             // in the right order.
10518             Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10519             return true;
10520           }
10521           ThisArg = This.get();
10522         }
10523       }
10524 
10525       DiagnoseUseOfDecl(OperatorDelete, Loc);
10526       MarkFunctionReferenced(Loc, OperatorDelete);
10527       Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10528     }
10529   }
10530 
10531   return false;
10532 }
10533 
10534 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10535 /// the well-formednes of the destructor declarator @p D with type @p
10536 /// R. If there are any errors in the declarator, this routine will
10537 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
10538 /// will be updated to reflect a well-formed type for the destructor and
10539 /// returned.
10540 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10541                                          StorageClass& SC) {
10542   // C++ [class.dtor]p1:
10543   //   [...] A typedef-name that names a class is a class-name
10544   //   (7.1.3); however, a typedef-name that names a class shall not
10545   //   be used as the identifier in the declarator for a destructor
10546   //   declaration.
10547   QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10548   if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10549     Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10550       << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10551   else if (const TemplateSpecializationType *TST =
10552              DeclaratorType->getAs<TemplateSpecializationType>())
10553     if (TST->isTypeAlias())
10554       Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10555         << DeclaratorType << 1;
10556 
10557   // C++ [class.dtor]p2:
10558   //   A destructor is used to destroy objects of its class type. A
10559   //   destructor takes no parameters, and no return type can be
10560   //   specified for it (not even void). The address of a destructor
10561   //   shall not be taken. A destructor shall not be static. A
10562   //   destructor can be invoked for a const, volatile or const
10563   //   volatile object. A destructor shall not be declared const,
10564   //   volatile or const volatile (9.3.2).
10565   if (SC == SC_Static) {
10566     if (!D.isInvalidType())
10567       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10568         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10569         << SourceRange(D.getIdentifierLoc())
10570         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10571 
10572     SC = SC_None;
10573   }
10574   if (!D.isInvalidType()) {
10575     // Destructors don't have return types, but the parser will
10576     // happily parse something like:
10577     //
10578     //   class X {
10579     //     float ~X();
10580     //   };
10581     //
10582     // The return type will be eliminated later.
10583     if (D.getDeclSpec().hasTypeSpecifier())
10584       Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10585         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10586         << SourceRange(D.getIdentifierLoc());
10587     else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10588       diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10589                                 SourceLocation(),
10590                                 D.getDeclSpec().getConstSpecLoc(),
10591                                 D.getDeclSpec().getVolatileSpecLoc(),
10592                                 D.getDeclSpec().getRestrictSpecLoc(),
10593                                 D.getDeclSpec().getAtomicSpecLoc());
10594       D.setInvalidType();
10595     }
10596   }
10597 
10598   checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10599 
10600   // C++0x [class.dtor]p2:
10601   //   A destructor shall not be declared with a ref-qualifier.
10602   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10603   if (FTI.hasRefQualifier()) {
10604     Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10605       << FTI.RefQualifierIsLValueRef
10606       << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10607     D.setInvalidType();
10608   }
10609 
10610   // Make sure we don't have any parameters.
10611   if (FTIHasNonVoidParameters(FTI)) {
10612     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10613 
10614     // Delete the parameters.
10615     FTI.freeParams();
10616     D.setInvalidType();
10617   }
10618 
10619   // Make sure the destructor isn't variadic.
10620   if (FTI.isVariadic) {
10621     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10622     D.setInvalidType();
10623   }
10624 
10625   // Rebuild the function type "R" without any type qualifiers or
10626   // parameters (in case any of the errors above fired) and with
10627   // "void" as the return type, since destructors don't have return
10628   // types.
10629   if (!D.isInvalidType())
10630     return R;
10631 
10632   const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10633   FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10634   EPI.Variadic = false;
10635   EPI.TypeQuals = Qualifiers();
10636   EPI.RefQualifier = RQ_None;
10637   return Context.getFunctionType(Context.VoidTy, None, EPI);
10638 }
10639 
10640 static void extendLeft(SourceRange &R, SourceRange Before) {
10641   if (Before.isInvalid())
10642     return;
10643   R.setBegin(Before.getBegin());
10644   if (R.getEnd().isInvalid())
10645     R.setEnd(Before.getEnd());
10646 }
10647 
10648 static void extendRight(SourceRange &R, SourceRange After) {
10649   if (After.isInvalid())
10650     return;
10651   if (R.getBegin().isInvalid())
10652     R.setBegin(After.getBegin());
10653   R.setEnd(After.getEnd());
10654 }
10655 
10656 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10657 /// well-formednes of the conversion function declarator @p D with
10658 /// type @p R. If there are any errors in the declarator, this routine
10659 /// will emit diagnostics and return true. Otherwise, it will return
10660 /// false. Either way, the type @p R will be updated to reflect a
10661 /// well-formed type for the conversion operator.
10662 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10663                                      StorageClass& SC) {
10664   // C++ [class.conv.fct]p1:
10665   //   Neither parameter types nor return type can be specified. The
10666   //   type of a conversion function (8.3.5) is "function taking no
10667   //   parameter returning conversion-type-id."
10668   if (SC == SC_Static) {
10669     if (!D.isInvalidType())
10670       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10671         << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10672         << D.getName().getSourceRange();
10673     D.setInvalidType();
10674     SC = SC_None;
10675   }
10676 
10677   TypeSourceInfo *ConvTSI = nullptr;
10678   QualType ConvType =
10679       GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10680 
10681   const DeclSpec &DS = D.getDeclSpec();
10682   if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10683     // Conversion functions don't have return types, but the parser will
10684     // happily parse something like:
10685     //
10686     //   class X {
10687     //     float operator bool();
10688     //   };
10689     //
10690     // The return type will be changed later anyway.
10691     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10692       << SourceRange(DS.getTypeSpecTypeLoc())
10693       << SourceRange(D.getIdentifierLoc());
10694     D.setInvalidType();
10695   } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10696     // It's also plausible that the user writes type qualifiers in the wrong
10697     // place, such as:
10698     //   struct S { const operator int(); };
10699     // FIXME: we could provide a fixit to move the qualifiers onto the
10700     // conversion type.
10701     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10702         << SourceRange(D.getIdentifierLoc()) << 0;
10703     D.setInvalidType();
10704   }
10705 
10706   const auto *Proto = R->castAs<FunctionProtoType>();
10707 
10708   // Make sure we don't have any parameters.
10709   if (Proto->getNumParams() > 0) {
10710     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10711 
10712     // Delete the parameters.
10713     D.getFunctionTypeInfo().freeParams();
10714     D.setInvalidType();
10715   } else if (Proto->isVariadic()) {
10716     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10717     D.setInvalidType();
10718   }
10719 
10720   // Diagnose "&operator bool()" and other such nonsense.  This
10721   // is actually a gcc extension which we don't support.
10722   if (Proto->getReturnType() != ConvType) {
10723     bool NeedsTypedef = false;
10724     SourceRange Before, After;
10725 
10726     // Walk the chunks and extract information on them for our diagnostic.
10727     bool PastFunctionChunk = false;
10728     for (auto &Chunk : D.type_objects()) {
10729       switch (Chunk.Kind) {
10730       case DeclaratorChunk::Function:
10731         if (!PastFunctionChunk) {
10732           if (Chunk.Fun.HasTrailingReturnType) {
10733             TypeSourceInfo *TRT = nullptr;
10734             GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10735             if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10736           }
10737           PastFunctionChunk = true;
10738           break;
10739         }
10740         LLVM_FALLTHROUGH;
10741       case DeclaratorChunk::Array:
10742         NeedsTypedef = true;
10743         extendRight(After, Chunk.getSourceRange());
10744         break;
10745 
10746       case DeclaratorChunk::Pointer:
10747       case DeclaratorChunk::BlockPointer:
10748       case DeclaratorChunk::Reference:
10749       case DeclaratorChunk::MemberPointer:
10750       case DeclaratorChunk::Pipe:
10751         extendLeft(Before, Chunk.getSourceRange());
10752         break;
10753 
10754       case DeclaratorChunk::Paren:
10755         extendLeft(Before, Chunk.Loc);
10756         extendRight(After, Chunk.EndLoc);
10757         break;
10758       }
10759     }
10760 
10761     SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10762                          After.isValid()  ? After.getBegin() :
10763                                             D.getIdentifierLoc();
10764     auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10765     DB << Before << After;
10766 
10767     if (!NeedsTypedef) {
10768       DB << /*don't need a typedef*/0;
10769 
10770       // If we can provide a correct fix-it hint, do so.
10771       if (After.isInvalid() && ConvTSI) {
10772         SourceLocation InsertLoc =
10773             getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10774         DB << FixItHint::CreateInsertion(InsertLoc, " ")
10775            << FixItHint::CreateInsertionFromRange(
10776                   InsertLoc, CharSourceRange::getTokenRange(Before))
10777            << FixItHint::CreateRemoval(Before);
10778       }
10779     } else if (!Proto->getReturnType()->isDependentType()) {
10780       DB << /*typedef*/1 << Proto->getReturnType();
10781     } else if (getLangOpts().CPlusPlus11) {
10782       DB << /*alias template*/2 << Proto->getReturnType();
10783     } else {
10784       DB << /*might not be fixable*/3;
10785     }
10786 
10787     // Recover by incorporating the other type chunks into the result type.
10788     // Note, this does *not* change the name of the function. This is compatible
10789     // with the GCC extension:
10790     //   struct S { &operator int(); } s;
10791     //   int &r = s.operator int(); // ok in GCC
10792     //   S::operator int&() {} // error in GCC, function name is 'operator int'.
10793     ConvType = Proto->getReturnType();
10794   }
10795 
10796   // C++ [class.conv.fct]p4:
10797   //   The conversion-type-id shall not represent a function type nor
10798   //   an array type.
10799   if (ConvType->isArrayType()) {
10800     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10801     ConvType = Context.getPointerType(ConvType);
10802     D.setInvalidType();
10803   } else if (ConvType->isFunctionType()) {
10804     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10805     ConvType = Context.getPointerType(ConvType);
10806     D.setInvalidType();
10807   }
10808 
10809   // Rebuild the function type "R" without any parameters (in case any
10810   // of the errors above fired) and with the conversion type as the
10811   // return type.
10812   if (D.isInvalidType())
10813     R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10814 
10815   // C++0x explicit conversion operators.
10816   if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10817     Diag(DS.getExplicitSpecLoc(),
10818          getLangOpts().CPlusPlus11
10819              ? diag::warn_cxx98_compat_explicit_conversion_functions
10820              : diag::ext_explicit_conversion_functions)
10821         << SourceRange(DS.getExplicitSpecRange());
10822 }
10823 
10824 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10825 /// the declaration of the given C++ conversion function. This routine
10826 /// is responsible for recording the conversion function in the C++
10827 /// class, if possible.
10828 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10829   assert(Conversion && "Expected to receive a conversion function declaration");
10830 
10831   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10832 
10833   // Make sure we aren't redeclaring the conversion function.
10834   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10835   // C++ [class.conv.fct]p1:
10836   //   [...] A conversion function is never used to convert a
10837   //   (possibly cv-qualified) object to the (possibly cv-qualified)
10838   //   same object type (or a reference to it), to a (possibly
10839   //   cv-qualified) base class of that type (or a reference to it),
10840   //   or to (possibly cv-qualified) void.
10841   QualType ClassType
10842     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10843   if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10844     ConvType = ConvTypeRef->getPointeeType();
10845   if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10846       Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10847     /* Suppress diagnostics for instantiations. */;
10848   else if (Conversion->size_overridden_methods() != 0)
10849     /* Suppress diagnostics for overriding virtual function in a base class. */;
10850   else if (ConvType->isRecordType()) {
10851     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10852     if (ConvType == ClassType)
10853       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10854         << ClassType;
10855     else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10856       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10857         <<  ClassType << ConvType;
10858   } else if (ConvType->isVoidType()) {
10859     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10860       << ClassType << ConvType;
10861   }
10862 
10863   if (FunctionTemplateDecl *ConversionTemplate
10864                                 = Conversion->getDescribedFunctionTemplate())
10865     return ConversionTemplate;
10866 
10867   return Conversion;
10868 }
10869 
10870 namespace {
10871 /// Utility class to accumulate and print a diagnostic listing the invalid
10872 /// specifier(s) on a declaration.
10873 struct BadSpecifierDiagnoser {
10874   BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10875       : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10876   ~BadSpecifierDiagnoser() {
10877     Diagnostic << Specifiers;
10878   }
10879 
10880   template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10881     return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10882   }
10883   void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10884     return check(SpecLoc,
10885                  DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10886   }
10887   void check(SourceLocation SpecLoc, const char *Spec) {
10888     if (SpecLoc.isInvalid()) return;
10889     Diagnostic << SourceRange(SpecLoc, SpecLoc);
10890     if (!Specifiers.empty()) Specifiers += " ";
10891     Specifiers += Spec;
10892   }
10893 
10894   Sema &S;
10895   Sema::SemaDiagnosticBuilder Diagnostic;
10896   std::string Specifiers;
10897 };
10898 }
10899 
10900 /// Check the validity of a declarator that we parsed for a deduction-guide.
10901 /// These aren't actually declarators in the grammar, so we need to check that
10902 /// the user didn't specify any pieces that are not part of the deduction-guide
10903 /// grammar.
10904 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10905                                          StorageClass &SC) {
10906   TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10907   TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10908   assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10909 
10910   // C++ [temp.deduct.guide]p3:
10911   //   A deduction-gide shall be declared in the same scope as the
10912   //   corresponding class template.
10913   if (!CurContext->getRedeclContext()->Equals(
10914           GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10915     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10916       << GuidedTemplateDecl;
10917     Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10918   }
10919 
10920   auto &DS = D.getMutableDeclSpec();
10921   // We leave 'friend' and 'virtual' to be rejected in the normal way.
10922   if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10923       DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10924       DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10925     BadSpecifierDiagnoser Diagnoser(
10926         *this, D.getIdentifierLoc(),
10927         diag::err_deduction_guide_invalid_specifier);
10928 
10929     Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10930     DS.ClearStorageClassSpecs();
10931     SC = SC_None;
10932 
10933     // 'explicit' is permitted.
10934     Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10935     Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10936     Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10937     DS.ClearConstexprSpec();
10938 
10939     Diagnoser.check(DS.getConstSpecLoc(), "const");
10940     Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10941     Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10942     Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10943     Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10944     DS.ClearTypeQualifiers();
10945 
10946     Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10947     Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10948     Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10949     Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10950     DS.ClearTypeSpecType();
10951   }
10952 
10953   if (D.isInvalidType())
10954     return;
10955 
10956   // Check the declarator is simple enough.
10957   bool FoundFunction = false;
10958   for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10959     if (Chunk.Kind == DeclaratorChunk::Paren)
10960       continue;
10961     if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10962       Diag(D.getDeclSpec().getBeginLoc(),
10963            diag::err_deduction_guide_with_complex_decl)
10964           << D.getSourceRange();
10965       break;
10966     }
10967     if (!Chunk.Fun.hasTrailingReturnType()) {
10968       Diag(D.getName().getBeginLoc(),
10969            diag::err_deduction_guide_no_trailing_return_type);
10970       break;
10971     }
10972 
10973     // Check that the return type is written as a specialization of
10974     // the template specified as the deduction-guide's name.
10975     ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10976     TypeSourceInfo *TSI = nullptr;
10977     QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10978     assert(TSI && "deduction guide has valid type but invalid return type?");
10979     bool AcceptableReturnType = false;
10980     bool MightInstantiateToSpecialization = false;
10981     if (auto RetTST =
10982             TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10983       TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10984       bool TemplateMatches =
10985           Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10986       if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10987         AcceptableReturnType = true;
10988       else {
10989         // This could still instantiate to the right type, unless we know it
10990         // names the wrong class template.
10991         auto *TD = SpecifiedName.getAsTemplateDecl();
10992         MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10993                                              !TemplateMatches);
10994       }
10995     } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10996       MightInstantiateToSpecialization = true;
10997     }
10998 
10999     if (!AcceptableReturnType) {
11000       Diag(TSI->getTypeLoc().getBeginLoc(),
11001            diag::err_deduction_guide_bad_trailing_return_type)
11002           << GuidedTemplate << TSI->getType()
11003           << MightInstantiateToSpecialization
11004           << TSI->getTypeLoc().getSourceRange();
11005     }
11006 
11007     // Keep going to check that we don't have any inner declarator pieces (we
11008     // could still have a function returning a pointer to a function).
11009     FoundFunction = true;
11010   }
11011 
11012   if (D.isFunctionDefinition())
11013     Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
11014 }
11015 
11016 //===----------------------------------------------------------------------===//
11017 // Namespace Handling
11018 //===----------------------------------------------------------------------===//
11019 
11020 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11021 /// reopened.
11022 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11023                                             SourceLocation Loc,
11024                                             IdentifierInfo *II, bool *IsInline,
11025                                             NamespaceDecl *PrevNS) {
11026   assert(*IsInline != PrevNS->isInline());
11027 
11028   if (PrevNS->isInline())
11029     // The user probably just forgot the 'inline', so suggest that it
11030     // be added back.
11031     S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
11032       << FixItHint::CreateInsertion(KeywordLoc, "inline ");
11033   else
11034     S.Diag(Loc, diag::err_inline_namespace_mismatch);
11035 
11036   S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
11037   *IsInline = PrevNS->isInline();
11038 }
11039 
11040 /// ActOnStartNamespaceDef - This is called at the start of a namespace
11041 /// definition.
11042 Decl *Sema::ActOnStartNamespaceDef(
11043     Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
11044     SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
11045     const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
11046   SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11047   // For anonymous namespace, take the location of the left brace.
11048   SourceLocation Loc = II ? IdentLoc : LBrace;
11049   bool IsInline = InlineLoc.isValid();
11050   bool IsInvalid = false;
11051   bool IsStd = false;
11052   bool AddToKnown = false;
11053   Scope *DeclRegionScope = NamespcScope->getParent();
11054 
11055   NamespaceDecl *PrevNS = nullptr;
11056   if (II) {
11057     // C++ [namespace.def]p2:
11058     //   The identifier in an original-namespace-definition shall not
11059     //   have been previously defined in the declarative region in
11060     //   which the original-namespace-definition appears. The
11061     //   identifier in an original-namespace-definition is the name of
11062     //   the namespace. Subsequently in that declarative region, it is
11063     //   treated as an original-namespace-name.
11064     //
11065     // Since namespace names are unique in their scope, and we don't
11066     // look through using directives, just look for any ordinary names
11067     // as if by qualified name lookup.
11068     LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11069                    ForExternalRedeclaration);
11070     LookupQualifiedName(R, CurContext->getRedeclContext());
11071     NamedDecl *PrevDecl =
11072         R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11073     PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
11074 
11075     if (PrevNS) {
11076       // This is an extended namespace definition.
11077       if (IsInline != PrevNS->isInline())
11078         DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
11079                                         &IsInline, PrevNS);
11080     } else if (PrevDecl) {
11081       // This is an invalid name redefinition.
11082       Diag(Loc, diag::err_redefinition_different_kind)
11083         << II;
11084       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11085       IsInvalid = true;
11086       // Continue on to push Namespc as current DeclContext and return it.
11087     } else if (II->isStr("std") &&
11088                CurContext->getRedeclContext()->isTranslationUnit()) {
11089       // This is the first "real" definition of the namespace "std", so update
11090       // our cache of the "std" namespace to point at this definition.
11091       PrevNS = getStdNamespace();
11092       IsStd = true;
11093       AddToKnown = !IsInline;
11094     } else {
11095       // We've seen this namespace for the first time.
11096       AddToKnown = !IsInline;
11097     }
11098   } else {
11099     // Anonymous namespaces.
11100 
11101     // Determine whether the parent already has an anonymous namespace.
11102     DeclContext *Parent = CurContext->getRedeclContext();
11103     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11104       PrevNS = TU->getAnonymousNamespace();
11105     } else {
11106       NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11107       PrevNS = ND->getAnonymousNamespace();
11108     }
11109 
11110     if (PrevNS && IsInline != PrevNS->isInline())
11111       DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11112                                       &IsInline, PrevNS);
11113   }
11114 
11115   NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
11116                                                  StartLoc, Loc, II, PrevNS);
11117   if (IsInvalid)
11118     Namespc->setInvalidDecl();
11119 
11120   ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11121   AddPragmaAttributes(DeclRegionScope, Namespc);
11122 
11123   // FIXME: Should we be merging attributes?
11124   if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11125     PushNamespaceVisibilityAttr(Attr, Loc);
11126 
11127   if (IsStd)
11128     StdNamespace = Namespc;
11129   if (AddToKnown)
11130     KnownNamespaces[Namespc] = false;
11131 
11132   if (II) {
11133     PushOnScopeChains(Namespc, DeclRegionScope);
11134   } else {
11135     // Link the anonymous namespace into its parent.
11136     DeclContext *Parent = CurContext->getRedeclContext();
11137     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11138       TU->setAnonymousNamespace(Namespc);
11139     } else {
11140       cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11141     }
11142 
11143     CurContext->addDecl(Namespc);
11144 
11145     // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
11146     //   behaves as if it were replaced by
11147     //     namespace unique { /* empty body */ }
11148     //     using namespace unique;
11149     //     namespace unique { namespace-body }
11150     //   where all occurrences of 'unique' in a translation unit are
11151     //   replaced by the same identifier and this identifier differs
11152     //   from all other identifiers in the entire program.
11153 
11154     // We just create the namespace with an empty name and then add an
11155     // implicit using declaration, just like the standard suggests.
11156     //
11157     // CodeGen enforces the "universally unique" aspect by giving all
11158     // declarations semantically contained within an anonymous
11159     // namespace internal linkage.
11160 
11161     if (!PrevNS) {
11162       UD = UsingDirectiveDecl::Create(Context, Parent,
11163                                       /* 'using' */ LBrace,
11164                                       /* 'namespace' */ SourceLocation(),
11165                                       /* qualifier */ NestedNameSpecifierLoc(),
11166                                       /* identifier */ SourceLocation(),
11167                                       Namespc,
11168                                       /* Ancestor */ Parent);
11169       UD->setImplicit();
11170       Parent->addDecl(UD);
11171     }
11172   }
11173 
11174   ActOnDocumentableDecl(Namespc);
11175 
11176   // Although we could have an invalid decl (i.e. the namespace name is a
11177   // redefinition), push it as current DeclContext and try to continue parsing.
11178   // FIXME: We should be able to push Namespc here, so that the each DeclContext
11179   // for the namespace has the declarations that showed up in that particular
11180   // namespace definition.
11181   PushDeclContext(NamespcScope, Namespc);
11182   return Namespc;
11183 }
11184 
11185 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11186 /// is a namespace alias, returns the namespace it points to.
11187 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11188   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11189     return AD->getNamespace();
11190   return dyn_cast_or_null<NamespaceDecl>(D);
11191 }
11192 
11193 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
11194 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11195 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11196   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11197   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
11198   Namespc->setRBraceLoc(RBrace);
11199   PopDeclContext();
11200   if (Namespc->hasAttr<VisibilityAttr>())
11201     PopPragmaVisibility(true, RBrace);
11202   // If this namespace contains an export-declaration, export it now.
11203   if (DeferredExportedNamespaces.erase(Namespc))
11204     Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11205 }
11206 
11207 CXXRecordDecl *Sema::getStdBadAlloc() const {
11208   return cast_or_null<CXXRecordDecl>(
11209                                   StdBadAlloc.get(Context.getExternalSource()));
11210 }
11211 
11212 EnumDecl *Sema::getStdAlignValT() const {
11213   return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11214 }
11215 
11216 NamespaceDecl *Sema::getStdNamespace() const {
11217   return cast_or_null<NamespaceDecl>(
11218                                  StdNamespace.get(Context.getExternalSource()));
11219 }
11220 
11221 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11222   if (!StdExperimentalNamespaceCache) {
11223     if (auto Std = getStdNamespace()) {
11224       LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11225                           SourceLocation(), LookupNamespaceName);
11226       if (!LookupQualifiedName(Result, Std) ||
11227           !(StdExperimentalNamespaceCache =
11228                 Result.getAsSingle<NamespaceDecl>()))
11229         Result.suppressDiagnostics();
11230     }
11231   }
11232   return StdExperimentalNamespaceCache;
11233 }
11234 
11235 namespace {
11236 
11237 enum UnsupportedSTLSelect {
11238   USS_InvalidMember,
11239   USS_MissingMember,
11240   USS_NonTrivial,
11241   USS_Other
11242 };
11243 
11244 struct InvalidSTLDiagnoser {
11245   Sema &S;
11246   SourceLocation Loc;
11247   QualType TyForDiags;
11248 
11249   QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11250                       const VarDecl *VD = nullptr) {
11251     {
11252       auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11253                << TyForDiags << ((int)Sel);
11254       if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11255         assert(!Name.empty());
11256         D << Name;
11257       }
11258     }
11259     if (Sel == USS_InvalidMember) {
11260       S.Diag(VD->getLocation(), diag::note_var_declared_here)
11261           << VD << VD->getSourceRange();
11262     }
11263     return QualType();
11264   }
11265 };
11266 } // namespace
11267 
11268 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11269                                            SourceLocation Loc,
11270                                            ComparisonCategoryUsage Usage) {
11271   assert(getLangOpts().CPlusPlus &&
11272          "Looking for comparison category type outside of C++.");
11273 
11274   // Use an elaborated type for diagnostics which has a name containing the
11275   // prepended 'std' namespace but not any inline namespace names.
11276   auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11277     auto *NNS =
11278         NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11279     return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11280   };
11281 
11282   // Check if we've already successfully checked the comparison category type
11283   // before. If so, skip checking it again.
11284   ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11285   if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11286     // The only thing we need to check is that the type has a reachable
11287     // definition in the current context.
11288     if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11289       return QualType();
11290 
11291     return Info->getType();
11292   }
11293 
11294   // If lookup failed
11295   if (!Info) {
11296     std::string NameForDiags = "std::";
11297     NameForDiags += ComparisonCategories::getCategoryString(Kind);
11298     Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11299         << NameForDiags << (int)Usage;
11300     return QualType();
11301   }
11302 
11303   assert(Info->Kind == Kind);
11304   assert(Info->Record);
11305 
11306   // Update the Record decl in case we encountered a forward declaration on our
11307   // first pass. FIXME: This is a bit of a hack.
11308   if (Info->Record->hasDefinition())
11309     Info->Record = Info->Record->getDefinition();
11310 
11311   if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11312     return QualType();
11313 
11314   InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11315 
11316   if (!Info->Record->isTriviallyCopyable())
11317     return UnsupportedSTLError(USS_NonTrivial);
11318 
11319   for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11320     CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11321     // Tolerate empty base classes.
11322     if (Base->isEmpty())
11323       continue;
11324     // Reject STL implementations which have at least one non-empty base.
11325     return UnsupportedSTLError();
11326   }
11327 
11328   // Check that the STL has implemented the types using a single integer field.
11329   // This expectation allows better codegen for builtin operators. We require:
11330   //   (1) The class has exactly one field.
11331   //   (2) The field is an integral or enumeration type.
11332   auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11333   if (std::distance(FIt, FEnd) != 1 ||
11334       !FIt->getType()->isIntegralOrEnumerationType()) {
11335     return UnsupportedSTLError();
11336   }
11337 
11338   // Build each of the require values and store them in Info.
11339   for (ComparisonCategoryResult CCR :
11340        ComparisonCategories::getPossibleResultsForType(Kind)) {
11341     StringRef MemName = ComparisonCategories::getResultString(CCR);
11342     ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11343 
11344     if (!ValInfo)
11345       return UnsupportedSTLError(USS_MissingMember, MemName);
11346 
11347     VarDecl *VD = ValInfo->VD;
11348     assert(VD && "should not be null!");
11349 
11350     // Attempt to diagnose reasons why the STL definition of this type
11351     // might be foobar, including it failing to be a constant expression.
11352     // TODO Handle more ways the lookup or result can be invalid.
11353     if (!VD->isStaticDataMember() ||
11354         !VD->isUsableInConstantExpressions(Context))
11355       return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11356 
11357     // Attempt to evaluate the var decl as a constant expression and extract
11358     // the value of its first field as a ICE. If this fails, the STL
11359     // implementation is not supported.
11360     if (!ValInfo->hasValidIntValue())
11361       return UnsupportedSTLError();
11362 
11363     MarkVariableReferenced(Loc, VD);
11364   }
11365 
11366   // We've successfully built the required types and expressions. Update
11367   // the cache and return the newly cached value.
11368   FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11369   return Info->getType();
11370 }
11371 
11372 /// Retrieve the special "std" namespace, which may require us to
11373 /// implicitly define the namespace.
11374 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11375   if (!StdNamespace) {
11376     // The "std" namespace has not yet been defined, so build one implicitly.
11377     StdNamespace = NamespaceDecl::Create(Context,
11378                                          Context.getTranslationUnitDecl(),
11379                                          /*Inline=*/false,
11380                                          SourceLocation(), SourceLocation(),
11381                                          &PP.getIdentifierTable().get("std"),
11382                                          /*PrevDecl=*/nullptr);
11383     getStdNamespace()->setImplicit(true);
11384   }
11385 
11386   return getStdNamespace();
11387 }
11388 
11389 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11390   assert(getLangOpts().CPlusPlus &&
11391          "Looking for std::initializer_list outside of C++.");
11392 
11393   // We're looking for implicit instantiations of
11394   // template <typename E> class std::initializer_list.
11395 
11396   if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11397     return false;
11398 
11399   ClassTemplateDecl *Template = nullptr;
11400   const TemplateArgument *Arguments = nullptr;
11401 
11402   if (const RecordType *RT = Ty->getAs<RecordType>()) {
11403 
11404     ClassTemplateSpecializationDecl *Specialization =
11405         dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11406     if (!Specialization)
11407       return false;
11408 
11409     Template = Specialization->getSpecializedTemplate();
11410     Arguments = Specialization->getTemplateArgs().data();
11411   } else if (const TemplateSpecializationType *TST =
11412                  Ty->getAs<TemplateSpecializationType>()) {
11413     Template = dyn_cast_or_null<ClassTemplateDecl>(
11414         TST->getTemplateName().getAsTemplateDecl());
11415     Arguments = TST->getArgs();
11416   }
11417   if (!Template)
11418     return false;
11419 
11420   if (!StdInitializerList) {
11421     // Haven't recognized std::initializer_list yet, maybe this is it.
11422     CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11423     if (TemplateClass->getIdentifier() !=
11424             &PP.getIdentifierTable().get("initializer_list") ||
11425         !getStdNamespace()->InEnclosingNamespaceSetOf(
11426             TemplateClass->getDeclContext()))
11427       return false;
11428     // This is a template called std::initializer_list, but is it the right
11429     // template?
11430     TemplateParameterList *Params = Template->getTemplateParameters();
11431     if (Params->getMinRequiredArguments() != 1)
11432       return false;
11433     if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11434       return false;
11435 
11436     // It's the right template.
11437     StdInitializerList = Template;
11438   }
11439 
11440   if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11441     return false;
11442 
11443   // This is an instance of std::initializer_list. Find the argument type.
11444   if (Element)
11445     *Element = Arguments[0].getAsType();
11446   return true;
11447 }
11448 
11449 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11450   NamespaceDecl *Std = S.getStdNamespace();
11451   if (!Std) {
11452     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11453     return nullptr;
11454   }
11455 
11456   LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11457                       Loc, Sema::LookupOrdinaryName);
11458   if (!S.LookupQualifiedName(Result, Std)) {
11459     S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11460     return nullptr;
11461   }
11462   ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11463   if (!Template) {
11464     Result.suppressDiagnostics();
11465     // We found something weird. Complain about the first thing we found.
11466     NamedDecl *Found = *Result.begin();
11467     S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11468     return nullptr;
11469   }
11470 
11471   // We found some template called std::initializer_list. Now verify that it's
11472   // correct.
11473   TemplateParameterList *Params = Template->getTemplateParameters();
11474   if (Params->getMinRequiredArguments() != 1 ||
11475       !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11476     S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11477     return nullptr;
11478   }
11479 
11480   return Template;
11481 }
11482 
11483 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11484   if (!StdInitializerList) {
11485     StdInitializerList = LookupStdInitializerList(*this, Loc);
11486     if (!StdInitializerList)
11487       return QualType();
11488   }
11489 
11490   TemplateArgumentListInfo Args(Loc, Loc);
11491   Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11492                                        Context.getTrivialTypeSourceInfo(Element,
11493                                                                         Loc)));
11494   return Context.getCanonicalType(
11495       CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11496 }
11497 
11498 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11499   // C++ [dcl.init.list]p2:
11500   //   A constructor is an initializer-list constructor if its first parameter
11501   //   is of type std::initializer_list<E> or reference to possibly cv-qualified
11502   //   std::initializer_list<E> for some type E, and either there are no other
11503   //   parameters or else all other parameters have default arguments.
11504   if (!Ctor->hasOneParamOrDefaultArgs())
11505     return false;
11506 
11507   QualType ArgType = Ctor->getParamDecl(0)->getType();
11508   if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11509     ArgType = RT->getPointeeType().getUnqualifiedType();
11510 
11511   return isStdInitializerList(ArgType, nullptr);
11512 }
11513 
11514 /// Determine whether a using statement is in a context where it will be
11515 /// apply in all contexts.
11516 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11517   switch (CurContext->getDeclKind()) {
11518     case Decl::TranslationUnit:
11519       return true;
11520     case Decl::LinkageSpec:
11521       return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11522     default:
11523       return false;
11524   }
11525 }
11526 
11527 namespace {
11528 
11529 // Callback to only accept typo corrections that are namespaces.
11530 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11531 public:
11532   bool ValidateCandidate(const TypoCorrection &candidate) override {
11533     if (NamedDecl *ND = candidate.getCorrectionDecl())
11534       return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11535     return false;
11536   }
11537 
11538   std::unique_ptr<CorrectionCandidateCallback> clone() override {
11539     return std::make_unique<NamespaceValidatorCCC>(*this);
11540   }
11541 };
11542 
11543 }
11544 
11545 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11546                                        CXXScopeSpec &SS,
11547                                        SourceLocation IdentLoc,
11548                                        IdentifierInfo *Ident) {
11549   R.clear();
11550   NamespaceValidatorCCC CCC{};
11551   if (TypoCorrection Corrected =
11552           S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11553                         Sema::CTK_ErrorRecovery)) {
11554     if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11555       std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11556       bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11557                               Ident->getName().equals(CorrectedStr);
11558       S.diagnoseTypo(Corrected,
11559                      S.PDiag(diag::err_using_directive_member_suggest)
11560                        << Ident << DC << DroppedSpecifier << SS.getRange(),
11561                      S.PDiag(diag::note_namespace_defined_here));
11562     } else {
11563       S.diagnoseTypo(Corrected,
11564                      S.PDiag(diag::err_using_directive_suggest) << Ident,
11565                      S.PDiag(diag::note_namespace_defined_here));
11566     }
11567     R.addDecl(Corrected.getFoundDecl());
11568     return true;
11569   }
11570   return false;
11571 }
11572 
11573 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11574                                 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11575                                 SourceLocation IdentLoc,
11576                                 IdentifierInfo *NamespcName,
11577                                 const ParsedAttributesView &AttrList) {
11578   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11579   assert(NamespcName && "Invalid NamespcName.");
11580   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11581 
11582   // This can only happen along a recovery path.
11583   while (S->isTemplateParamScope())
11584     S = S->getParent();
11585   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11586 
11587   UsingDirectiveDecl *UDir = nullptr;
11588   NestedNameSpecifier *Qualifier = nullptr;
11589   if (SS.isSet())
11590     Qualifier = SS.getScopeRep();
11591 
11592   // Lookup namespace name.
11593   LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11594   LookupParsedName(R, S, &SS);
11595   if (R.isAmbiguous())
11596     return nullptr;
11597 
11598   if (R.empty()) {
11599     R.clear();
11600     // Allow "using namespace std;" or "using namespace ::std;" even if
11601     // "std" hasn't been defined yet, for GCC compatibility.
11602     if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11603         NamespcName->isStr("std")) {
11604       Diag(IdentLoc, diag::ext_using_undefined_std);
11605       R.addDecl(getOrCreateStdNamespace());
11606       R.resolveKind();
11607     }
11608     // Otherwise, attempt typo correction.
11609     else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11610   }
11611 
11612   if (!R.empty()) {
11613     NamedDecl *Named = R.getRepresentativeDecl();
11614     NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11615     assert(NS && "expected namespace decl");
11616 
11617     // The use of a nested name specifier may trigger deprecation warnings.
11618     DiagnoseUseOfDecl(Named, IdentLoc);
11619 
11620     // C++ [namespace.udir]p1:
11621     //   A using-directive specifies that the names in the nominated
11622     //   namespace can be used in the scope in which the
11623     //   using-directive appears after the using-directive. During
11624     //   unqualified name lookup (3.4.1), the names appear as if they
11625     //   were declared in the nearest enclosing namespace which
11626     //   contains both the using-directive and the nominated
11627     //   namespace. [Note: in this context, "contains" means "contains
11628     //   directly or indirectly". ]
11629 
11630     // Find enclosing context containing both using-directive and
11631     // nominated namespace.
11632     DeclContext *CommonAncestor = NS;
11633     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11634       CommonAncestor = CommonAncestor->getParent();
11635 
11636     UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11637                                       SS.getWithLocInContext(Context),
11638                                       IdentLoc, Named, CommonAncestor);
11639 
11640     if (IsUsingDirectiveInToplevelContext(CurContext) &&
11641         !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11642       Diag(IdentLoc, diag::warn_using_directive_in_header);
11643     }
11644 
11645     PushUsingDirective(S, UDir);
11646   } else {
11647     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11648   }
11649 
11650   if (UDir)
11651     ProcessDeclAttributeList(S, UDir, AttrList);
11652 
11653   return UDir;
11654 }
11655 
11656 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11657   // If the scope has an associated entity and the using directive is at
11658   // namespace or translation unit scope, add the UsingDirectiveDecl into
11659   // its lookup structure so qualified name lookup can find it.
11660   DeclContext *Ctx = S->getEntity();
11661   if (Ctx && !Ctx->isFunctionOrMethod())
11662     Ctx->addDecl(UDir);
11663   else
11664     // Otherwise, it is at block scope. The using-directives will affect lookup
11665     // only to the end of the scope.
11666     S->PushUsingDirective(UDir);
11667 }
11668 
11669 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11670                                   SourceLocation UsingLoc,
11671                                   SourceLocation TypenameLoc, CXXScopeSpec &SS,
11672                                   UnqualifiedId &Name,
11673                                   SourceLocation EllipsisLoc,
11674                                   const ParsedAttributesView &AttrList) {
11675   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11676 
11677   if (SS.isEmpty()) {
11678     Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11679     return nullptr;
11680   }
11681 
11682   switch (Name.getKind()) {
11683   case UnqualifiedIdKind::IK_ImplicitSelfParam:
11684   case UnqualifiedIdKind::IK_Identifier:
11685   case UnqualifiedIdKind::IK_OperatorFunctionId:
11686   case UnqualifiedIdKind::IK_LiteralOperatorId:
11687   case UnqualifiedIdKind::IK_ConversionFunctionId:
11688     break;
11689 
11690   case UnqualifiedIdKind::IK_ConstructorName:
11691   case UnqualifiedIdKind::IK_ConstructorTemplateId:
11692     // C++11 inheriting constructors.
11693     Diag(Name.getBeginLoc(),
11694          getLangOpts().CPlusPlus11
11695              ? diag::warn_cxx98_compat_using_decl_constructor
11696              : diag::err_using_decl_constructor)
11697         << SS.getRange();
11698 
11699     if (getLangOpts().CPlusPlus11) break;
11700 
11701     return nullptr;
11702 
11703   case UnqualifiedIdKind::IK_DestructorName:
11704     Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11705     return nullptr;
11706 
11707   case UnqualifiedIdKind::IK_TemplateId:
11708     Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11709         << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11710     return nullptr;
11711 
11712   case UnqualifiedIdKind::IK_DeductionGuideName:
11713     llvm_unreachable("cannot parse qualified deduction guide name");
11714   }
11715 
11716   DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11717   DeclarationName TargetName = TargetNameInfo.getName();
11718   if (!TargetName)
11719     return nullptr;
11720 
11721   // Warn about access declarations.
11722   if (UsingLoc.isInvalid()) {
11723     Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11724                                  ? diag::err_access_decl
11725                                  : diag::warn_access_decl_deprecated)
11726         << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11727   }
11728 
11729   if (EllipsisLoc.isInvalid()) {
11730     if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11731         DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11732       return nullptr;
11733   } else {
11734     if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11735         !TargetNameInfo.containsUnexpandedParameterPack()) {
11736       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11737         << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11738       EllipsisLoc = SourceLocation();
11739     }
11740   }
11741 
11742   NamedDecl *UD =
11743       BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11744                             SS, TargetNameInfo, EllipsisLoc, AttrList,
11745                             /*IsInstantiation*/ false,
11746                             AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11747   if (UD)
11748     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11749 
11750   return UD;
11751 }
11752 
11753 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
11754                                       SourceLocation UsingLoc,
11755                                       SourceLocation EnumLoc,
11756                                       const DeclSpec &DS) {
11757   switch (DS.getTypeSpecType()) {
11758   case DeclSpec::TST_error:
11759     // This will already have been diagnosed
11760     return nullptr;
11761 
11762   case DeclSpec::TST_enum:
11763     break;
11764 
11765   case DeclSpec::TST_typename:
11766     Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
11767     return nullptr;
11768 
11769   default:
11770     llvm_unreachable("unexpected DeclSpec type");
11771   }
11772 
11773   // As with enum-decls, we ignore attributes for now.
11774   auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
11775   if (auto *Def = Enum->getDefinition())
11776     Enum = Def;
11777 
11778   auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
11779                                        DS.getTypeSpecTypeNameLoc(), Enum);
11780   if (UD)
11781     PushOnScopeChains(UD, S, /*AddToContext*/ false);
11782 
11783   return UD;
11784 }
11785 
11786 /// Determine whether a using declaration considers the given
11787 /// declarations as "equivalent", e.g., if they are redeclarations of
11788 /// the same entity or are both typedefs of the same type.
11789 static bool
11790 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11791   if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11792     return true;
11793 
11794   if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11795     if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11796       return Context.hasSameType(TD1->getUnderlyingType(),
11797                                  TD2->getUnderlyingType());
11798 
11799   // Two using_if_exists using-declarations are equivalent if both are
11800   // unresolved.
11801   if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11802       isa<UnresolvedUsingIfExistsDecl>(D2))
11803     return true;
11804 
11805   return false;
11806 }
11807 
11808 
11809 /// Determines whether to create a using shadow decl for a particular
11810 /// decl, given the set of decls existing prior to this using lookup.
11811 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
11812                                 const LookupResult &Previous,
11813                                 UsingShadowDecl *&PrevShadow) {
11814   // Diagnose finding a decl which is not from a base class of the
11815   // current class.  We do this now because there are cases where this
11816   // function will silently decide not to build a shadow decl, which
11817   // will pre-empt further diagnostics.
11818   //
11819   // We don't need to do this in C++11 because we do the check once on
11820   // the qualifier.
11821   //
11822   // FIXME: diagnose the following if we care enough:
11823   //   struct A { int foo; };
11824   //   struct B : A { using A::foo; };
11825   //   template <class T> struct C : A {};
11826   //   template <class T> struct D : C<T> { using B::foo; } // <---
11827   // This is invalid (during instantiation) in C++03 because B::foo
11828   // resolves to the using decl in B, which is not a base class of D<T>.
11829   // We can't diagnose it immediately because C<T> is an unknown
11830   // specialization. The UsingShadowDecl in D<T> then points directly
11831   // to A::foo, which will look well-formed when we instantiate.
11832   // The right solution is to not collapse the shadow-decl chain.
11833   if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
11834     if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
11835       DeclContext *OrigDC = Orig->getDeclContext();
11836 
11837       // Handle enums and anonymous structs.
11838       if (isa<EnumDecl>(OrigDC))
11839         OrigDC = OrigDC->getParent();
11840       CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11841       while (OrigRec->isAnonymousStructOrUnion())
11842         OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11843 
11844       if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11845         if (OrigDC == CurContext) {
11846           Diag(Using->getLocation(),
11847                diag::err_using_decl_nested_name_specifier_is_current_class)
11848               << Using->getQualifierLoc().getSourceRange();
11849           Diag(Orig->getLocation(), diag::note_using_decl_target);
11850           Using->setInvalidDecl();
11851           return true;
11852         }
11853 
11854         Diag(Using->getQualifierLoc().getBeginLoc(),
11855              diag::err_using_decl_nested_name_specifier_is_not_base_class)
11856             << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
11857             << Using->getQualifierLoc().getSourceRange();
11858         Diag(Orig->getLocation(), diag::note_using_decl_target);
11859         Using->setInvalidDecl();
11860         return true;
11861       }
11862     }
11863 
11864   if (Previous.empty()) return false;
11865 
11866   NamedDecl *Target = Orig;
11867   if (isa<UsingShadowDecl>(Target))
11868     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11869 
11870   // If the target happens to be one of the previous declarations, we
11871   // don't have a conflict.
11872   //
11873   // FIXME: but we might be increasing its access, in which case we
11874   // should redeclare it.
11875   NamedDecl *NonTag = nullptr, *Tag = nullptr;
11876   bool FoundEquivalentDecl = false;
11877   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11878          I != E; ++I) {
11879     NamedDecl *D = (*I)->getUnderlyingDecl();
11880     // We can have UsingDecls in our Previous results because we use the same
11881     // LookupResult for checking whether the UsingDecl itself is a valid
11882     // redeclaration.
11883     if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
11884       continue;
11885 
11886     if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11887       // C++ [class.mem]p19:
11888       //   If T is the name of a class, then [every named member other than
11889       //   a non-static data member] shall have a name different from T
11890       if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11891           !isa<IndirectFieldDecl>(Target) &&
11892           !isa<UnresolvedUsingValueDecl>(Target) &&
11893           DiagnoseClassNameShadow(
11894               CurContext,
11895               DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
11896         return true;
11897     }
11898 
11899     if (IsEquivalentForUsingDecl(Context, D, Target)) {
11900       if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11901         PrevShadow = Shadow;
11902       FoundEquivalentDecl = true;
11903     } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11904       // We don't conflict with an existing using shadow decl of an equivalent
11905       // declaration, but we're not a redeclaration of it.
11906       FoundEquivalentDecl = true;
11907     }
11908 
11909     if (isVisible(D))
11910       (isa<TagDecl>(D) ? Tag : NonTag) = D;
11911   }
11912 
11913   if (FoundEquivalentDecl)
11914     return false;
11915 
11916   // Always emit a diagnostic for a mismatch between an unresolved
11917   // using_if_exists and a resolved using declaration in either direction.
11918   if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
11919       (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
11920     if (!NonTag && !Tag)
11921       return false;
11922     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11923     Diag(Target->getLocation(), diag::note_using_decl_target);
11924     Diag((NonTag ? NonTag : Tag)->getLocation(),
11925          diag::note_using_decl_conflict);
11926     BUD->setInvalidDecl();
11927     return true;
11928   }
11929 
11930   if (FunctionDecl *FD = Target->getAsFunction()) {
11931     NamedDecl *OldDecl = nullptr;
11932     switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11933                           /*IsForUsingDecl*/ true)) {
11934     case Ovl_Overload:
11935       return false;
11936 
11937     case Ovl_NonFunction:
11938       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11939       break;
11940 
11941     // We found a decl with the exact signature.
11942     case Ovl_Match:
11943       // If we're in a record, we want to hide the target, so we
11944       // return true (without a diagnostic) to tell the caller not to
11945       // build a shadow decl.
11946       if (CurContext->isRecord())
11947         return true;
11948 
11949       // If we're not in a record, this is an error.
11950       Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11951       break;
11952     }
11953 
11954     Diag(Target->getLocation(), diag::note_using_decl_target);
11955     Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11956     BUD->setInvalidDecl();
11957     return true;
11958   }
11959 
11960   // Target is not a function.
11961 
11962   if (isa<TagDecl>(Target)) {
11963     // No conflict between a tag and a non-tag.
11964     if (!Tag) return false;
11965 
11966     Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11967     Diag(Target->getLocation(), diag::note_using_decl_target);
11968     Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11969     BUD->setInvalidDecl();
11970     return true;
11971   }
11972 
11973   // No conflict between a tag and a non-tag.
11974   if (!NonTag) return false;
11975 
11976   Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11977   Diag(Target->getLocation(), diag::note_using_decl_target);
11978   Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11979   BUD->setInvalidDecl();
11980   return true;
11981 }
11982 
11983 /// Determine whether a direct base class is a virtual base class.
11984 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11985   if (!Derived->getNumVBases())
11986     return false;
11987   for (auto &B : Derived->bases())
11988     if (B.getType()->getAsCXXRecordDecl() == Base)
11989       return B.isVirtual();
11990   llvm_unreachable("not a direct base class");
11991 }
11992 
11993 /// Builds a shadow declaration corresponding to a 'using' declaration.
11994 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
11995                                             NamedDecl *Orig,
11996                                             UsingShadowDecl *PrevDecl) {
11997   // If we resolved to another shadow declaration, just coalesce them.
11998   NamedDecl *Target = Orig;
11999   if (isa<UsingShadowDecl>(Target)) {
12000     Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
12001     assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
12002   }
12003 
12004   NamedDecl *NonTemplateTarget = Target;
12005   if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
12006     NonTemplateTarget = TargetTD->getTemplatedDecl();
12007 
12008   UsingShadowDecl *Shadow;
12009   if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
12010     UsingDecl *Using = cast<UsingDecl>(BUD);
12011     bool IsVirtualBase =
12012         isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
12013                             Using->getQualifier()->getAsRecordDecl());
12014     Shadow = ConstructorUsingShadowDecl::Create(
12015         Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
12016   } else {
12017     Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
12018                                      Target->getDeclName(), BUD, Target);
12019   }
12020   BUD->addShadowDecl(Shadow);
12021 
12022   Shadow->setAccess(BUD->getAccess());
12023   if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
12024     Shadow->setInvalidDecl();
12025 
12026   Shadow->setPreviousDecl(PrevDecl);
12027 
12028   if (S)
12029     PushOnScopeChains(Shadow, S);
12030   else
12031     CurContext->addDecl(Shadow);
12032 
12033 
12034   return Shadow;
12035 }
12036 
12037 /// Hides a using shadow declaration.  This is required by the current
12038 /// using-decl implementation when a resolvable using declaration in a
12039 /// class is followed by a declaration which would hide or override
12040 /// one or more of the using decl's targets; for example:
12041 ///
12042 ///   struct Base { void foo(int); };
12043 ///   struct Derived : Base {
12044 ///     using Base::foo;
12045 ///     void foo(int);
12046 ///   };
12047 ///
12048 /// The governing language is C++03 [namespace.udecl]p12:
12049 ///
12050 ///   When a using-declaration brings names from a base class into a
12051 ///   derived class scope, member functions in the derived class
12052 ///   override and/or hide member functions with the same name and
12053 ///   parameter types in a base class (rather than conflicting).
12054 ///
12055 /// There are two ways to implement this:
12056 ///   (1) optimistically create shadow decls when they're not hidden
12057 ///       by existing declarations, or
12058 ///   (2) don't create any shadow decls (or at least don't make them
12059 ///       visible) until we've fully parsed/instantiated the class.
12060 /// The problem with (1) is that we might have to retroactively remove
12061 /// a shadow decl, which requires several O(n) operations because the
12062 /// decl structures are (very reasonably) not designed for removal.
12063 /// (2) avoids this but is very fiddly and phase-dependent.
12064 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
12065   if (Shadow->getDeclName().getNameKind() ==
12066         DeclarationName::CXXConversionFunctionName)
12067     cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
12068 
12069   // Remove it from the DeclContext...
12070   Shadow->getDeclContext()->removeDecl(Shadow);
12071 
12072   // ...and the scope, if applicable...
12073   if (S) {
12074     S->RemoveDecl(Shadow);
12075     IdResolver.RemoveDecl(Shadow);
12076   }
12077 
12078   // ...and the using decl.
12079   Shadow->getIntroducer()->removeShadowDecl(Shadow);
12080 
12081   // TODO: complain somehow if Shadow was used.  It shouldn't
12082   // be possible for this to happen, because...?
12083 }
12084 
12085 /// Find the base specifier for a base class with the given type.
12086 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
12087                                                 QualType DesiredBase,
12088                                                 bool &AnyDependentBases) {
12089   // Check whether the named type is a direct base class.
12090   CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
12091     .getUnqualifiedType();
12092   for (auto &Base : Derived->bases()) {
12093     CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
12094     if (CanonicalDesiredBase == BaseType)
12095       return &Base;
12096     if (BaseType->isDependentType())
12097       AnyDependentBases = true;
12098   }
12099   return nullptr;
12100 }
12101 
12102 namespace {
12103 class UsingValidatorCCC final : public CorrectionCandidateCallback {
12104 public:
12105   UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12106                     NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12107       : HasTypenameKeyword(HasTypenameKeyword),
12108         IsInstantiation(IsInstantiation), OldNNS(NNS),
12109         RequireMemberOf(RequireMemberOf) {}
12110 
12111   bool ValidateCandidate(const TypoCorrection &Candidate) override {
12112     NamedDecl *ND = Candidate.getCorrectionDecl();
12113 
12114     // Keywords are not valid here.
12115     if (!ND || isa<NamespaceDecl>(ND))
12116       return false;
12117 
12118     // Completely unqualified names are invalid for a 'using' declaration.
12119     if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12120       return false;
12121 
12122     // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12123     // reject.
12124 
12125     if (RequireMemberOf) {
12126       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12127       if (FoundRecord && FoundRecord->isInjectedClassName()) {
12128         // No-one ever wants a using-declaration to name an injected-class-name
12129         // of a base class, unless they're declaring an inheriting constructor.
12130         ASTContext &Ctx = ND->getASTContext();
12131         if (!Ctx.getLangOpts().CPlusPlus11)
12132           return false;
12133         QualType FoundType = Ctx.getRecordType(FoundRecord);
12134 
12135         // Check that the injected-class-name is named as a member of its own
12136         // type; we don't want to suggest 'using Derived::Base;', since that
12137         // means something else.
12138         NestedNameSpecifier *Specifier =
12139             Candidate.WillReplaceSpecifier()
12140                 ? Candidate.getCorrectionSpecifier()
12141                 : OldNNS;
12142         if (!Specifier->getAsType() ||
12143             !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12144           return false;
12145 
12146         // Check that this inheriting constructor declaration actually names a
12147         // direct base class of the current class.
12148         bool AnyDependentBases = false;
12149         if (!findDirectBaseWithType(RequireMemberOf,
12150                                     Ctx.getRecordType(FoundRecord),
12151                                     AnyDependentBases) &&
12152             !AnyDependentBases)
12153           return false;
12154       } else {
12155         auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12156         if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12157           return false;
12158 
12159         // FIXME: Check that the base class member is accessible?
12160       }
12161     } else {
12162       auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12163       if (FoundRecord && FoundRecord->isInjectedClassName())
12164         return false;
12165     }
12166 
12167     if (isa<TypeDecl>(ND))
12168       return HasTypenameKeyword || !IsInstantiation;
12169 
12170     return !HasTypenameKeyword;
12171   }
12172 
12173   std::unique_ptr<CorrectionCandidateCallback> clone() override {
12174     return std::make_unique<UsingValidatorCCC>(*this);
12175   }
12176 
12177 private:
12178   bool HasTypenameKeyword;
12179   bool IsInstantiation;
12180   NestedNameSpecifier *OldNNS;
12181   CXXRecordDecl *RequireMemberOf;
12182 };
12183 } // end anonymous namespace
12184 
12185 /// Remove decls we can't actually see from a lookup being used to declare
12186 /// shadow using decls.
12187 ///
12188 /// \param S - The scope of the potential shadow decl
12189 /// \param Previous - The lookup of a potential shadow decl's name.
12190 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12191   // It is really dumb that we have to do this.
12192   LookupResult::Filter F = Previous.makeFilter();
12193   while (F.hasNext()) {
12194     NamedDecl *D = F.next();
12195     if (!isDeclInScope(D, CurContext, S))
12196       F.erase();
12197     // If we found a local extern declaration that's not ordinarily visible,
12198     // and this declaration is being added to a non-block scope, ignore it.
12199     // We're only checking for scope conflicts here, not also for violations
12200     // of the linkage rules.
12201     else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12202              !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12203       F.erase();
12204   }
12205   F.done();
12206 }
12207 
12208 /// Builds a using declaration.
12209 ///
12210 /// \param IsInstantiation - Whether this call arises from an
12211 ///   instantiation of an unresolved using declaration.  We treat
12212 ///   the lookup differently for these declarations.
12213 NamedDecl *Sema::BuildUsingDeclaration(
12214     Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12215     bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12216     DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12217     const ParsedAttributesView &AttrList, bool IsInstantiation,
12218     bool IsUsingIfExists) {
12219   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12220   SourceLocation IdentLoc = NameInfo.getLoc();
12221   assert(IdentLoc.isValid() && "Invalid TargetName location.");
12222 
12223   // FIXME: We ignore attributes for now.
12224 
12225   // For an inheriting constructor declaration, the name of the using
12226   // declaration is the name of a constructor in this class, not in the
12227   // base class.
12228   DeclarationNameInfo UsingName = NameInfo;
12229   if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12230     if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12231       UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12232           Context.getCanonicalType(Context.getRecordType(RD))));
12233 
12234   // Do the redeclaration lookup in the current scope.
12235   LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12236                         ForVisibleRedeclaration);
12237   Previous.setHideTags(false);
12238   if (S) {
12239     LookupName(Previous, S);
12240 
12241     FilterUsingLookup(S, Previous);
12242   } else {
12243     assert(IsInstantiation && "no scope in non-instantiation");
12244     if (CurContext->isRecord())
12245       LookupQualifiedName(Previous, CurContext);
12246     else {
12247       // No redeclaration check is needed here; in non-member contexts we
12248       // diagnosed all possible conflicts with other using-declarations when
12249       // building the template:
12250       //
12251       // For a dependent non-type using declaration, the only valid case is
12252       // if we instantiate to a single enumerator. We check for conflicts
12253       // between shadow declarations we introduce, and we check in the template
12254       // definition for conflicts between a non-type using declaration and any
12255       // other declaration, which together covers all cases.
12256       //
12257       // A dependent typename using declaration will never successfully
12258       // instantiate, since it will always name a class member, so we reject
12259       // that in the template definition.
12260     }
12261   }
12262 
12263   // Check for invalid redeclarations.
12264   if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12265                                   SS, IdentLoc, Previous))
12266     return nullptr;
12267 
12268   // 'using_if_exists' doesn't make sense on an inherited constructor.
12269   if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12270                              DeclarationName::CXXConstructorName) {
12271     Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12272     return nullptr;
12273   }
12274 
12275   DeclContext *LookupContext = computeDeclContext(SS);
12276   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12277   if (!LookupContext || EllipsisLoc.isValid()) {
12278     NamedDecl *D;
12279     // Dependent scope, or an unexpanded pack
12280     if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12281                                                   SS, NameInfo, IdentLoc))
12282       return nullptr;
12283 
12284     if (HasTypenameKeyword) {
12285       // FIXME: not all declaration name kinds are legal here
12286       D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12287                                               UsingLoc, TypenameLoc,
12288                                               QualifierLoc,
12289                                               IdentLoc, NameInfo.getName(),
12290                                               EllipsisLoc);
12291     } else {
12292       D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12293                                            QualifierLoc, NameInfo, EllipsisLoc);
12294     }
12295     D->setAccess(AS);
12296     CurContext->addDecl(D);
12297     ProcessDeclAttributeList(S, D, AttrList);
12298     return D;
12299   }
12300 
12301   auto Build = [&](bool Invalid) {
12302     UsingDecl *UD =
12303         UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12304                           UsingName, HasTypenameKeyword);
12305     UD->setAccess(AS);
12306     CurContext->addDecl(UD);
12307     ProcessDeclAttributeList(S, UD, AttrList);
12308     UD->setInvalidDecl(Invalid);
12309     return UD;
12310   };
12311   auto BuildInvalid = [&]{ return Build(true); };
12312   auto BuildValid = [&]{ return Build(false); };
12313 
12314   if (RequireCompleteDeclContext(SS, LookupContext))
12315     return BuildInvalid();
12316 
12317   // Look up the target name.
12318   LookupResult R(*this, NameInfo, LookupOrdinaryName);
12319 
12320   // Unlike most lookups, we don't always want to hide tag
12321   // declarations: tag names are visible through the using declaration
12322   // even if hidden by ordinary names, *except* in a dependent context
12323   // where they may be used by two-phase lookup.
12324   if (!IsInstantiation)
12325     R.setHideTags(false);
12326 
12327   // For the purposes of this lookup, we have a base object type
12328   // equal to that of the current context.
12329   if (CurContext->isRecord()) {
12330     R.setBaseObjectType(
12331                    Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12332   }
12333 
12334   LookupQualifiedName(R, LookupContext);
12335 
12336   // Validate the context, now we have a lookup
12337   if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12338                               IdentLoc, &R))
12339     return nullptr;
12340 
12341   if (R.empty() && IsUsingIfExists)
12342     R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12343                                                   UsingName.getName()),
12344               AS_public);
12345 
12346   // Try to correct typos if possible. If constructor name lookup finds no
12347   // results, that means the named class has no explicit constructors, and we
12348   // suppressed declaring implicit ones (probably because it's dependent or
12349   // invalid).
12350   if (R.empty() &&
12351       NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12352     // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12353     // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12354     // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12355     auto *II = NameInfo.getName().getAsIdentifierInfo();
12356     if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12357         CurContext->isStdNamespace() &&
12358         isa<TranslationUnitDecl>(LookupContext) &&
12359         getSourceManager().isInSystemHeader(UsingLoc))
12360       return nullptr;
12361     UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12362                           dyn_cast<CXXRecordDecl>(CurContext));
12363     if (TypoCorrection Corrected =
12364             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12365                         CTK_ErrorRecovery)) {
12366       // We reject candidates where DroppedSpecifier == true, hence the
12367       // literal '0' below.
12368       diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12369                                 << NameInfo.getName() << LookupContext << 0
12370                                 << SS.getRange());
12371 
12372       // If we picked a correction with no attached Decl we can't do anything
12373       // useful with it, bail out.
12374       NamedDecl *ND = Corrected.getCorrectionDecl();
12375       if (!ND)
12376         return BuildInvalid();
12377 
12378       // If we corrected to an inheriting constructor, handle it as one.
12379       auto *RD = dyn_cast<CXXRecordDecl>(ND);
12380       if (RD && RD->isInjectedClassName()) {
12381         // The parent of the injected class name is the class itself.
12382         RD = cast<CXXRecordDecl>(RD->getParent());
12383 
12384         // Fix up the information we'll use to build the using declaration.
12385         if (Corrected.WillReplaceSpecifier()) {
12386           NestedNameSpecifierLocBuilder Builder;
12387           Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12388                               QualifierLoc.getSourceRange());
12389           QualifierLoc = Builder.getWithLocInContext(Context);
12390         }
12391 
12392         // In this case, the name we introduce is the name of a derived class
12393         // constructor.
12394         auto *CurClass = cast<CXXRecordDecl>(CurContext);
12395         UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12396             Context.getCanonicalType(Context.getRecordType(CurClass))));
12397         UsingName.setNamedTypeInfo(nullptr);
12398         for (auto *Ctor : LookupConstructors(RD))
12399           R.addDecl(Ctor);
12400         R.resolveKind();
12401       } else {
12402         // FIXME: Pick up all the declarations if we found an overloaded
12403         // function.
12404         UsingName.setName(ND->getDeclName());
12405         R.addDecl(ND);
12406       }
12407     } else {
12408       Diag(IdentLoc, diag::err_no_member)
12409         << NameInfo.getName() << LookupContext << SS.getRange();
12410       return BuildInvalid();
12411     }
12412   }
12413 
12414   if (R.isAmbiguous())
12415     return BuildInvalid();
12416 
12417   if (HasTypenameKeyword) {
12418     // If we asked for a typename and got a non-type decl, error out.
12419     if (!R.getAsSingle<TypeDecl>() &&
12420         !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12421       Diag(IdentLoc, diag::err_using_typename_non_type);
12422       for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12423         Diag((*I)->getUnderlyingDecl()->getLocation(),
12424              diag::note_using_decl_target);
12425       return BuildInvalid();
12426     }
12427   } else {
12428     // If we asked for a non-typename and we got a type, error out,
12429     // but only if this is an instantiation of an unresolved using
12430     // decl.  Otherwise just silently find the type name.
12431     if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12432       Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12433       Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12434       return BuildInvalid();
12435     }
12436   }
12437 
12438   // C++14 [namespace.udecl]p6:
12439   // A using-declaration shall not name a namespace.
12440   if (R.getAsSingle<NamespaceDecl>()) {
12441     Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12442       << SS.getRange();
12443     return BuildInvalid();
12444   }
12445 
12446   UsingDecl *UD = BuildValid();
12447 
12448   // Some additional rules apply to inheriting constructors.
12449   if (UsingName.getName().getNameKind() ==
12450         DeclarationName::CXXConstructorName) {
12451     // Suppress access diagnostics; the access check is instead performed at the
12452     // point of use for an inheriting constructor.
12453     R.suppressDiagnostics();
12454     if (CheckInheritingConstructorUsingDecl(UD))
12455       return UD;
12456   }
12457 
12458   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12459     UsingShadowDecl *PrevDecl = nullptr;
12460     if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12461       BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12462   }
12463 
12464   return UD;
12465 }
12466 
12467 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12468                                            SourceLocation UsingLoc,
12469                                            SourceLocation EnumLoc,
12470                                            SourceLocation NameLoc,
12471                                            EnumDecl *ED) {
12472   bool Invalid = false;
12473 
12474   if (CurContext->getRedeclContext()->isRecord()) {
12475     /// In class scope, check if this is a duplicate, for better a diagnostic.
12476     DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12477     LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12478                           ForVisibleRedeclaration);
12479 
12480     LookupName(Previous, S);
12481 
12482     for (NamedDecl *D : Previous)
12483       if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12484         if (UED->getEnumDecl() == ED) {
12485           Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12486               << SourceRange(EnumLoc, NameLoc);
12487           Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12488           Invalid = true;
12489           break;
12490         }
12491   }
12492 
12493   if (RequireCompleteEnumDecl(ED, NameLoc))
12494     Invalid = true;
12495 
12496   UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12497                                             EnumLoc, NameLoc, ED);
12498   UD->setAccess(AS);
12499   CurContext->addDecl(UD);
12500 
12501   if (Invalid) {
12502     UD->setInvalidDecl();
12503     return UD;
12504   }
12505 
12506   // Create the shadow decls for each enumerator
12507   for (EnumConstantDecl *EC : ED->enumerators()) {
12508     UsingShadowDecl *PrevDecl = nullptr;
12509     DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12510     LookupResult Previous(*this, DNI, LookupOrdinaryName,
12511                           ForVisibleRedeclaration);
12512     LookupName(Previous, S);
12513     FilterUsingLookup(S, Previous);
12514 
12515     if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12516       BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12517   }
12518 
12519   return UD;
12520 }
12521 
12522 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12523                                     ArrayRef<NamedDecl *> Expansions) {
12524   assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12525          isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12526          isa<UsingPackDecl>(InstantiatedFrom));
12527 
12528   auto *UPD =
12529       UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12530   UPD->setAccess(InstantiatedFrom->getAccess());
12531   CurContext->addDecl(UPD);
12532   return UPD;
12533 }
12534 
12535 /// Additional checks for a using declaration referring to a constructor name.
12536 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12537   assert(!UD->hasTypename() && "expecting a constructor name");
12538 
12539   const Type *SourceType = UD->getQualifier()->getAsType();
12540   assert(SourceType &&
12541          "Using decl naming constructor doesn't have type in scope spec.");
12542   CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12543 
12544   // Check whether the named type is a direct base class.
12545   bool AnyDependentBases = false;
12546   auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12547                                       AnyDependentBases);
12548   if (!Base && !AnyDependentBases) {
12549     Diag(UD->getUsingLoc(),
12550          diag::err_using_decl_constructor_not_in_direct_base)
12551       << UD->getNameInfo().getSourceRange()
12552       << QualType(SourceType, 0) << TargetClass;
12553     UD->setInvalidDecl();
12554     return true;
12555   }
12556 
12557   if (Base)
12558     Base->setInheritConstructors();
12559 
12560   return false;
12561 }
12562 
12563 /// Checks that the given using declaration is not an invalid
12564 /// redeclaration.  Note that this is checking only for the using decl
12565 /// itself, not for any ill-formedness among the UsingShadowDecls.
12566 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12567                                        bool HasTypenameKeyword,
12568                                        const CXXScopeSpec &SS,
12569                                        SourceLocation NameLoc,
12570                                        const LookupResult &Prev) {
12571   NestedNameSpecifier *Qual = SS.getScopeRep();
12572 
12573   // C++03 [namespace.udecl]p8:
12574   // C++0x [namespace.udecl]p10:
12575   //   A using-declaration is a declaration and can therefore be used
12576   //   repeatedly where (and only where) multiple declarations are
12577   //   allowed.
12578   //
12579   // That's in non-member contexts.
12580   if (!CurContext->getRedeclContext()->isRecord()) {
12581     // A dependent qualifier outside a class can only ever resolve to an
12582     // enumeration type. Therefore it conflicts with any other non-type
12583     // declaration in the same scope.
12584     // FIXME: How should we check for dependent type-type conflicts at block
12585     // scope?
12586     if (Qual->isDependent() && !HasTypenameKeyword) {
12587       for (auto *D : Prev) {
12588         if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12589           bool OldCouldBeEnumerator =
12590               isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12591           Diag(NameLoc,
12592                OldCouldBeEnumerator ? diag::err_redefinition
12593                                     : diag::err_redefinition_different_kind)
12594               << Prev.getLookupName();
12595           Diag(D->getLocation(), diag::note_previous_definition);
12596           return true;
12597         }
12598       }
12599     }
12600     return false;
12601   }
12602 
12603   const NestedNameSpecifier *CNNS =
12604       Context.getCanonicalNestedNameSpecifier(Qual);
12605   for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12606     NamedDecl *D = *I;
12607 
12608     bool DTypename;
12609     NestedNameSpecifier *DQual;
12610     if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12611       DTypename = UD->hasTypename();
12612       DQual = UD->getQualifier();
12613     } else if (UnresolvedUsingValueDecl *UD
12614                  = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12615       DTypename = false;
12616       DQual = UD->getQualifier();
12617     } else if (UnresolvedUsingTypenameDecl *UD
12618                  = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12619       DTypename = true;
12620       DQual = UD->getQualifier();
12621     } else continue;
12622 
12623     // using decls differ if one says 'typename' and the other doesn't.
12624     // FIXME: non-dependent using decls?
12625     if (HasTypenameKeyword != DTypename) continue;
12626 
12627     // using decls differ if they name different scopes (but note that
12628     // template instantiation can cause this check to trigger when it
12629     // didn't before instantiation).
12630     if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12631       continue;
12632 
12633     Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12634     Diag(D->getLocation(), diag::note_using_decl) << 1;
12635     return true;
12636   }
12637 
12638   return false;
12639 }
12640 
12641 /// Checks that the given nested-name qualifier used in a using decl
12642 /// in the current context is appropriately related to the current
12643 /// scope.  If an error is found, diagnoses it and returns true.
12644 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12645 /// result of that lookup. UD is likewise nullptr, except when we have an
12646 /// already-populated UsingDecl whose shadow decls contain the same information
12647 /// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12648 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12649                                    const CXXScopeSpec &SS,
12650                                    const DeclarationNameInfo &NameInfo,
12651                                    SourceLocation NameLoc,
12652                                    const LookupResult *R, const UsingDecl *UD) {
12653   DeclContext *NamedContext = computeDeclContext(SS);
12654   assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
12655          "resolvable context must have exactly one set of decls");
12656 
12657   // C++ 20 permits using an enumerator that does not have a class-hierarchy
12658   // relationship.
12659   bool Cxx20Enumerator = false;
12660   if (NamedContext) {
12661     EnumConstantDecl *EC = nullptr;
12662     if (R)
12663       EC = R->getAsSingle<EnumConstantDecl>();
12664     else if (UD && UD->shadow_size() == 1)
12665       EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12666     if (EC)
12667       Cxx20Enumerator = getLangOpts().CPlusPlus20;
12668 
12669     if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12670       // C++14 [namespace.udecl]p7:
12671       // A using-declaration shall not name a scoped enumerator.
12672       // C++20 p1099 permits enumerators.
12673       if (EC && R && ED->isScoped())
12674         Diag(SS.getBeginLoc(),
12675              getLangOpts().CPlusPlus20
12676                  ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12677                  : diag::ext_using_decl_scoped_enumerator)
12678             << SS.getRange();
12679 
12680       // We want to consider the scope of the enumerator
12681       NamedContext = ED->getDeclContext();
12682     }
12683   }
12684 
12685   if (!CurContext->isRecord()) {
12686     // C++03 [namespace.udecl]p3:
12687     // C++0x [namespace.udecl]p8:
12688     //   A using-declaration for a class member shall be a member-declaration.
12689     // C++20 [namespace.udecl]p7
12690     //   ... other than an enumerator ...
12691 
12692     // If we weren't able to compute a valid scope, it might validly be a
12693     // dependent class or enumeration scope. If we have a 'typename' keyword,
12694     // the scope must resolve to a class type.
12695     if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12696                      : !HasTypename)
12697       return false; // OK
12698 
12699     Diag(NameLoc,
12700          Cxx20Enumerator
12701              ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12702              : diag::err_using_decl_can_not_refer_to_class_member)
12703         << SS.getRange();
12704 
12705     if (Cxx20Enumerator)
12706       return false; // OK
12707 
12708     auto *RD = NamedContext
12709                    ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12710                    : nullptr;
12711     if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12712       // See if there's a helpful fixit
12713 
12714       if (!R) {
12715         // We will have already diagnosed the problem on the template
12716         // definition,  Maybe we should do so again?
12717       } else if (R->getAsSingle<TypeDecl>()) {
12718         if (getLangOpts().CPlusPlus11) {
12719           // Convert 'using X::Y;' to 'using Y = X::Y;'.
12720           Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12721             << 0 // alias declaration
12722             << FixItHint::CreateInsertion(SS.getBeginLoc(),
12723                                           NameInfo.getName().getAsString() +
12724                                               " = ");
12725         } else {
12726           // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12727           SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12728           Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12729             << 1 // typedef declaration
12730             << FixItHint::CreateReplacement(UsingLoc, "typedef")
12731             << FixItHint::CreateInsertion(
12732                    InsertLoc, " " + NameInfo.getName().getAsString());
12733         }
12734       } else if (R->getAsSingle<VarDecl>()) {
12735         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12736         // repeating the type of the static data member here.
12737         FixItHint FixIt;
12738         if (getLangOpts().CPlusPlus11) {
12739           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12740           FixIt = FixItHint::CreateReplacement(
12741               UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12742         }
12743 
12744         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12745           << 2 // reference declaration
12746           << FixIt;
12747       } else if (R->getAsSingle<EnumConstantDecl>()) {
12748         // Don't provide a fixit outside C++11 mode; we don't want to suggest
12749         // repeating the type of the enumeration here, and we can't do so if
12750         // the type is anonymous.
12751         FixItHint FixIt;
12752         if (getLangOpts().CPlusPlus11) {
12753           // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12754           FixIt = FixItHint::CreateReplacement(
12755               UsingLoc,
12756               "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12757         }
12758 
12759         Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12760           << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12761           << FixIt;
12762       }
12763     }
12764 
12765     return true; // Fail
12766   }
12767 
12768   // If the named context is dependent, we can't decide much.
12769   if (!NamedContext) {
12770     // FIXME: in C++0x, we can diagnose if we can prove that the
12771     // nested-name-specifier does not refer to a base class, which is
12772     // still possible in some cases.
12773 
12774     // Otherwise we have to conservatively report that things might be
12775     // okay.
12776     return false;
12777   }
12778 
12779   // The current scope is a record.
12780   if (!NamedContext->isRecord()) {
12781     // Ideally this would point at the last name in the specifier,
12782     // but we don't have that level of source info.
12783     Diag(SS.getBeginLoc(),
12784          Cxx20Enumerator
12785              ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12786              : diag::err_using_decl_nested_name_specifier_is_not_class)
12787         << SS.getScopeRep() << SS.getRange();
12788 
12789     if (Cxx20Enumerator)
12790       return false; // OK
12791 
12792     return true;
12793   }
12794 
12795   if (!NamedContext->isDependentContext() &&
12796       RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12797     return true;
12798 
12799   if (getLangOpts().CPlusPlus11) {
12800     // C++11 [namespace.udecl]p3:
12801     //   In a using-declaration used as a member-declaration, the
12802     //   nested-name-specifier shall name a base class of the class
12803     //   being defined.
12804 
12805     if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12806                                  cast<CXXRecordDecl>(NamedContext))) {
12807 
12808       if (Cxx20Enumerator) {
12809         Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12810             << SS.getRange();
12811         return false;
12812       }
12813 
12814       if (CurContext == NamedContext) {
12815         Diag(SS.getBeginLoc(),
12816              diag::err_using_decl_nested_name_specifier_is_current_class)
12817             << SS.getRange();
12818         return !getLangOpts().CPlusPlus20;
12819       }
12820 
12821       if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12822         Diag(SS.getBeginLoc(),
12823              diag::err_using_decl_nested_name_specifier_is_not_base_class)
12824             << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12825             << SS.getRange();
12826       }
12827       return true;
12828     }
12829 
12830     return false;
12831   }
12832 
12833   // C++03 [namespace.udecl]p4:
12834   //   A using-declaration used as a member-declaration shall refer
12835   //   to a member of a base class of the class being defined [etc.].
12836 
12837   // Salient point: SS doesn't have to name a base class as long as
12838   // lookup only finds members from base classes.  Therefore we can
12839   // diagnose here only if we can prove that that can't happen,
12840   // i.e. if the class hierarchies provably don't intersect.
12841 
12842   // TODO: it would be nice if "definitely valid" results were cached
12843   // in the UsingDecl and UsingShadowDecl so that these checks didn't
12844   // need to be repeated.
12845 
12846   llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12847   auto Collect = [&Bases](const CXXRecordDecl *Base) {
12848     Bases.insert(Base);
12849     return true;
12850   };
12851 
12852   // Collect all bases. Return false if we find a dependent base.
12853   if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12854     return false;
12855 
12856   // Returns true if the base is dependent or is one of the accumulated base
12857   // classes.
12858   auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12859     return !Bases.count(Base);
12860   };
12861 
12862   // Return false if the class has a dependent base or if it or one
12863   // of its bases is present in the base set of the current context.
12864   if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12865       !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12866     return false;
12867 
12868   Diag(SS.getRange().getBegin(),
12869        diag::err_using_decl_nested_name_specifier_is_not_base_class)
12870     << SS.getScopeRep()
12871     << cast<CXXRecordDecl>(CurContext)
12872     << SS.getRange();
12873 
12874   return true;
12875 }
12876 
12877 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12878                                   MultiTemplateParamsArg TemplateParamLists,
12879                                   SourceLocation UsingLoc, UnqualifiedId &Name,
12880                                   const ParsedAttributesView &AttrList,
12881                                   TypeResult Type, Decl *DeclFromDeclSpec) {
12882   // Skip up to the relevant declaration scope.
12883   while (S->isTemplateParamScope())
12884     S = S->getParent();
12885   assert((S->getFlags() & Scope::DeclScope) &&
12886          "got alias-declaration outside of declaration scope");
12887 
12888   if (Type.isInvalid())
12889     return nullptr;
12890 
12891   bool Invalid = false;
12892   DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12893   TypeSourceInfo *TInfo = nullptr;
12894   GetTypeFromParser(Type.get(), &TInfo);
12895 
12896   if (DiagnoseClassNameShadow(CurContext, NameInfo))
12897     return nullptr;
12898 
12899   if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12900                                       UPPC_DeclarationType)) {
12901     Invalid = true;
12902     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12903                                              TInfo->getTypeLoc().getBeginLoc());
12904   }
12905 
12906   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12907                         TemplateParamLists.size()
12908                             ? forRedeclarationInCurContext()
12909                             : ForVisibleRedeclaration);
12910   LookupName(Previous, S);
12911 
12912   // Warn about shadowing the name of a template parameter.
12913   if (Previous.isSingleResult() &&
12914       Previous.getFoundDecl()->isTemplateParameter()) {
12915     DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12916     Previous.clear();
12917   }
12918 
12919   assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12920          "name in alias declaration must be an identifier");
12921   TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12922                                                Name.StartLocation,
12923                                                Name.Identifier, TInfo);
12924 
12925   NewTD->setAccess(AS);
12926 
12927   if (Invalid)
12928     NewTD->setInvalidDecl();
12929 
12930   ProcessDeclAttributeList(S, NewTD, AttrList);
12931   AddPragmaAttributes(S, NewTD);
12932 
12933   CheckTypedefForVariablyModifiedType(S, NewTD);
12934   Invalid |= NewTD->isInvalidDecl();
12935 
12936   bool Redeclaration = false;
12937 
12938   NamedDecl *NewND;
12939   if (TemplateParamLists.size()) {
12940     TypeAliasTemplateDecl *OldDecl = nullptr;
12941     TemplateParameterList *OldTemplateParams = nullptr;
12942 
12943     if (TemplateParamLists.size() != 1) {
12944       Diag(UsingLoc, diag::err_alias_template_extra_headers)
12945         << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12946          TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12947     }
12948     TemplateParameterList *TemplateParams = TemplateParamLists[0];
12949 
12950     // Check that we can declare a template here.
12951     if (CheckTemplateDeclScope(S, TemplateParams))
12952       return nullptr;
12953 
12954     // Only consider previous declarations in the same scope.
12955     FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12956                          /*ExplicitInstantiationOrSpecialization*/false);
12957     if (!Previous.empty()) {
12958       Redeclaration = true;
12959 
12960       OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12961       if (!OldDecl && !Invalid) {
12962         Diag(UsingLoc, diag::err_redefinition_different_kind)
12963           << Name.Identifier;
12964 
12965         NamedDecl *OldD = Previous.getRepresentativeDecl();
12966         if (OldD->getLocation().isValid())
12967           Diag(OldD->getLocation(), diag::note_previous_definition);
12968 
12969         Invalid = true;
12970       }
12971 
12972       if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12973         if (TemplateParameterListsAreEqual(TemplateParams,
12974                                            OldDecl->getTemplateParameters(),
12975                                            /*Complain=*/true,
12976                                            TPL_TemplateMatch))
12977           OldTemplateParams =
12978               OldDecl->getMostRecentDecl()->getTemplateParameters();
12979         else
12980           Invalid = true;
12981 
12982         TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12983         if (!Invalid &&
12984             !Context.hasSameType(OldTD->getUnderlyingType(),
12985                                  NewTD->getUnderlyingType())) {
12986           // FIXME: The C++0x standard does not clearly say this is ill-formed,
12987           // but we can't reasonably accept it.
12988           Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12989             << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12990           if (OldTD->getLocation().isValid())
12991             Diag(OldTD->getLocation(), diag::note_previous_definition);
12992           Invalid = true;
12993         }
12994       }
12995     }
12996 
12997     // Merge any previous default template arguments into our parameters,
12998     // and check the parameter list.
12999     if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
13000                                    TPC_TypeAliasTemplate))
13001       return nullptr;
13002 
13003     TypeAliasTemplateDecl *NewDecl =
13004       TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
13005                                     Name.Identifier, TemplateParams,
13006                                     NewTD);
13007     NewTD->setDescribedAliasTemplate(NewDecl);
13008 
13009     NewDecl->setAccess(AS);
13010 
13011     if (Invalid)
13012       NewDecl->setInvalidDecl();
13013     else if (OldDecl) {
13014       NewDecl->setPreviousDecl(OldDecl);
13015       CheckRedeclarationInModule(NewDecl, OldDecl);
13016     }
13017 
13018     NewND = NewDecl;
13019   } else {
13020     if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
13021       setTagNameForLinkagePurposes(TD, NewTD);
13022       handleTagNumbering(TD, S);
13023     }
13024     ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
13025     NewND = NewTD;
13026   }
13027 
13028   PushOnScopeChains(NewND, S);
13029   ActOnDocumentableDecl(NewND);
13030   return NewND;
13031 }
13032 
13033 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13034                                    SourceLocation AliasLoc,
13035                                    IdentifierInfo *Alias, CXXScopeSpec &SS,
13036                                    SourceLocation IdentLoc,
13037                                    IdentifierInfo *Ident) {
13038 
13039   // Lookup the namespace name.
13040   LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13041   LookupParsedName(R, S, &SS);
13042 
13043   if (R.isAmbiguous())
13044     return nullptr;
13045 
13046   if (R.empty()) {
13047     if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
13048       Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
13049       return nullptr;
13050     }
13051   }
13052   assert(!R.isAmbiguous() && !R.empty());
13053   NamedDecl *ND = R.getRepresentativeDecl();
13054 
13055   // Check if we have a previous declaration with the same name.
13056   LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13057                      ForVisibleRedeclaration);
13058   LookupName(PrevR, S);
13059 
13060   // Check we're not shadowing a template parameter.
13061   if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13062     DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
13063     PrevR.clear();
13064   }
13065 
13066   // Filter out any other lookup result from an enclosing scope.
13067   FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
13068                        /*AllowInlineNamespace*/false);
13069 
13070   // Find the previous declaration and check that we can redeclare it.
13071   NamespaceAliasDecl *Prev = nullptr;
13072   if (PrevR.isSingleResult()) {
13073     NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
13074     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
13075       // We already have an alias with the same name that points to the same
13076       // namespace; check that it matches.
13077       if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
13078         Prev = AD;
13079       } else if (isVisible(PrevDecl)) {
13080         Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
13081           << Alias;
13082         Diag(AD->getLocation(), diag::note_previous_namespace_alias)
13083           << AD->getNamespace();
13084         return nullptr;
13085       }
13086     } else if (isVisible(PrevDecl)) {
13087       unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
13088                             ? diag::err_redefinition
13089                             : diag::err_redefinition_different_kind;
13090       Diag(AliasLoc, DiagID) << Alias;
13091       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13092       return nullptr;
13093     }
13094   }
13095 
13096   // The use of a nested name specifier may trigger deprecation warnings.
13097   DiagnoseUseOfDecl(ND, IdentLoc);
13098 
13099   NamespaceAliasDecl *AliasDecl =
13100     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13101                                Alias, SS.getWithLocInContext(Context),
13102                                IdentLoc, ND);
13103   if (Prev)
13104     AliasDecl->setPreviousDecl(Prev);
13105 
13106   PushOnScopeChains(AliasDecl, S);
13107   return AliasDecl;
13108 }
13109 
13110 namespace {
13111 struct SpecialMemberExceptionSpecInfo
13112     : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13113   SourceLocation Loc;
13114   Sema::ImplicitExceptionSpecification ExceptSpec;
13115 
13116   SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13117                                  Sema::CXXSpecialMember CSM,
13118                                  Sema::InheritedConstructorInfo *ICI,
13119                                  SourceLocation Loc)
13120       : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13121 
13122   bool visitBase(CXXBaseSpecifier *Base);
13123   bool visitField(FieldDecl *FD);
13124 
13125   void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13126                            unsigned Quals);
13127 
13128   void visitSubobjectCall(Subobject Subobj,
13129                           Sema::SpecialMemberOverloadResult SMOR);
13130 };
13131 }
13132 
13133 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13134   auto *RT = Base->getType()->getAs<RecordType>();
13135   if (!RT)
13136     return false;
13137 
13138   auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13139   Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13140   if (auto *BaseCtor = SMOR.getMethod()) {
13141     visitSubobjectCall(Base, BaseCtor);
13142     return false;
13143   }
13144 
13145   visitClassSubobject(BaseClass, Base, 0);
13146   return false;
13147 }
13148 
13149 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13150   if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13151     Expr *E = FD->getInClassInitializer();
13152     if (!E)
13153       // FIXME: It's a little wasteful to build and throw away a
13154       // CXXDefaultInitExpr here.
13155       // FIXME: We should have a single context note pointing at Loc, and
13156       // this location should be MD->getLocation() instead, since that's
13157       // the location where we actually use the default init expression.
13158       E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13159     if (E)
13160       ExceptSpec.CalledExpr(E);
13161   } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13162                             ->getAs<RecordType>()) {
13163     visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13164                         FD->getType().getCVRQualifiers());
13165   }
13166   return false;
13167 }
13168 
13169 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13170                                                          Subobject Subobj,
13171                                                          unsigned Quals) {
13172   FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13173   bool IsMutable = Field && Field->isMutable();
13174   visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13175 }
13176 
13177 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13178     Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13179   // Note, if lookup fails, it doesn't matter what exception specification we
13180   // choose because the special member will be deleted.
13181   if (CXXMethodDecl *MD = SMOR.getMethod())
13182     ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13183 }
13184 
13185 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13186   llvm::APSInt Result;
13187   ExprResult Converted = CheckConvertedConstantExpression(
13188       ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13189   ExplicitSpec.setExpr(Converted.get());
13190   if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13191     ExplicitSpec.setKind(Result.getBoolValue()
13192                              ? ExplicitSpecKind::ResolvedTrue
13193                              : ExplicitSpecKind::ResolvedFalse);
13194     return true;
13195   }
13196   ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13197   return false;
13198 }
13199 
13200 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13201   ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13202   if (!ExplicitExpr->isTypeDependent())
13203     tryResolveExplicitSpecifier(ES);
13204   return ES;
13205 }
13206 
13207 static Sema::ImplicitExceptionSpecification
13208 ComputeDefaultedSpecialMemberExceptionSpec(
13209     Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13210     Sema::InheritedConstructorInfo *ICI) {
13211   ComputingExceptionSpec CES(S, MD, Loc);
13212 
13213   CXXRecordDecl *ClassDecl = MD->getParent();
13214 
13215   // C++ [except.spec]p14:
13216   //   An implicitly declared special member function (Clause 12) shall have an
13217   //   exception-specification. [...]
13218   SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13219   if (ClassDecl->isInvalidDecl())
13220     return Info.ExceptSpec;
13221 
13222   // FIXME: If this diagnostic fires, we're probably missing a check for
13223   // attempting to resolve an exception specification before it's known
13224   // at a higher level.
13225   if (S.RequireCompleteType(MD->getLocation(),
13226                             S.Context.getRecordType(ClassDecl),
13227                             diag::err_exception_spec_incomplete_type))
13228     return Info.ExceptSpec;
13229 
13230   // C++1z [except.spec]p7:
13231   //   [Look for exceptions thrown by] a constructor selected [...] to
13232   //   initialize a potentially constructed subobject,
13233   // C++1z [except.spec]p8:
13234   //   The exception specification for an implicitly-declared destructor, or a
13235   //   destructor without a noexcept-specifier, is potentially-throwing if and
13236   //   only if any of the destructors for any of its potentially constructed
13237   //   subojects is potentially throwing.
13238   // FIXME: We respect the first rule but ignore the "potentially constructed"
13239   // in the second rule to resolve a core issue (no number yet) that would have
13240   // us reject:
13241   //   struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13242   //   struct B : A {};
13243   //   struct C : B { void f(); };
13244   // ... due to giving B::~B() a non-throwing exception specification.
13245   Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13246                                 : Info.VisitAllBases);
13247 
13248   return Info.ExceptSpec;
13249 }
13250 
13251 namespace {
13252 /// RAII object to register a special member as being currently declared.
13253 struct DeclaringSpecialMember {
13254   Sema &S;
13255   Sema::SpecialMemberDecl D;
13256   Sema::ContextRAII SavedContext;
13257   bool WasAlreadyBeingDeclared;
13258 
13259   DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13260       : S(S), D(RD, CSM), SavedContext(S, RD) {
13261     WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13262     if (WasAlreadyBeingDeclared)
13263       // This almost never happens, but if it does, ensure that our cache
13264       // doesn't contain a stale result.
13265       S.SpecialMemberCache.clear();
13266     else {
13267       // Register a note to be produced if we encounter an error while
13268       // declaring the special member.
13269       Sema::CodeSynthesisContext Ctx;
13270       Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13271       // FIXME: We don't have a location to use here. Using the class's
13272       // location maintains the fiction that we declare all special members
13273       // with the class, but (1) it's not clear that lying about that helps our
13274       // users understand what's going on, and (2) there may be outer contexts
13275       // on the stack (some of which are relevant) and printing them exposes
13276       // our lies.
13277       Ctx.PointOfInstantiation = RD->getLocation();
13278       Ctx.Entity = RD;
13279       Ctx.SpecialMember = CSM;
13280       S.pushCodeSynthesisContext(Ctx);
13281     }
13282   }
13283   ~DeclaringSpecialMember() {
13284     if (!WasAlreadyBeingDeclared) {
13285       S.SpecialMembersBeingDeclared.erase(D);
13286       S.popCodeSynthesisContext();
13287     }
13288   }
13289 
13290   /// Are we already trying to declare this special member?
13291   bool isAlreadyBeingDeclared() const {
13292     return WasAlreadyBeingDeclared;
13293   }
13294 };
13295 }
13296 
13297 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13298   // Look up any existing declarations, but don't trigger declaration of all
13299   // implicit special members with this name.
13300   DeclarationName Name = FD->getDeclName();
13301   LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13302                  ForExternalRedeclaration);
13303   for (auto *D : FD->getParent()->lookup(Name))
13304     if (auto *Acceptable = R.getAcceptableDecl(D))
13305       R.addDecl(Acceptable);
13306   R.resolveKind();
13307   R.suppressDiagnostics();
13308 
13309   CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
13310 }
13311 
13312 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13313                                           QualType ResultTy,
13314                                           ArrayRef<QualType> Args) {
13315   // Build an exception specification pointing back at this constructor.
13316   FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13317 
13318   LangAS AS = getDefaultCXXMethodAddrSpace();
13319   if (AS != LangAS::Default) {
13320     EPI.TypeQuals.addAddressSpace(AS);
13321   }
13322 
13323   auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13324   SpecialMem->setType(QT);
13325 
13326   // During template instantiation of implicit special member functions we need
13327   // a reliable TypeSourceInfo for the function prototype in order to allow
13328   // functions to be substituted.
13329   if (inTemplateInstantiation() &&
13330       cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13331     TypeSourceInfo *TSI =
13332         Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13333     SpecialMem->setTypeSourceInfo(TSI);
13334   }
13335 }
13336 
13337 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13338                                                      CXXRecordDecl *ClassDecl) {
13339   // C++ [class.ctor]p5:
13340   //   A default constructor for a class X is a constructor of class X
13341   //   that can be called without an argument. If there is no
13342   //   user-declared constructor for class X, a default constructor is
13343   //   implicitly declared. An implicitly-declared default constructor
13344   //   is an inline public member of its class.
13345   assert(ClassDecl->needsImplicitDefaultConstructor() &&
13346          "Should not build implicit default constructor!");
13347 
13348   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13349   if (DSM.isAlreadyBeingDeclared())
13350     return nullptr;
13351 
13352   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13353                                                      CXXDefaultConstructor,
13354                                                      false);
13355 
13356   // Create the actual constructor declaration.
13357   CanQualType ClassType
13358     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13359   SourceLocation ClassLoc = ClassDecl->getLocation();
13360   DeclarationName Name
13361     = Context.DeclarationNames.getCXXConstructorName(ClassType);
13362   DeclarationNameInfo NameInfo(Name, ClassLoc);
13363   CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13364       Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13365       /*TInfo=*/nullptr, ExplicitSpecifier(),
13366       getCurFPFeatures().isFPConstrained(),
13367       /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13368       Constexpr ? ConstexprSpecKind::Constexpr
13369                 : ConstexprSpecKind::Unspecified);
13370   DefaultCon->setAccess(AS_public);
13371   DefaultCon->setDefaulted();
13372 
13373   if (getLangOpts().CUDA) {
13374     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13375                                             DefaultCon,
13376                                             /* ConstRHS */ false,
13377                                             /* Diagnose */ false);
13378   }
13379 
13380   setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13381 
13382   // We don't need to use SpecialMemberIsTrivial here; triviality for default
13383   // constructors is easy to compute.
13384   DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13385 
13386   // Note that we have declared this constructor.
13387   ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13388 
13389   Scope *S = getScopeForContext(ClassDecl);
13390   CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13391 
13392   if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13393     SetDeclDeleted(DefaultCon, ClassLoc);
13394 
13395   if (S)
13396     PushOnScopeChains(DefaultCon, S, false);
13397   ClassDecl->addDecl(DefaultCon);
13398 
13399   return DefaultCon;
13400 }
13401 
13402 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13403                                             CXXConstructorDecl *Constructor) {
13404   assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
13405           !Constructor->doesThisDeclarationHaveABody() &&
13406           !Constructor->isDeleted()) &&
13407     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
13408   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13409     return;
13410 
13411   CXXRecordDecl *ClassDecl = Constructor->getParent();
13412   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
13413 
13414   SynthesizedFunctionScope Scope(*this, Constructor);
13415 
13416   // The exception specification is needed because we are defining the
13417   // function.
13418   ResolveExceptionSpec(CurrentLocation,
13419                        Constructor->getType()->castAs<FunctionProtoType>());
13420   MarkVTableUsed(CurrentLocation, ClassDecl);
13421 
13422   // Add a context note for diagnostics produced after this point.
13423   Scope.addContextNote(CurrentLocation);
13424 
13425   if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13426     Constructor->setInvalidDecl();
13427     return;
13428   }
13429 
13430   SourceLocation Loc = Constructor->getEndLoc().isValid()
13431                            ? Constructor->getEndLoc()
13432                            : Constructor->getLocation();
13433   Constructor->setBody(new (Context) CompoundStmt(Loc));
13434   Constructor->markUsed(Context);
13435 
13436   if (ASTMutationListener *L = getASTMutationListener()) {
13437     L->CompletedImplicitDefinition(Constructor);
13438   }
13439 
13440   DiagnoseUninitializedFields(*this, Constructor);
13441 }
13442 
13443 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13444   // Perform any delayed checks on exception specifications.
13445   CheckDelayedMemberExceptionSpecs();
13446 }
13447 
13448 /// Find or create the fake constructor we synthesize to model constructing an
13449 /// object of a derived class via a constructor of a base class.
13450 CXXConstructorDecl *
13451 Sema::findInheritingConstructor(SourceLocation Loc,
13452                                 CXXConstructorDecl *BaseCtor,
13453                                 ConstructorUsingShadowDecl *Shadow) {
13454   CXXRecordDecl *Derived = Shadow->getParent();
13455   SourceLocation UsingLoc = Shadow->getLocation();
13456 
13457   // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13458   // For now we use the name of the base class constructor as a member of the
13459   // derived class to indicate a (fake) inherited constructor name.
13460   DeclarationName Name = BaseCtor->getDeclName();
13461 
13462   // Check to see if we already have a fake constructor for this inherited
13463   // constructor call.
13464   for (NamedDecl *Ctor : Derived->lookup(Name))
13465     if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13466                                ->getInheritedConstructor()
13467                                .getConstructor(),
13468                            BaseCtor))
13469       return cast<CXXConstructorDecl>(Ctor);
13470 
13471   DeclarationNameInfo NameInfo(Name, UsingLoc);
13472   TypeSourceInfo *TInfo =
13473       Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13474   FunctionProtoTypeLoc ProtoLoc =
13475       TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13476 
13477   // Check the inherited constructor is valid and find the list of base classes
13478   // from which it was inherited.
13479   InheritedConstructorInfo ICI(*this, Loc, Shadow);
13480 
13481   bool Constexpr =
13482       BaseCtor->isConstexpr() &&
13483       defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13484                                         false, BaseCtor, &ICI);
13485 
13486   CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13487       Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13488       BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13489       /*isInline=*/true,
13490       /*isImplicitlyDeclared=*/true,
13491       Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13492       InheritedConstructor(Shadow, BaseCtor),
13493       BaseCtor->getTrailingRequiresClause());
13494   if (Shadow->isInvalidDecl())
13495     DerivedCtor->setInvalidDecl();
13496 
13497   // Build an unevaluated exception specification for this fake constructor.
13498   const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13499   FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13500   EPI.ExceptionSpec.Type = EST_Unevaluated;
13501   EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13502   DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13503                                                FPT->getParamTypes(), EPI));
13504 
13505   // Build the parameter declarations.
13506   SmallVector<ParmVarDecl *, 16> ParamDecls;
13507   for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13508     TypeSourceInfo *TInfo =
13509         Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13510     ParmVarDecl *PD = ParmVarDecl::Create(
13511         Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13512         FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13513     PD->setScopeInfo(0, I);
13514     PD->setImplicit();
13515     // Ensure attributes are propagated onto parameters (this matters for
13516     // format, pass_object_size, ...).
13517     mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13518     ParamDecls.push_back(PD);
13519     ProtoLoc.setParam(I, PD);
13520   }
13521 
13522   // Set up the new constructor.
13523   assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13524   DerivedCtor->setAccess(BaseCtor->getAccess());
13525   DerivedCtor->setParams(ParamDecls);
13526   Derived->addDecl(DerivedCtor);
13527 
13528   if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13529     SetDeclDeleted(DerivedCtor, UsingLoc);
13530 
13531   return DerivedCtor;
13532 }
13533 
13534 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13535   InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13536                                Ctor->getInheritedConstructor().getShadowDecl());
13537   ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13538                             /*Diagnose*/true);
13539 }
13540 
13541 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13542                                        CXXConstructorDecl *Constructor) {
13543   CXXRecordDecl *ClassDecl = Constructor->getParent();
13544   assert(Constructor->getInheritedConstructor() &&
13545          !Constructor->doesThisDeclarationHaveABody() &&
13546          !Constructor->isDeleted());
13547   if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13548     return;
13549 
13550   // Initializations are performed "as if by a defaulted default constructor",
13551   // so enter the appropriate scope.
13552   SynthesizedFunctionScope Scope(*this, Constructor);
13553 
13554   // The exception specification is needed because we are defining the
13555   // function.
13556   ResolveExceptionSpec(CurrentLocation,
13557                        Constructor->getType()->castAs<FunctionProtoType>());
13558   MarkVTableUsed(CurrentLocation, ClassDecl);
13559 
13560   // Add a context note for diagnostics produced after this point.
13561   Scope.addContextNote(CurrentLocation);
13562 
13563   ConstructorUsingShadowDecl *Shadow =
13564       Constructor->getInheritedConstructor().getShadowDecl();
13565   CXXConstructorDecl *InheritedCtor =
13566       Constructor->getInheritedConstructor().getConstructor();
13567 
13568   // [class.inhctor.init]p1:
13569   //   initialization proceeds as if a defaulted default constructor is used to
13570   //   initialize the D object and each base class subobject from which the
13571   //   constructor was inherited
13572 
13573   InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13574   CXXRecordDecl *RD = Shadow->getParent();
13575   SourceLocation InitLoc = Shadow->getLocation();
13576 
13577   // Build explicit initializers for all base classes from which the
13578   // constructor was inherited.
13579   SmallVector<CXXCtorInitializer*, 8> Inits;
13580   for (bool VBase : {false, true}) {
13581     for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13582       if (B.isVirtual() != VBase)
13583         continue;
13584 
13585       auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13586       if (!BaseRD)
13587         continue;
13588 
13589       auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13590       if (!BaseCtor.first)
13591         continue;
13592 
13593       MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13594       ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13595           InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13596 
13597       auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13598       Inits.push_back(new (Context) CXXCtorInitializer(
13599           Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13600           SourceLocation()));
13601     }
13602   }
13603 
13604   // We now proceed as if for a defaulted default constructor, with the relevant
13605   // initializers replaced.
13606 
13607   if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13608     Constructor->setInvalidDecl();
13609     return;
13610   }
13611 
13612   Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13613   Constructor->markUsed(Context);
13614 
13615   if (ASTMutationListener *L = getASTMutationListener()) {
13616     L->CompletedImplicitDefinition(Constructor);
13617   }
13618 
13619   DiagnoseUninitializedFields(*this, Constructor);
13620 }
13621 
13622 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13623   // C++ [class.dtor]p2:
13624   //   If a class has no user-declared destructor, a destructor is
13625   //   declared implicitly. An implicitly-declared destructor is an
13626   //   inline public member of its class.
13627   assert(ClassDecl->needsImplicitDestructor());
13628 
13629   DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13630   if (DSM.isAlreadyBeingDeclared())
13631     return nullptr;
13632 
13633   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13634                                                      CXXDestructor,
13635                                                      false);
13636 
13637   // Create the actual destructor declaration.
13638   CanQualType ClassType
13639     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13640   SourceLocation ClassLoc = ClassDecl->getLocation();
13641   DeclarationName Name
13642     = Context.DeclarationNames.getCXXDestructorName(ClassType);
13643   DeclarationNameInfo NameInfo(Name, ClassLoc);
13644   CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
13645       Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13646       getCurFPFeatures().isFPConstrained(),
13647       /*isInline=*/true,
13648       /*isImplicitlyDeclared=*/true,
13649       Constexpr ? ConstexprSpecKind::Constexpr
13650                 : ConstexprSpecKind::Unspecified);
13651   Destructor->setAccess(AS_public);
13652   Destructor->setDefaulted();
13653 
13654   if (getLangOpts().CUDA) {
13655     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13656                                             Destructor,
13657                                             /* ConstRHS */ false,
13658                                             /* Diagnose */ false);
13659   }
13660 
13661   setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13662 
13663   // We don't need to use SpecialMemberIsTrivial here; triviality for
13664   // destructors is easy to compute.
13665   Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13666   Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13667                                 ClassDecl->hasTrivialDestructorForCall());
13668 
13669   // Note that we have declared this destructor.
13670   ++getASTContext().NumImplicitDestructorsDeclared;
13671 
13672   Scope *S = getScopeForContext(ClassDecl);
13673   CheckImplicitSpecialMemberDeclaration(S, Destructor);
13674 
13675   // We can't check whether an implicit destructor is deleted before we complete
13676   // the definition of the class, because its validity depends on the alignment
13677   // of the class. We'll check this from ActOnFields once the class is complete.
13678   if (ClassDecl->isCompleteDefinition() &&
13679       ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13680     SetDeclDeleted(Destructor, ClassLoc);
13681 
13682   // Introduce this destructor into its scope.
13683   if (S)
13684     PushOnScopeChains(Destructor, S, false);
13685   ClassDecl->addDecl(Destructor);
13686 
13687   return Destructor;
13688 }
13689 
13690 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13691                                     CXXDestructorDecl *Destructor) {
13692   assert((Destructor->isDefaulted() &&
13693           !Destructor->doesThisDeclarationHaveABody() &&
13694           !Destructor->isDeleted()) &&
13695          "DefineImplicitDestructor - call it for implicit default dtor");
13696   if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13697     return;
13698 
13699   CXXRecordDecl *ClassDecl = Destructor->getParent();
13700   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13701 
13702   SynthesizedFunctionScope Scope(*this, Destructor);
13703 
13704   // The exception specification is needed because we are defining the
13705   // function.
13706   ResolveExceptionSpec(CurrentLocation,
13707                        Destructor->getType()->castAs<FunctionProtoType>());
13708   MarkVTableUsed(CurrentLocation, ClassDecl);
13709 
13710   // Add a context note for diagnostics produced after this point.
13711   Scope.addContextNote(CurrentLocation);
13712 
13713   MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13714                                          Destructor->getParent());
13715 
13716   if (CheckDestructor(Destructor)) {
13717     Destructor->setInvalidDecl();
13718     return;
13719   }
13720 
13721   SourceLocation Loc = Destructor->getEndLoc().isValid()
13722                            ? Destructor->getEndLoc()
13723                            : Destructor->getLocation();
13724   Destructor->setBody(new (Context) CompoundStmt(Loc));
13725   Destructor->markUsed(Context);
13726 
13727   if (ASTMutationListener *L = getASTMutationListener()) {
13728     L->CompletedImplicitDefinition(Destructor);
13729   }
13730 }
13731 
13732 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13733                                           CXXDestructorDecl *Destructor) {
13734   if (Destructor->isInvalidDecl())
13735     return;
13736 
13737   CXXRecordDecl *ClassDecl = Destructor->getParent();
13738   assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13739          "implicit complete dtors unneeded outside MS ABI");
13740   assert(ClassDecl->getNumVBases() > 0 &&
13741          "complete dtor only exists for classes with vbases");
13742 
13743   SynthesizedFunctionScope Scope(*this, Destructor);
13744 
13745   // Add a context note for diagnostics produced after this point.
13746   Scope.addContextNote(CurrentLocation);
13747 
13748   MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13749 }
13750 
13751 /// Perform any semantic analysis which needs to be delayed until all
13752 /// pending class member declarations have been parsed.
13753 void Sema::ActOnFinishCXXMemberDecls() {
13754   // If the context is an invalid C++ class, just suppress these checks.
13755   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13756     if (Record->isInvalidDecl()) {
13757       DelayedOverridingExceptionSpecChecks.clear();
13758       DelayedEquivalentExceptionSpecChecks.clear();
13759       return;
13760     }
13761     checkForMultipleExportedDefaultConstructors(*this, Record);
13762   }
13763 }
13764 
13765 void Sema::ActOnFinishCXXNonNestedClass() {
13766   referenceDLLExportedClassMethods();
13767 
13768   if (!DelayedDllExportMemberFunctions.empty()) {
13769     SmallVector<CXXMethodDecl*, 4> WorkList;
13770     std::swap(DelayedDllExportMemberFunctions, WorkList);
13771     for (CXXMethodDecl *M : WorkList) {
13772       DefineDefaultedFunction(*this, M, M->getLocation());
13773 
13774       // Pass the method to the consumer to get emitted. This is not necessary
13775       // for explicit instantiation definitions, as they will get emitted
13776       // anyway.
13777       if (M->getParent()->getTemplateSpecializationKind() !=
13778           TSK_ExplicitInstantiationDefinition)
13779         ActOnFinishInlineFunctionDef(M);
13780     }
13781   }
13782 }
13783 
13784 void Sema::referenceDLLExportedClassMethods() {
13785   if (!DelayedDllExportClasses.empty()) {
13786     // Calling ReferenceDllExportedMembers might cause the current function to
13787     // be called again, so use a local copy of DelayedDllExportClasses.
13788     SmallVector<CXXRecordDecl *, 4> WorkList;
13789     std::swap(DelayedDllExportClasses, WorkList);
13790     for (CXXRecordDecl *Class : WorkList)
13791       ReferenceDllExportedMembers(*this, Class);
13792   }
13793 }
13794 
13795 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13796   assert(getLangOpts().CPlusPlus11 &&
13797          "adjusting dtor exception specs was introduced in c++11");
13798 
13799   if (Destructor->isDependentContext())
13800     return;
13801 
13802   // C++11 [class.dtor]p3:
13803   //   A declaration of a destructor that does not have an exception-
13804   //   specification is implicitly considered to have the same exception-
13805   //   specification as an implicit declaration.
13806   const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13807   if (DtorType->hasExceptionSpec())
13808     return;
13809 
13810   // Replace the destructor's type, building off the existing one. Fortunately,
13811   // the only thing of interest in the destructor type is its extended info.
13812   // The return and arguments are fixed.
13813   FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13814   EPI.ExceptionSpec.Type = EST_Unevaluated;
13815   EPI.ExceptionSpec.SourceDecl = Destructor;
13816   Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13817 
13818   // FIXME: If the destructor has a body that could throw, and the newly created
13819   // spec doesn't allow exceptions, we should emit a warning, because this
13820   // change in behavior can break conforming C++03 programs at runtime.
13821   // However, we don't have a body or an exception specification yet, so it
13822   // needs to be done somewhere else.
13823 }
13824 
13825 namespace {
13826 /// An abstract base class for all helper classes used in building the
13827 //  copy/move operators. These classes serve as factory functions and help us
13828 //  avoid using the same Expr* in the AST twice.
13829 class ExprBuilder {
13830   ExprBuilder(const ExprBuilder&) = delete;
13831   ExprBuilder &operator=(const ExprBuilder&) = delete;
13832 
13833 protected:
13834   static Expr *assertNotNull(Expr *E) {
13835     assert(E && "Expression construction must not fail.");
13836     return E;
13837   }
13838 
13839 public:
13840   ExprBuilder() {}
13841   virtual ~ExprBuilder() {}
13842 
13843   virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13844 };
13845 
13846 class RefBuilder: public ExprBuilder {
13847   VarDecl *Var;
13848   QualType VarType;
13849 
13850 public:
13851   Expr *build(Sema &S, SourceLocation Loc) const override {
13852     return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13853   }
13854 
13855   RefBuilder(VarDecl *Var, QualType VarType)
13856       : Var(Var), VarType(VarType) {}
13857 };
13858 
13859 class ThisBuilder: public ExprBuilder {
13860 public:
13861   Expr *build(Sema &S, SourceLocation Loc) const override {
13862     return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13863   }
13864 };
13865 
13866 class CastBuilder: public ExprBuilder {
13867   const ExprBuilder &Builder;
13868   QualType Type;
13869   ExprValueKind Kind;
13870   const CXXCastPath &Path;
13871 
13872 public:
13873   Expr *build(Sema &S, SourceLocation Loc) const override {
13874     return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13875                                              CK_UncheckedDerivedToBase, Kind,
13876                                              &Path).get());
13877   }
13878 
13879   CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13880               const CXXCastPath &Path)
13881       : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13882 };
13883 
13884 class DerefBuilder: public ExprBuilder {
13885   const ExprBuilder &Builder;
13886 
13887 public:
13888   Expr *build(Sema &S, SourceLocation Loc) const override {
13889     return assertNotNull(
13890         S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13891   }
13892 
13893   DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13894 };
13895 
13896 class MemberBuilder: public ExprBuilder {
13897   const ExprBuilder &Builder;
13898   QualType Type;
13899   CXXScopeSpec SS;
13900   bool IsArrow;
13901   LookupResult &MemberLookup;
13902 
13903 public:
13904   Expr *build(Sema &S, SourceLocation Loc) const override {
13905     return assertNotNull(S.BuildMemberReferenceExpr(
13906         Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13907         nullptr, MemberLookup, nullptr, nullptr).get());
13908   }
13909 
13910   MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13911                 LookupResult &MemberLookup)
13912       : Builder(Builder), Type(Type), IsArrow(IsArrow),
13913         MemberLookup(MemberLookup) {}
13914 };
13915 
13916 class MoveCastBuilder: public ExprBuilder {
13917   const ExprBuilder &Builder;
13918 
13919 public:
13920   Expr *build(Sema &S, SourceLocation Loc) const override {
13921     return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13922   }
13923 
13924   MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13925 };
13926 
13927 class LvalueConvBuilder: public ExprBuilder {
13928   const ExprBuilder &Builder;
13929 
13930 public:
13931   Expr *build(Sema &S, SourceLocation Loc) const override {
13932     return assertNotNull(
13933         S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13934   }
13935 
13936   LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13937 };
13938 
13939 class SubscriptBuilder: public ExprBuilder {
13940   const ExprBuilder &Base;
13941   const ExprBuilder &Index;
13942 
13943 public:
13944   Expr *build(Sema &S, SourceLocation Loc) const override {
13945     return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13946         Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13947   }
13948 
13949   SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13950       : Base(Base), Index(Index) {}
13951 };
13952 
13953 } // end anonymous namespace
13954 
13955 /// When generating a defaulted copy or move assignment operator, if a field
13956 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13957 /// do so. This optimization only applies for arrays of scalars, and for arrays
13958 /// of class type where the selected copy/move-assignment operator is trivial.
13959 static StmtResult
13960 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13961                            const ExprBuilder &ToB, const ExprBuilder &FromB) {
13962   // Compute the size of the memory buffer to be copied.
13963   QualType SizeType = S.Context.getSizeType();
13964   llvm::APInt Size(S.Context.getTypeSize(SizeType),
13965                    S.Context.getTypeSizeInChars(T).getQuantity());
13966 
13967   // Take the address of the field references for "from" and "to". We
13968   // directly construct UnaryOperators here because semantic analysis
13969   // does not permit us to take the address of an xvalue.
13970   Expr *From = FromB.build(S, Loc);
13971   From = UnaryOperator::Create(
13972       S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13973       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13974   Expr *To = ToB.build(S, Loc);
13975   To = UnaryOperator::Create(
13976       S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13977       VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13978 
13979   const Type *E = T->getBaseElementTypeUnsafe();
13980   bool NeedsCollectableMemCpy =
13981       E->isRecordType() &&
13982       E->castAs<RecordType>()->getDecl()->hasObjectMember();
13983 
13984   // Create a reference to the __builtin_objc_memmove_collectable function
13985   StringRef MemCpyName = NeedsCollectableMemCpy ?
13986     "__builtin_objc_memmove_collectable" :
13987     "__builtin_memcpy";
13988   LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13989                  Sema::LookupOrdinaryName);
13990   S.LookupName(R, S.TUScope, true);
13991 
13992   FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13993   if (!MemCpy)
13994     // Something went horribly wrong earlier, and we will have complained
13995     // about it.
13996     return StmtError();
13997 
13998   ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13999                                             VK_PRValue, Loc, nullptr);
14000   assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14001 
14002   Expr *CallArgs[] = {
14003     To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
14004   };
14005   ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
14006                                     Loc, CallArgs, Loc);
14007 
14008   assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14009   return Call.getAs<Stmt>();
14010 }
14011 
14012 /// Builds a statement that copies/moves the given entity from \p From to
14013 /// \c To.
14014 ///
14015 /// This routine is used to copy/move the members of a class with an
14016 /// implicitly-declared copy/move assignment operator. When the entities being
14017 /// copied are arrays, this routine builds for loops to copy them.
14018 ///
14019 /// \param S The Sema object used for type-checking.
14020 ///
14021 /// \param Loc The location where the implicit copy/move is being generated.
14022 ///
14023 /// \param T The type of the expressions being copied/moved. Both expressions
14024 /// must have this type.
14025 ///
14026 /// \param To The expression we are copying/moving to.
14027 ///
14028 /// \param From The expression we are copying/moving from.
14029 ///
14030 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14031 /// Otherwise, it's a non-static member subobject.
14032 ///
14033 /// \param Copying Whether we're copying or moving.
14034 ///
14035 /// \param Depth Internal parameter recording the depth of the recursion.
14036 ///
14037 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14038 /// if a memcpy should be used instead.
14039 static StmtResult
14040 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14041                                  const ExprBuilder &To, const ExprBuilder &From,
14042                                  bool CopyingBaseSubobject, bool Copying,
14043                                  unsigned Depth = 0) {
14044   // C++11 [class.copy]p28:
14045   //   Each subobject is assigned in the manner appropriate to its type:
14046   //
14047   //     - if the subobject is of class type, as if by a call to operator= with
14048   //       the subobject as the object expression and the corresponding
14049   //       subobject of x as a single function argument (as if by explicit
14050   //       qualification; that is, ignoring any possible virtual overriding
14051   //       functions in more derived classes);
14052   //
14053   // C++03 [class.copy]p13:
14054   //     - if the subobject is of class type, the copy assignment operator for
14055   //       the class is used (as if by explicit qualification; that is,
14056   //       ignoring any possible virtual overriding functions in more derived
14057   //       classes);
14058   if (const RecordType *RecordTy = T->getAs<RecordType>()) {
14059     CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
14060 
14061     // Look for operator=.
14062     DeclarationName Name
14063       = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14064     LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14065     S.LookupQualifiedName(OpLookup, ClassDecl, false);
14066 
14067     // Prior to C++11, filter out any result that isn't a copy/move-assignment
14068     // operator.
14069     if (!S.getLangOpts().CPlusPlus11) {
14070       LookupResult::Filter F = OpLookup.makeFilter();
14071       while (F.hasNext()) {
14072         NamedDecl *D = F.next();
14073         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
14074           if (Method->isCopyAssignmentOperator() ||
14075               (!Copying && Method->isMoveAssignmentOperator()))
14076             continue;
14077 
14078         F.erase();
14079       }
14080       F.done();
14081     }
14082 
14083     // Suppress the protected check (C++ [class.protected]) for each of the
14084     // assignment operators we found. This strange dance is required when
14085     // we're assigning via a base classes's copy-assignment operator. To
14086     // ensure that we're getting the right base class subobject (without
14087     // ambiguities), we need to cast "this" to that subobject type; to
14088     // ensure that we don't go through the virtual call mechanism, we need
14089     // to qualify the operator= name with the base class (see below). However,
14090     // this means that if the base class has a protected copy assignment
14091     // operator, the protected member access check will fail. So, we
14092     // rewrite "protected" access to "public" access in this case, since we
14093     // know by construction that we're calling from a derived class.
14094     if (CopyingBaseSubobject) {
14095       for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14096            L != LEnd; ++L) {
14097         if (L.getAccess() == AS_protected)
14098           L.setAccess(AS_public);
14099       }
14100     }
14101 
14102     // Create the nested-name-specifier that will be used to qualify the
14103     // reference to operator=; this is required to suppress the virtual
14104     // call mechanism.
14105     CXXScopeSpec SS;
14106     const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14107     SS.MakeTrivial(S.Context,
14108                    NestedNameSpecifier::Create(S.Context, nullptr, false,
14109                                                CanonicalT),
14110                    Loc);
14111 
14112     // Create the reference to operator=.
14113     ExprResult OpEqualRef
14114       = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14115                                    SS, /*TemplateKWLoc=*/SourceLocation(),
14116                                    /*FirstQualifierInScope=*/nullptr,
14117                                    OpLookup,
14118                                    /*TemplateArgs=*/nullptr, /*S*/nullptr,
14119                                    /*SuppressQualifierCheck=*/true);
14120     if (OpEqualRef.isInvalid())
14121       return StmtError();
14122 
14123     // Build the call to the assignment operator.
14124 
14125     Expr *FromInst = From.build(S, Loc);
14126     ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14127                                                   OpEqualRef.getAs<Expr>(),
14128                                                   Loc, FromInst, Loc);
14129     if (Call.isInvalid())
14130       return StmtError();
14131 
14132     // If we built a call to a trivial 'operator=' while copying an array,
14133     // bail out. We'll replace the whole shebang with a memcpy.
14134     CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14135     if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14136       return StmtResult((Stmt*)nullptr);
14137 
14138     // Convert to an expression-statement, and clean up any produced
14139     // temporaries.
14140     return S.ActOnExprStmt(Call);
14141   }
14142 
14143   //     - if the subobject is of scalar type, the built-in assignment
14144   //       operator is used.
14145   const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14146   if (!ArrayTy) {
14147     ExprResult Assignment = S.CreateBuiltinBinOp(
14148         Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14149     if (Assignment.isInvalid())
14150       return StmtError();
14151     return S.ActOnExprStmt(Assignment);
14152   }
14153 
14154   //     - if the subobject is an array, each element is assigned, in the
14155   //       manner appropriate to the element type;
14156 
14157   // Construct a loop over the array bounds, e.g.,
14158   //
14159   //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14160   //
14161   // that will copy each of the array elements.
14162   QualType SizeType = S.Context.getSizeType();
14163 
14164   // Create the iteration variable.
14165   IdentifierInfo *IterationVarName = nullptr;
14166   {
14167     SmallString<8> Str;
14168     llvm::raw_svector_ostream OS(Str);
14169     OS << "__i" << Depth;
14170     IterationVarName = &S.Context.Idents.get(OS.str());
14171   }
14172   VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14173                                           IterationVarName, SizeType,
14174                             S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14175                                           SC_None);
14176 
14177   // Initialize the iteration variable to zero.
14178   llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14179   IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14180 
14181   // Creates a reference to the iteration variable.
14182   RefBuilder IterationVarRef(IterationVar, SizeType);
14183   LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14184 
14185   // Create the DeclStmt that holds the iteration variable.
14186   Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14187 
14188   // Subscript the "from" and "to" expressions with the iteration variable.
14189   SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14190   MoveCastBuilder FromIndexMove(FromIndexCopy);
14191   const ExprBuilder *FromIndex;
14192   if (Copying)
14193     FromIndex = &FromIndexCopy;
14194   else
14195     FromIndex = &FromIndexMove;
14196 
14197   SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14198 
14199   // Build the copy/move for an individual element of the array.
14200   StmtResult Copy =
14201     buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14202                                      ToIndex, *FromIndex, CopyingBaseSubobject,
14203                                      Copying, Depth + 1);
14204   // Bail out if copying fails or if we determined that we should use memcpy.
14205   if (Copy.isInvalid() || !Copy.get())
14206     return Copy;
14207 
14208   // Create the comparison against the array bound.
14209   llvm::APInt Upper
14210     = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14211   Expr *Comparison = BinaryOperator::Create(
14212       S.Context, IterationVarRefRVal.build(S, Loc),
14213       IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14214       S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14215       S.CurFPFeatureOverrides());
14216 
14217   // Create the pre-increment of the iteration variable. We can determine
14218   // whether the increment will overflow based on the value of the array
14219   // bound.
14220   Expr *Increment = UnaryOperator::Create(
14221       S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14222       OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14223 
14224   // Construct the loop that copies all elements of this array.
14225   return S.ActOnForStmt(
14226       Loc, Loc, InitStmt,
14227       S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14228       S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14229 }
14230 
14231 static StmtResult
14232 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14233                       const ExprBuilder &To, const ExprBuilder &From,
14234                       bool CopyingBaseSubobject, bool Copying) {
14235   // Maybe we should use a memcpy?
14236   if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14237       T.isTriviallyCopyableType(S.Context))
14238     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14239 
14240   StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14241                                                      CopyingBaseSubobject,
14242                                                      Copying, 0));
14243 
14244   // If we ended up picking a trivial assignment operator for an array of a
14245   // non-trivially-copyable class type, just emit a memcpy.
14246   if (!Result.isInvalid() && !Result.get())
14247     return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14248 
14249   return Result;
14250 }
14251 
14252 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14253   // Note: The following rules are largely analoguous to the copy
14254   // constructor rules. Note that virtual bases are not taken into account
14255   // for determining the argument type of the operator. Note also that
14256   // operators taking an object instead of a reference are allowed.
14257   assert(ClassDecl->needsImplicitCopyAssignment());
14258 
14259   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14260   if (DSM.isAlreadyBeingDeclared())
14261     return nullptr;
14262 
14263   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14264   LangAS AS = getDefaultCXXMethodAddrSpace();
14265   if (AS != LangAS::Default)
14266     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14267   QualType RetType = Context.getLValueReferenceType(ArgType);
14268   bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14269   if (Const)
14270     ArgType = ArgType.withConst();
14271 
14272   ArgType = Context.getLValueReferenceType(ArgType);
14273 
14274   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14275                                                      CXXCopyAssignment,
14276                                                      Const);
14277 
14278   //   An implicitly-declared copy assignment operator is an inline public
14279   //   member of its class.
14280   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14281   SourceLocation ClassLoc = ClassDecl->getLocation();
14282   DeclarationNameInfo NameInfo(Name, ClassLoc);
14283   CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14284       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14285       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14286       getCurFPFeatures().isFPConstrained(),
14287       /*isInline=*/true,
14288       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14289       SourceLocation());
14290   CopyAssignment->setAccess(AS_public);
14291   CopyAssignment->setDefaulted();
14292   CopyAssignment->setImplicit();
14293 
14294   if (getLangOpts().CUDA) {
14295     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14296                                             CopyAssignment,
14297                                             /* ConstRHS */ Const,
14298                                             /* Diagnose */ false);
14299   }
14300 
14301   setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14302 
14303   // Add the parameter to the operator.
14304   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14305                                                ClassLoc, ClassLoc,
14306                                                /*Id=*/nullptr, ArgType,
14307                                                /*TInfo=*/nullptr, SC_None,
14308                                                nullptr);
14309   CopyAssignment->setParams(FromParam);
14310 
14311   CopyAssignment->setTrivial(
14312     ClassDecl->needsOverloadResolutionForCopyAssignment()
14313       ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14314       : ClassDecl->hasTrivialCopyAssignment());
14315 
14316   // Note that we have added this copy-assignment operator.
14317   ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14318 
14319   Scope *S = getScopeForContext(ClassDecl);
14320   CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14321 
14322   if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14323     ClassDecl->setImplicitCopyAssignmentIsDeleted();
14324     SetDeclDeleted(CopyAssignment, ClassLoc);
14325   }
14326 
14327   if (S)
14328     PushOnScopeChains(CopyAssignment, S, false);
14329   ClassDecl->addDecl(CopyAssignment);
14330 
14331   return CopyAssignment;
14332 }
14333 
14334 /// Diagnose an implicit copy operation for a class which is odr-used, but
14335 /// which is deprecated because the class has a user-declared copy constructor,
14336 /// copy assignment operator, or destructor.
14337 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14338   assert(CopyOp->isImplicit());
14339 
14340   CXXRecordDecl *RD = CopyOp->getParent();
14341   CXXMethodDecl *UserDeclaredOperation = nullptr;
14342 
14343   // In Microsoft mode, assignment operations don't affect constructors and
14344   // vice versa.
14345   if (RD->hasUserDeclaredDestructor()) {
14346     UserDeclaredOperation = RD->getDestructor();
14347   } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14348              RD->hasUserDeclaredCopyConstructor() &&
14349              !S.getLangOpts().MSVCCompat) {
14350     // Find any user-declared copy constructor.
14351     for (auto *I : RD->ctors()) {
14352       if (I->isCopyConstructor()) {
14353         UserDeclaredOperation = I;
14354         break;
14355       }
14356     }
14357     assert(UserDeclaredOperation);
14358   } else if (isa<CXXConstructorDecl>(CopyOp) &&
14359              RD->hasUserDeclaredCopyAssignment() &&
14360              !S.getLangOpts().MSVCCompat) {
14361     // Find any user-declared move assignment operator.
14362     for (auto *I : RD->methods()) {
14363       if (I->isCopyAssignmentOperator()) {
14364         UserDeclaredOperation = I;
14365         break;
14366       }
14367     }
14368     assert(UserDeclaredOperation);
14369   }
14370 
14371   if (UserDeclaredOperation) {
14372     bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14373     bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14374     bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14375     unsigned DiagID =
14376         (UDOIsUserProvided && UDOIsDestructor)
14377             ? diag::warn_deprecated_copy_with_user_provided_dtor
14378         : (UDOIsUserProvided && !UDOIsDestructor)
14379             ? diag::warn_deprecated_copy_with_user_provided_copy
14380         : (!UDOIsUserProvided && UDOIsDestructor)
14381             ? diag::warn_deprecated_copy_with_dtor
14382             : diag::warn_deprecated_copy;
14383     S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14384         << RD << IsCopyAssignment;
14385   }
14386 }
14387 
14388 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14389                                         CXXMethodDecl *CopyAssignOperator) {
14390   assert((CopyAssignOperator->isDefaulted() &&
14391           CopyAssignOperator->isOverloadedOperator() &&
14392           CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
14393           !CopyAssignOperator->doesThisDeclarationHaveABody() &&
14394           !CopyAssignOperator->isDeleted()) &&
14395          "DefineImplicitCopyAssignment called for wrong function");
14396   if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14397     return;
14398 
14399   CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14400   if (ClassDecl->isInvalidDecl()) {
14401     CopyAssignOperator->setInvalidDecl();
14402     return;
14403   }
14404 
14405   SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14406 
14407   // The exception specification is needed because we are defining the
14408   // function.
14409   ResolveExceptionSpec(CurrentLocation,
14410                        CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14411 
14412   // Add a context note for diagnostics produced after this point.
14413   Scope.addContextNote(CurrentLocation);
14414 
14415   // C++11 [class.copy]p18:
14416   //   The [definition of an implicitly declared copy assignment operator] is
14417   //   deprecated if the class has a user-declared copy constructor or a
14418   //   user-declared destructor.
14419   if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14420     diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14421 
14422   // C++0x [class.copy]p30:
14423   //   The implicitly-defined or explicitly-defaulted copy assignment operator
14424   //   for a non-union class X performs memberwise copy assignment of its
14425   //   subobjects. The direct base classes of X are assigned first, in the
14426   //   order of their declaration in the base-specifier-list, and then the
14427   //   immediate non-static data members of X are assigned, in the order in
14428   //   which they were declared in the class definition.
14429 
14430   // The statements that form the synthesized function body.
14431   SmallVector<Stmt*, 8> Statements;
14432 
14433   // The parameter for the "other" object, which we are copying from.
14434   ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14435   Qualifiers OtherQuals = Other->getType().getQualifiers();
14436   QualType OtherRefType = Other->getType();
14437   if (const LValueReferenceType *OtherRef
14438                                 = OtherRefType->getAs<LValueReferenceType>()) {
14439     OtherRefType = OtherRef->getPointeeType();
14440     OtherQuals = OtherRefType.getQualifiers();
14441   }
14442 
14443   // Our location for everything implicitly-generated.
14444   SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14445                            ? CopyAssignOperator->getEndLoc()
14446                            : CopyAssignOperator->getLocation();
14447 
14448   // Builds a DeclRefExpr for the "other" object.
14449   RefBuilder OtherRef(Other, OtherRefType);
14450 
14451   // Builds the "this" pointer.
14452   ThisBuilder This;
14453 
14454   // Assign base classes.
14455   bool Invalid = false;
14456   for (auto &Base : ClassDecl->bases()) {
14457     // Form the assignment:
14458     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14459     QualType BaseType = Base.getType().getUnqualifiedType();
14460     if (!BaseType->isRecordType()) {
14461       Invalid = true;
14462       continue;
14463     }
14464 
14465     CXXCastPath BasePath;
14466     BasePath.push_back(&Base);
14467 
14468     // Construct the "from" expression, which is an implicit cast to the
14469     // appropriately-qualified base type.
14470     CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14471                      VK_LValue, BasePath);
14472 
14473     // Dereference "this".
14474     DerefBuilder DerefThis(This);
14475     CastBuilder To(DerefThis,
14476                    Context.getQualifiedType(
14477                        BaseType, CopyAssignOperator->getMethodQualifiers()),
14478                    VK_LValue, BasePath);
14479 
14480     // Build the copy.
14481     StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14482                                             To, From,
14483                                             /*CopyingBaseSubobject=*/true,
14484                                             /*Copying=*/true);
14485     if (Copy.isInvalid()) {
14486       CopyAssignOperator->setInvalidDecl();
14487       return;
14488     }
14489 
14490     // Success! Record the copy.
14491     Statements.push_back(Copy.getAs<Expr>());
14492   }
14493 
14494   // Assign non-static members.
14495   for (auto *Field : ClassDecl->fields()) {
14496     // FIXME: We should form some kind of AST representation for the implied
14497     // memcpy in a union copy operation.
14498     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14499       continue;
14500 
14501     if (Field->isInvalidDecl()) {
14502       Invalid = true;
14503       continue;
14504     }
14505 
14506     // Check for members of reference type; we can't copy those.
14507     if (Field->getType()->isReferenceType()) {
14508       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14509         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14510       Diag(Field->getLocation(), diag::note_declared_at);
14511       Invalid = true;
14512       continue;
14513     }
14514 
14515     // Check for members of const-qualified, non-class type.
14516     QualType BaseType = Context.getBaseElementType(Field->getType());
14517     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14518       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14519         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14520       Diag(Field->getLocation(), diag::note_declared_at);
14521       Invalid = true;
14522       continue;
14523     }
14524 
14525     // Suppress assigning zero-width bitfields.
14526     if (Field->isZeroLengthBitField(Context))
14527       continue;
14528 
14529     QualType FieldType = Field->getType().getNonReferenceType();
14530     if (FieldType->isIncompleteArrayType()) {
14531       assert(ClassDecl->hasFlexibleArrayMember() &&
14532              "Incomplete array type is not valid");
14533       continue;
14534     }
14535 
14536     // Build references to the field in the object we're copying from and to.
14537     CXXScopeSpec SS; // Intentionally empty
14538     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14539                               LookupMemberName);
14540     MemberLookup.addDecl(Field);
14541     MemberLookup.resolveKind();
14542 
14543     MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14544 
14545     MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14546 
14547     // Build the copy of this field.
14548     StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14549                                             To, From,
14550                                             /*CopyingBaseSubobject=*/false,
14551                                             /*Copying=*/true);
14552     if (Copy.isInvalid()) {
14553       CopyAssignOperator->setInvalidDecl();
14554       return;
14555     }
14556 
14557     // Success! Record the copy.
14558     Statements.push_back(Copy.getAs<Stmt>());
14559   }
14560 
14561   if (!Invalid) {
14562     // Add a "return *this;"
14563     ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14564 
14565     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14566     if (Return.isInvalid())
14567       Invalid = true;
14568     else
14569       Statements.push_back(Return.getAs<Stmt>());
14570   }
14571 
14572   if (Invalid) {
14573     CopyAssignOperator->setInvalidDecl();
14574     return;
14575   }
14576 
14577   StmtResult Body;
14578   {
14579     CompoundScopeRAII CompoundScope(*this);
14580     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14581                              /*isStmtExpr=*/false);
14582     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14583   }
14584   CopyAssignOperator->setBody(Body.getAs<Stmt>());
14585   CopyAssignOperator->markUsed(Context);
14586 
14587   if (ASTMutationListener *L = getASTMutationListener()) {
14588     L->CompletedImplicitDefinition(CopyAssignOperator);
14589   }
14590 }
14591 
14592 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14593   assert(ClassDecl->needsImplicitMoveAssignment());
14594 
14595   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14596   if (DSM.isAlreadyBeingDeclared())
14597     return nullptr;
14598 
14599   // Note: The following rules are largely analoguous to the move
14600   // constructor rules.
14601 
14602   QualType ArgType = Context.getTypeDeclType(ClassDecl);
14603   LangAS AS = getDefaultCXXMethodAddrSpace();
14604   if (AS != LangAS::Default)
14605     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14606   QualType RetType = Context.getLValueReferenceType(ArgType);
14607   ArgType = Context.getRValueReferenceType(ArgType);
14608 
14609   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14610                                                      CXXMoveAssignment,
14611                                                      false);
14612 
14613   //   An implicitly-declared move assignment operator is an inline public
14614   //   member of its class.
14615   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14616   SourceLocation ClassLoc = ClassDecl->getLocation();
14617   DeclarationNameInfo NameInfo(Name, ClassLoc);
14618   CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14619       Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14620       /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14621       getCurFPFeatures().isFPConstrained(),
14622       /*isInline=*/true,
14623       Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14624       SourceLocation());
14625   MoveAssignment->setAccess(AS_public);
14626   MoveAssignment->setDefaulted();
14627   MoveAssignment->setImplicit();
14628 
14629   if (getLangOpts().CUDA) {
14630     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14631                                             MoveAssignment,
14632                                             /* ConstRHS */ false,
14633                                             /* Diagnose */ false);
14634   }
14635 
14636   setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14637 
14638   // Add the parameter to the operator.
14639   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14640                                                ClassLoc, ClassLoc,
14641                                                /*Id=*/nullptr, ArgType,
14642                                                /*TInfo=*/nullptr, SC_None,
14643                                                nullptr);
14644   MoveAssignment->setParams(FromParam);
14645 
14646   MoveAssignment->setTrivial(
14647     ClassDecl->needsOverloadResolutionForMoveAssignment()
14648       ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14649       : ClassDecl->hasTrivialMoveAssignment());
14650 
14651   // Note that we have added this copy-assignment operator.
14652   ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14653 
14654   Scope *S = getScopeForContext(ClassDecl);
14655   CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14656 
14657   if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14658     ClassDecl->setImplicitMoveAssignmentIsDeleted();
14659     SetDeclDeleted(MoveAssignment, ClassLoc);
14660   }
14661 
14662   if (S)
14663     PushOnScopeChains(MoveAssignment, S, false);
14664   ClassDecl->addDecl(MoveAssignment);
14665 
14666   return MoveAssignment;
14667 }
14668 
14669 /// Check if we're implicitly defining a move assignment operator for a class
14670 /// with virtual bases. Such a move assignment might move-assign the virtual
14671 /// base multiple times.
14672 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14673                                                SourceLocation CurrentLocation) {
14674   assert(!Class->isDependentContext() && "should not define dependent move");
14675 
14676   // Only a virtual base could get implicitly move-assigned multiple times.
14677   // Only a non-trivial move assignment can observe this. We only want to
14678   // diagnose if we implicitly define an assignment operator that assigns
14679   // two base classes, both of which move-assign the same virtual base.
14680   if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14681       Class->getNumBases() < 2)
14682     return;
14683 
14684   llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14685   typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14686   VBaseMap VBases;
14687 
14688   for (auto &BI : Class->bases()) {
14689     Worklist.push_back(&BI);
14690     while (!Worklist.empty()) {
14691       CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14692       CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14693 
14694       // If the base has no non-trivial move assignment operators,
14695       // we don't care about moves from it.
14696       if (!Base->hasNonTrivialMoveAssignment())
14697         continue;
14698 
14699       // If there's nothing virtual here, skip it.
14700       if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14701         continue;
14702 
14703       // If we're not actually going to call a move assignment for this base,
14704       // or the selected move assignment is trivial, skip it.
14705       Sema::SpecialMemberOverloadResult SMOR =
14706         S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14707                               /*ConstArg*/false, /*VolatileArg*/false,
14708                               /*RValueThis*/true, /*ConstThis*/false,
14709                               /*VolatileThis*/false);
14710       if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14711           !SMOR.getMethod()->isMoveAssignmentOperator())
14712         continue;
14713 
14714       if (BaseSpec->isVirtual()) {
14715         // We're going to move-assign this virtual base, and its move
14716         // assignment operator is not trivial. If this can happen for
14717         // multiple distinct direct bases of Class, diagnose it. (If it
14718         // only happens in one base, we'll diagnose it when synthesizing
14719         // that base class's move assignment operator.)
14720         CXXBaseSpecifier *&Existing =
14721             VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14722                 .first->second;
14723         if (Existing && Existing != &BI) {
14724           S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14725             << Class << Base;
14726           S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14727               << (Base->getCanonicalDecl() ==
14728                   Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14729               << Base << Existing->getType() << Existing->getSourceRange();
14730           S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14731               << (Base->getCanonicalDecl() ==
14732                   BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14733               << Base << BI.getType() << BaseSpec->getSourceRange();
14734 
14735           // Only diagnose each vbase once.
14736           Existing = nullptr;
14737         }
14738       } else {
14739         // Only walk over bases that have defaulted move assignment operators.
14740         // We assume that any user-provided move assignment operator handles
14741         // the multiple-moves-of-vbase case itself somehow.
14742         if (!SMOR.getMethod()->isDefaulted())
14743           continue;
14744 
14745         // We're going to move the base classes of Base. Add them to the list.
14746         for (auto &BI : Base->bases())
14747           Worklist.push_back(&BI);
14748       }
14749     }
14750   }
14751 }
14752 
14753 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14754                                         CXXMethodDecl *MoveAssignOperator) {
14755   assert((MoveAssignOperator->isDefaulted() &&
14756           MoveAssignOperator->isOverloadedOperator() &&
14757           MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14758           !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14759           !MoveAssignOperator->isDeleted()) &&
14760          "DefineImplicitMoveAssignment called for wrong function");
14761   if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14762     return;
14763 
14764   CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14765   if (ClassDecl->isInvalidDecl()) {
14766     MoveAssignOperator->setInvalidDecl();
14767     return;
14768   }
14769 
14770   // C++0x [class.copy]p28:
14771   //   The implicitly-defined or move assignment operator for a non-union class
14772   //   X performs memberwise move assignment of its subobjects. The direct base
14773   //   classes of X are assigned first, in the order of their declaration in the
14774   //   base-specifier-list, and then the immediate non-static data members of X
14775   //   are assigned, in the order in which they were declared in the class
14776   //   definition.
14777 
14778   // Issue a warning if our implicit move assignment operator will move
14779   // from a virtual base more than once.
14780   checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14781 
14782   SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14783 
14784   // The exception specification is needed because we are defining the
14785   // function.
14786   ResolveExceptionSpec(CurrentLocation,
14787                        MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14788 
14789   // Add a context note for diagnostics produced after this point.
14790   Scope.addContextNote(CurrentLocation);
14791 
14792   // The statements that form the synthesized function body.
14793   SmallVector<Stmt*, 8> Statements;
14794 
14795   // The parameter for the "other" object, which we are move from.
14796   ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14797   QualType OtherRefType =
14798       Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14799 
14800   // Our location for everything implicitly-generated.
14801   SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14802                            ? MoveAssignOperator->getEndLoc()
14803                            : MoveAssignOperator->getLocation();
14804 
14805   // Builds a reference to the "other" object.
14806   RefBuilder OtherRef(Other, OtherRefType);
14807   // Cast to rvalue.
14808   MoveCastBuilder MoveOther(OtherRef);
14809 
14810   // Builds the "this" pointer.
14811   ThisBuilder This;
14812 
14813   // Assign base classes.
14814   bool Invalid = false;
14815   for (auto &Base : ClassDecl->bases()) {
14816     // C++11 [class.copy]p28:
14817     //   It is unspecified whether subobjects representing virtual base classes
14818     //   are assigned more than once by the implicitly-defined copy assignment
14819     //   operator.
14820     // FIXME: Do not assign to a vbase that will be assigned by some other base
14821     // class. For a move-assignment, this can result in the vbase being moved
14822     // multiple times.
14823 
14824     // Form the assignment:
14825     //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14826     QualType BaseType = Base.getType().getUnqualifiedType();
14827     if (!BaseType->isRecordType()) {
14828       Invalid = true;
14829       continue;
14830     }
14831 
14832     CXXCastPath BasePath;
14833     BasePath.push_back(&Base);
14834 
14835     // Construct the "from" expression, which is an implicit cast to the
14836     // appropriately-qualified base type.
14837     CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14838 
14839     // Dereference "this".
14840     DerefBuilder DerefThis(This);
14841 
14842     // Implicitly cast "this" to the appropriately-qualified base type.
14843     CastBuilder To(DerefThis,
14844                    Context.getQualifiedType(
14845                        BaseType, MoveAssignOperator->getMethodQualifiers()),
14846                    VK_LValue, BasePath);
14847 
14848     // Build the move.
14849     StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14850                                             To, From,
14851                                             /*CopyingBaseSubobject=*/true,
14852                                             /*Copying=*/false);
14853     if (Move.isInvalid()) {
14854       MoveAssignOperator->setInvalidDecl();
14855       return;
14856     }
14857 
14858     // Success! Record the move.
14859     Statements.push_back(Move.getAs<Expr>());
14860   }
14861 
14862   // Assign non-static members.
14863   for (auto *Field : ClassDecl->fields()) {
14864     // FIXME: We should form some kind of AST representation for the implied
14865     // memcpy in a union copy operation.
14866     if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14867       continue;
14868 
14869     if (Field->isInvalidDecl()) {
14870       Invalid = true;
14871       continue;
14872     }
14873 
14874     // Check for members of reference type; we can't move those.
14875     if (Field->getType()->isReferenceType()) {
14876       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14877         << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14878       Diag(Field->getLocation(), diag::note_declared_at);
14879       Invalid = true;
14880       continue;
14881     }
14882 
14883     // Check for members of const-qualified, non-class type.
14884     QualType BaseType = Context.getBaseElementType(Field->getType());
14885     if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14886       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14887         << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14888       Diag(Field->getLocation(), diag::note_declared_at);
14889       Invalid = true;
14890       continue;
14891     }
14892 
14893     // Suppress assigning zero-width bitfields.
14894     if (Field->isZeroLengthBitField(Context))
14895       continue;
14896 
14897     QualType FieldType = Field->getType().getNonReferenceType();
14898     if (FieldType->isIncompleteArrayType()) {
14899       assert(ClassDecl->hasFlexibleArrayMember() &&
14900              "Incomplete array type is not valid");
14901       continue;
14902     }
14903 
14904     // Build references to the field in the object we're copying from and to.
14905     LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14906                               LookupMemberName);
14907     MemberLookup.addDecl(Field);
14908     MemberLookup.resolveKind();
14909     MemberBuilder From(MoveOther, OtherRefType,
14910                        /*IsArrow=*/false, MemberLookup);
14911     MemberBuilder To(This, getCurrentThisType(),
14912                      /*IsArrow=*/true, MemberLookup);
14913 
14914     assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14915         "Member reference with rvalue base must be rvalue except for reference "
14916         "members, which aren't allowed for move assignment.");
14917 
14918     // Build the move of this field.
14919     StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14920                                             To, From,
14921                                             /*CopyingBaseSubobject=*/false,
14922                                             /*Copying=*/false);
14923     if (Move.isInvalid()) {
14924       MoveAssignOperator->setInvalidDecl();
14925       return;
14926     }
14927 
14928     // Success! Record the copy.
14929     Statements.push_back(Move.getAs<Stmt>());
14930   }
14931 
14932   if (!Invalid) {
14933     // Add a "return *this;"
14934     ExprResult ThisObj =
14935         CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14936 
14937     StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14938     if (Return.isInvalid())
14939       Invalid = true;
14940     else
14941       Statements.push_back(Return.getAs<Stmt>());
14942   }
14943 
14944   if (Invalid) {
14945     MoveAssignOperator->setInvalidDecl();
14946     return;
14947   }
14948 
14949   StmtResult Body;
14950   {
14951     CompoundScopeRAII CompoundScope(*this);
14952     Body = ActOnCompoundStmt(Loc, Loc, Statements,
14953                              /*isStmtExpr=*/false);
14954     assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14955   }
14956   MoveAssignOperator->setBody(Body.getAs<Stmt>());
14957   MoveAssignOperator->markUsed(Context);
14958 
14959   if (ASTMutationListener *L = getASTMutationListener()) {
14960     L->CompletedImplicitDefinition(MoveAssignOperator);
14961   }
14962 }
14963 
14964 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14965                                                     CXXRecordDecl *ClassDecl) {
14966   // C++ [class.copy]p4:
14967   //   If the class definition does not explicitly declare a copy
14968   //   constructor, one is declared implicitly.
14969   assert(ClassDecl->needsImplicitCopyConstructor());
14970 
14971   DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14972   if (DSM.isAlreadyBeingDeclared())
14973     return nullptr;
14974 
14975   QualType ClassType = Context.getTypeDeclType(ClassDecl);
14976   QualType ArgType = ClassType;
14977   bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14978   if (Const)
14979     ArgType = ArgType.withConst();
14980 
14981   LangAS AS = getDefaultCXXMethodAddrSpace();
14982   if (AS != LangAS::Default)
14983     ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14984 
14985   ArgType = Context.getLValueReferenceType(ArgType);
14986 
14987   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14988                                                      CXXCopyConstructor,
14989                                                      Const);
14990 
14991   DeclarationName Name
14992     = Context.DeclarationNames.getCXXConstructorName(
14993                                            Context.getCanonicalType(ClassType));
14994   SourceLocation ClassLoc = ClassDecl->getLocation();
14995   DeclarationNameInfo NameInfo(Name, ClassLoc);
14996 
14997   //   An implicitly-declared copy constructor is an inline public
14998   //   member of its class.
14999   CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15000       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15001       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15002       /*isInline=*/true,
15003       /*isImplicitlyDeclared=*/true,
15004       Constexpr ? ConstexprSpecKind::Constexpr
15005                 : ConstexprSpecKind::Unspecified);
15006   CopyConstructor->setAccess(AS_public);
15007   CopyConstructor->setDefaulted();
15008 
15009   if (getLangOpts().CUDA) {
15010     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
15011                                             CopyConstructor,
15012                                             /* ConstRHS */ Const,
15013                                             /* Diagnose */ false);
15014   }
15015 
15016   setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
15017 
15018   // During template instantiation of special member functions we need a
15019   // reliable TypeSourceInfo for the parameter types in order to allow functions
15020   // to be substituted.
15021   TypeSourceInfo *TSI = nullptr;
15022   if (inTemplateInstantiation() && ClassDecl->isLambda())
15023     TSI = Context.getTrivialTypeSourceInfo(ArgType);
15024 
15025   // Add the parameter to the constructor.
15026   ParmVarDecl *FromParam =
15027       ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
15028                           /*IdentifierInfo=*/nullptr, ArgType,
15029                           /*TInfo=*/TSI, SC_None, nullptr);
15030   CopyConstructor->setParams(FromParam);
15031 
15032   CopyConstructor->setTrivial(
15033       ClassDecl->needsOverloadResolutionForCopyConstructor()
15034           ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
15035           : ClassDecl->hasTrivialCopyConstructor());
15036 
15037   CopyConstructor->setTrivialForCall(
15038       ClassDecl->hasAttr<TrivialABIAttr>() ||
15039       (ClassDecl->needsOverloadResolutionForCopyConstructor()
15040            ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
15041              TAH_ConsiderTrivialABI)
15042            : ClassDecl->hasTrivialCopyConstructorForCall()));
15043 
15044   // Note that we have declared this constructor.
15045   ++getASTContext().NumImplicitCopyConstructorsDeclared;
15046 
15047   Scope *S = getScopeForContext(ClassDecl);
15048   CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
15049 
15050   if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
15051     ClassDecl->setImplicitCopyConstructorIsDeleted();
15052     SetDeclDeleted(CopyConstructor, ClassLoc);
15053   }
15054 
15055   if (S)
15056     PushOnScopeChains(CopyConstructor, S, false);
15057   ClassDecl->addDecl(CopyConstructor);
15058 
15059   return CopyConstructor;
15060 }
15061 
15062 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
15063                                          CXXConstructorDecl *CopyConstructor) {
15064   assert((CopyConstructor->isDefaulted() &&
15065           CopyConstructor->isCopyConstructor() &&
15066           !CopyConstructor->doesThisDeclarationHaveABody() &&
15067           !CopyConstructor->isDeleted()) &&
15068          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
15069   if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
15070     return;
15071 
15072   CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
15073   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
15074 
15075   SynthesizedFunctionScope Scope(*this, CopyConstructor);
15076 
15077   // The exception specification is needed because we are defining the
15078   // function.
15079   ResolveExceptionSpec(CurrentLocation,
15080                        CopyConstructor->getType()->castAs<FunctionProtoType>());
15081   MarkVTableUsed(CurrentLocation, ClassDecl);
15082 
15083   // Add a context note for diagnostics produced after this point.
15084   Scope.addContextNote(CurrentLocation);
15085 
15086   // C++11 [class.copy]p7:
15087   //   The [definition of an implicitly declared copy constructor] is
15088   //   deprecated if the class has a user-declared copy assignment operator
15089   //   or a user-declared destructor.
15090   if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
15091     diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
15092 
15093   if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
15094     CopyConstructor->setInvalidDecl();
15095   }  else {
15096     SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15097                              ? CopyConstructor->getEndLoc()
15098                              : CopyConstructor->getLocation();
15099     Sema::CompoundScopeRAII CompoundScope(*this);
15100     CopyConstructor->setBody(
15101         ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
15102     CopyConstructor->markUsed(Context);
15103   }
15104 
15105   if (ASTMutationListener *L = getASTMutationListener()) {
15106     L->CompletedImplicitDefinition(CopyConstructor);
15107   }
15108 }
15109 
15110 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15111                                                     CXXRecordDecl *ClassDecl) {
15112   assert(ClassDecl->needsImplicitMoveConstructor());
15113 
15114   DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15115   if (DSM.isAlreadyBeingDeclared())
15116     return nullptr;
15117 
15118   QualType ClassType = Context.getTypeDeclType(ClassDecl);
15119 
15120   QualType ArgType = ClassType;
15121   LangAS AS = getDefaultCXXMethodAddrSpace();
15122   if (AS != LangAS::Default)
15123     ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15124   ArgType = Context.getRValueReferenceType(ArgType);
15125 
15126   bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15127                                                      CXXMoveConstructor,
15128                                                      false);
15129 
15130   DeclarationName Name
15131     = Context.DeclarationNames.getCXXConstructorName(
15132                                            Context.getCanonicalType(ClassType));
15133   SourceLocation ClassLoc = ClassDecl->getLocation();
15134   DeclarationNameInfo NameInfo(Name, ClassLoc);
15135 
15136   // C++11 [class.copy]p11:
15137   //   An implicitly-declared copy/move constructor is an inline public
15138   //   member of its class.
15139   CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15140       Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15141       ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15142       /*isInline=*/true,
15143       /*isImplicitlyDeclared=*/true,
15144       Constexpr ? ConstexprSpecKind::Constexpr
15145                 : ConstexprSpecKind::Unspecified);
15146   MoveConstructor->setAccess(AS_public);
15147   MoveConstructor->setDefaulted();
15148 
15149   if (getLangOpts().CUDA) {
15150     inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15151                                             MoveConstructor,
15152                                             /* ConstRHS */ false,
15153                                             /* Diagnose */ false);
15154   }
15155 
15156   setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15157 
15158   // Add the parameter to the constructor.
15159   ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15160                                                ClassLoc, ClassLoc,
15161                                                /*IdentifierInfo=*/nullptr,
15162                                                ArgType, /*TInfo=*/nullptr,
15163                                                SC_None, nullptr);
15164   MoveConstructor->setParams(FromParam);
15165 
15166   MoveConstructor->setTrivial(
15167       ClassDecl->needsOverloadResolutionForMoveConstructor()
15168           ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15169           : ClassDecl->hasTrivialMoveConstructor());
15170 
15171   MoveConstructor->setTrivialForCall(
15172       ClassDecl->hasAttr<TrivialABIAttr>() ||
15173       (ClassDecl->needsOverloadResolutionForMoveConstructor()
15174            ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15175                                     TAH_ConsiderTrivialABI)
15176            : ClassDecl->hasTrivialMoveConstructorForCall()));
15177 
15178   // Note that we have declared this constructor.
15179   ++getASTContext().NumImplicitMoveConstructorsDeclared;
15180 
15181   Scope *S = getScopeForContext(ClassDecl);
15182   CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15183 
15184   if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15185     ClassDecl->setImplicitMoveConstructorIsDeleted();
15186     SetDeclDeleted(MoveConstructor, ClassLoc);
15187   }
15188 
15189   if (S)
15190     PushOnScopeChains(MoveConstructor, S, false);
15191   ClassDecl->addDecl(MoveConstructor);
15192 
15193   return MoveConstructor;
15194 }
15195 
15196 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15197                                          CXXConstructorDecl *MoveConstructor) {
15198   assert((MoveConstructor->isDefaulted() &&
15199           MoveConstructor->isMoveConstructor() &&
15200           !MoveConstructor->doesThisDeclarationHaveABody() &&
15201           !MoveConstructor->isDeleted()) &&
15202          "DefineImplicitMoveConstructor - call it for implicit move ctor");
15203   if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15204     return;
15205 
15206   CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15207   assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
15208 
15209   SynthesizedFunctionScope Scope(*this, MoveConstructor);
15210 
15211   // The exception specification is needed because we are defining the
15212   // function.
15213   ResolveExceptionSpec(CurrentLocation,
15214                        MoveConstructor->getType()->castAs<FunctionProtoType>());
15215   MarkVTableUsed(CurrentLocation, ClassDecl);
15216 
15217   // Add a context note for diagnostics produced after this point.
15218   Scope.addContextNote(CurrentLocation);
15219 
15220   if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15221     MoveConstructor->setInvalidDecl();
15222   } else {
15223     SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15224                              ? MoveConstructor->getEndLoc()
15225                              : MoveConstructor->getLocation();
15226     Sema::CompoundScopeRAII CompoundScope(*this);
15227     MoveConstructor->setBody(ActOnCompoundStmt(
15228         Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
15229     MoveConstructor->markUsed(Context);
15230   }
15231 
15232   if (ASTMutationListener *L = getASTMutationListener()) {
15233     L->CompletedImplicitDefinition(MoveConstructor);
15234   }
15235 }
15236 
15237 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15238   return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15239 }
15240 
15241 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15242                             SourceLocation CurrentLocation,
15243                             CXXConversionDecl *Conv) {
15244   SynthesizedFunctionScope Scope(*this, Conv);
15245   assert(!Conv->getReturnType()->isUndeducedType());
15246 
15247   QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15248   CallingConv CC =
15249       ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15250 
15251   CXXRecordDecl *Lambda = Conv->getParent();
15252   FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15253   FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
15254 
15255   if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15256     CallOp = InstantiateFunctionDeclaration(
15257         CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15258     if (!CallOp)
15259       return;
15260 
15261     Invoker = InstantiateFunctionDeclaration(
15262         Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15263     if (!Invoker)
15264       return;
15265   }
15266 
15267   if (CallOp->isInvalidDecl())
15268     return;
15269 
15270   // Mark the call operator referenced (and add to pending instantiations
15271   // if necessary).
15272   // For both the conversion and static-invoker template specializations
15273   // we construct their body's in this function, so no need to add them
15274   // to the PendingInstantiations.
15275   MarkFunctionReferenced(CurrentLocation, CallOp);
15276 
15277   // Fill in the __invoke function with a dummy implementation. IR generation
15278   // will fill in the actual details. Update its type in case it contained
15279   // an 'auto'.
15280   Invoker->markUsed(Context);
15281   Invoker->setReferenced();
15282   Invoker->setType(Conv->getReturnType()->getPointeeType());
15283   Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15284 
15285   // Construct the body of the conversion function { return __invoke; }.
15286   Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
15287                                        VK_LValue, Conv->getLocation());
15288   assert(FunctionRef && "Can't refer to __invoke function?");
15289   Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15290   Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
15291                                      Conv->getLocation()));
15292   Conv->markUsed(Context);
15293   Conv->setReferenced();
15294 
15295   if (ASTMutationListener *L = getASTMutationListener()) {
15296     L->CompletedImplicitDefinition(Conv);
15297     L->CompletedImplicitDefinition(Invoker);
15298   }
15299 }
15300 
15301 
15302 
15303 void Sema::DefineImplicitLambdaToBlockPointerConversion(
15304        SourceLocation CurrentLocation,
15305        CXXConversionDecl *Conv)
15306 {
15307   assert(!Conv->getParent()->isGenericLambda());
15308 
15309   SynthesizedFunctionScope Scope(*this, Conv);
15310 
15311   // Copy-initialize the lambda object as needed to capture it.
15312   Expr *This = ActOnCXXThis(CurrentLocation).get();
15313   Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15314 
15315   ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15316                                                         Conv->getLocation(),
15317                                                         Conv, DerefThis);
15318 
15319   // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15320   // behavior.  Note that only the general conversion function does this
15321   // (since it's unusable otherwise); in the case where we inline the
15322   // block literal, it has block literal lifetime semantics.
15323   if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15324     BuildBlock = ImplicitCastExpr::Create(
15325         Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15326         BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15327 
15328   if (BuildBlock.isInvalid()) {
15329     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15330     Conv->setInvalidDecl();
15331     return;
15332   }
15333 
15334   // Create the return statement that returns the block from the conversion
15335   // function.
15336   StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15337   if (Return.isInvalid()) {
15338     Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15339     Conv->setInvalidDecl();
15340     return;
15341   }
15342 
15343   // Set the body of the conversion function.
15344   Stmt *ReturnS = Return.get();
15345   Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
15346                                      Conv->getLocation()));
15347   Conv->markUsed(Context);
15348 
15349   // We're done; notify the mutation listener, if any.
15350   if (ASTMutationListener *L = getASTMutationListener()) {
15351     L->CompletedImplicitDefinition(Conv);
15352   }
15353 }
15354 
15355 /// Determine whether the given list arguments contains exactly one
15356 /// "real" (non-default) argument.
15357 static bool hasOneRealArgument(MultiExprArg Args) {
15358   switch (Args.size()) {
15359   case 0:
15360     return false;
15361 
15362   default:
15363     if (!Args[1]->isDefaultArgument())
15364       return false;
15365 
15366     LLVM_FALLTHROUGH;
15367   case 1:
15368     return !Args[0]->isDefaultArgument();
15369   }
15370 
15371   return false;
15372 }
15373 
15374 ExprResult
15375 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15376                             NamedDecl *FoundDecl,
15377                             CXXConstructorDecl *Constructor,
15378                             MultiExprArg ExprArgs,
15379                             bool HadMultipleCandidates,
15380                             bool IsListInitialization,
15381                             bool IsStdInitListInitialization,
15382                             bool RequiresZeroInit,
15383                             unsigned ConstructKind,
15384                             SourceRange ParenRange) {
15385   bool Elidable = false;
15386 
15387   // C++0x [class.copy]p34:
15388   //   When certain criteria are met, an implementation is allowed to
15389   //   omit the copy/move construction of a class object, even if the
15390   //   copy/move constructor and/or destructor for the object have
15391   //   side effects. [...]
15392   //     - when a temporary class object that has not been bound to a
15393   //       reference (12.2) would be copied/moved to a class object
15394   //       with the same cv-unqualified type, the copy/move operation
15395   //       can be omitted by constructing the temporary object
15396   //       directly into the target of the omitted copy/move
15397   if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15398       // FIXME: Converting constructors should also be accepted.
15399       // But to fix this, the logic that digs down into a CXXConstructExpr
15400       // to find the source object needs to handle it.
15401       // Right now it assumes the source object is passed directly as the
15402       // first argument.
15403       Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15404     Expr *SubExpr = ExprArgs[0];
15405     // FIXME: Per above, this is also incorrect if we want to accept
15406     //        converting constructors, as isTemporaryObject will
15407     //        reject temporaries with different type from the
15408     //        CXXRecord itself.
15409     Elidable = SubExpr->isTemporaryObject(
15410         Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15411   }
15412 
15413   return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15414                                FoundDecl, Constructor,
15415                                Elidable, ExprArgs, HadMultipleCandidates,
15416                                IsListInitialization,
15417                                IsStdInitListInitialization, RequiresZeroInit,
15418                                ConstructKind, ParenRange);
15419 }
15420 
15421 ExprResult
15422 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15423                             NamedDecl *FoundDecl,
15424                             CXXConstructorDecl *Constructor,
15425                             bool Elidable,
15426                             MultiExprArg ExprArgs,
15427                             bool HadMultipleCandidates,
15428                             bool IsListInitialization,
15429                             bool IsStdInitListInitialization,
15430                             bool RequiresZeroInit,
15431                             unsigned ConstructKind,
15432                             SourceRange ParenRange) {
15433   if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15434     Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15435     if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15436       return ExprError();
15437   }
15438 
15439   return BuildCXXConstructExpr(
15440       ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15441       HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15442       RequiresZeroInit, ConstructKind, ParenRange);
15443 }
15444 
15445 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
15446 /// including handling of its default argument expressions.
15447 ExprResult
15448 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15449                             CXXConstructorDecl *Constructor,
15450                             bool Elidable,
15451                             MultiExprArg ExprArgs,
15452                             bool HadMultipleCandidates,
15453                             bool IsListInitialization,
15454                             bool IsStdInitListInitialization,
15455                             bool RequiresZeroInit,
15456                             unsigned ConstructKind,
15457                             SourceRange ParenRange) {
15458   assert(declaresSameEntity(
15459              Constructor->getParent(),
15460              DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
15461          "given constructor for wrong type");
15462   MarkFunctionReferenced(ConstructLoc, Constructor);
15463   if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15464     return ExprError();
15465   if (getLangOpts().SYCLIsDevice &&
15466       !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15467     return ExprError();
15468 
15469   return CheckForImmediateInvocation(
15470       CXXConstructExpr::Create(
15471           Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15472           HadMultipleCandidates, IsListInitialization,
15473           IsStdInitListInitialization, RequiresZeroInit,
15474           static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15475           ParenRange),
15476       Constructor);
15477 }
15478 
15479 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15480   assert(Field->hasInClassInitializer());
15481 
15482   // If we already have the in-class initializer nothing needs to be done.
15483   if (Field->getInClassInitializer())
15484     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15485 
15486   // If we might have already tried and failed to instantiate, don't try again.
15487   if (Field->isInvalidDecl())
15488     return ExprError();
15489 
15490   // Maybe we haven't instantiated the in-class initializer. Go check the
15491   // pattern FieldDecl to see if it has one.
15492   CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15493 
15494   if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15495     CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15496     DeclContext::lookup_result Lookup =
15497         ClassPattern->lookup(Field->getDeclName());
15498 
15499     FieldDecl *Pattern = nullptr;
15500     for (auto L : Lookup) {
15501       if (isa<FieldDecl>(L)) {
15502         Pattern = cast<FieldDecl>(L);
15503         break;
15504       }
15505     }
15506     assert(Pattern && "We must have set the Pattern!");
15507 
15508     if (!Pattern->hasInClassInitializer() ||
15509         InstantiateInClassInitializer(Loc, Field, Pattern,
15510                                       getTemplateInstantiationArgs(Field))) {
15511       // Don't diagnose this again.
15512       Field->setInvalidDecl();
15513       return ExprError();
15514     }
15515     return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15516   }
15517 
15518   // DR1351:
15519   //   If the brace-or-equal-initializer of a non-static data member
15520   //   invokes a defaulted default constructor of its class or of an
15521   //   enclosing class in a potentially evaluated subexpression, the
15522   //   program is ill-formed.
15523   //
15524   // This resolution is unworkable: the exception specification of the
15525   // default constructor can be needed in an unevaluated context, in
15526   // particular, in the operand of a noexcept-expression, and we can be
15527   // unable to compute an exception specification for an enclosed class.
15528   //
15529   // Any attempt to resolve the exception specification of a defaulted default
15530   // constructor before the initializer is lexically complete will ultimately
15531   // come here at which point we can diagnose it.
15532   RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15533   Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15534       << OutermostClass << Field;
15535   Diag(Field->getEndLoc(),
15536        diag::note_default_member_initializer_not_yet_parsed);
15537   // Recover by marking the field invalid, unless we're in a SFINAE context.
15538   if (!isSFINAEContext())
15539     Field->setInvalidDecl();
15540   return ExprError();
15541 }
15542 
15543 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15544   if (VD->isInvalidDecl()) return;
15545   // If initializing the variable failed, don't also diagnose problems with
15546   // the destructor, they're likely related.
15547   if (VD->getInit() && VD->getInit()->containsErrors())
15548     return;
15549 
15550   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15551   if (ClassDecl->isInvalidDecl()) return;
15552   if (ClassDecl->hasIrrelevantDestructor()) return;
15553   if (ClassDecl->isDependentContext()) return;
15554 
15555   if (VD->isNoDestroy(getASTContext()))
15556     return;
15557 
15558   CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15559 
15560   // If this is an array, we'll require the destructor during initialization, so
15561   // we can skip over this. We still want to emit exit-time destructor warnings
15562   // though.
15563   if (!VD->getType()->isArrayType()) {
15564     MarkFunctionReferenced(VD->getLocation(), Destructor);
15565     CheckDestructorAccess(VD->getLocation(), Destructor,
15566                           PDiag(diag::err_access_dtor_var)
15567                               << VD->getDeclName() << VD->getType());
15568     DiagnoseUseOfDecl(Destructor, VD->getLocation());
15569   }
15570 
15571   if (Destructor->isTrivial()) return;
15572 
15573   // If the destructor is constexpr, check whether the variable has constant
15574   // destruction now.
15575   if (Destructor->isConstexpr()) {
15576     bool HasConstantInit = false;
15577     if (VD->getInit() && !VD->getInit()->isValueDependent())
15578       HasConstantInit = VD->evaluateValue();
15579     SmallVector<PartialDiagnosticAt, 8> Notes;
15580     if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15581         HasConstantInit) {
15582       Diag(VD->getLocation(),
15583            diag::err_constexpr_var_requires_const_destruction) << VD;
15584       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15585         Diag(Notes[I].first, Notes[I].second);
15586     }
15587   }
15588 
15589   if (!VD->hasGlobalStorage()) return;
15590 
15591   // Emit warning for non-trivial dtor in global scope (a real global,
15592   // class-static, function-static).
15593   Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15594 
15595   // TODO: this should be re-enabled for static locals by !CXAAtExit
15596   if (!VD->isStaticLocal())
15597     Diag(VD->getLocation(), diag::warn_global_destructor);
15598 }
15599 
15600 /// Given a constructor and the set of arguments provided for the
15601 /// constructor, convert the arguments and add any required default arguments
15602 /// to form a proper call to this constructor.
15603 ///
15604 /// \returns true if an error occurred, false otherwise.
15605 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15606                                    QualType DeclInitType, MultiExprArg ArgsPtr,
15607                                    SourceLocation Loc,
15608                                    SmallVectorImpl<Expr *> &ConvertedArgs,
15609                                    bool AllowExplicit,
15610                                    bool IsListInitialization) {
15611   // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15612   unsigned NumArgs = ArgsPtr.size();
15613   Expr **Args = ArgsPtr.data();
15614 
15615   const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15616   unsigned NumParams = Proto->getNumParams();
15617 
15618   // If too few arguments are available, we'll fill in the rest with defaults.
15619   if (NumArgs < NumParams)
15620     ConvertedArgs.reserve(NumParams);
15621   else
15622     ConvertedArgs.reserve(NumArgs);
15623 
15624   VariadicCallType CallType =
15625     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15626   SmallVector<Expr *, 8> AllArgs;
15627   bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15628                                         Proto, 0,
15629                                         llvm::makeArrayRef(Args, NumArgs),
15630                                         AllArgs,
15631                                         CallType, AllowExplicit,
15632                                         IsListInitialization);
15633   ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15634 
15635   DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15636 
15637   CheckConstructorCall(Constructor, DeclInitType,
15638                        llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15639                        Proto, Loc);
15640 
15641   return Invalid;
15642 }
15643 
15644 static inline bool
15645 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15646                                        const FunctionDecl *FnDecl) {
15647   const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15648   if (isa<NamespaceDecl>(DC)) {
15649     return SemaRef.Diag(FnDecl->getLocation(),
15650                         diag::err_operator_new_delete_declared_in_namespace)
15651       << FnDecl->getDeclName();
15652   }
15653 
15654   if (isa<TranslationUnitDecl>(DC) &&
15655       FnDecl->getStorageClass() == SC_Static) {
15656     return SemaRef.Diag(FnDecl->getLocation(),
15657                         diag::err_operator_new_delete_declared_static)
15658       << FnDecl->getDeclName();
15659   }
15660 
15661   return false;
15662 }
15663 
15664 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15665                                              const PointerType *PtrTy) {
15666   auto &Ctx = SemaRef.Context;
15667   Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15668   PtrQuals.removeAddressSpace();
15669   return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15670       PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15671 }
15672 
15673 static inline bool
15674 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15675                             CanQualType ExpectedResultType,
15676                             CanQualType ExpectedFirstParamType,
15677                             unsigned DependentParamTypeDiag,
15678                             unsigned InvalidParamTypeDiag) {
15679   QualType ResultType =
15680       FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15681 
15682   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15683     // The operator is valid on any address space for OpenCL.
15684     // Drop address space from actual and expected result types.
15685     if (const auto *PtrTy = ResultType->getAs<PointerType>())
15686       ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15687 
15688     if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15689       ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15690   }
15691 
15692   // Check that the result type is what we expect.
15693   if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15694     // Reject even if the type is dependent; an operator delete function is
15695     // required to have a non-dependent result type.
15696     return SemaRef.Diag(
15697                FnDecl->getLocation(),
15698                ResultType->isDependentType()
15699                    ? diag::err_operator_new_delete_dependent_result_type
15700                    : diag::err_operator_new_delete_invalid_result_type)
15701            << FnDecl->getDeclName() << ExpectedResultType;
15702   }
15703 
15704   // A function template must have at least 2 parameters.
15705   if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15706     return SemaRef.Diag(FnDecl->getLocation(),
15707                       diag::err_operator_new_delete_template_too_few_parameters)
15708         << FnDecl->getDeclName();
15709 
15710   // The function decl must have at least 1 parameter.
15711   if (FnDecl->getNumParams() == 0)
15712     return SemaRef.Diag(FnDecl->getLocation(),
15713                         diag::err_operator_new_delete_too_few_parameters)
15714       << FnDecl->getDeclName();
15715 
15716   QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15717   if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15718     // The operator is valid on any address space for OpenCL.
15719     // Drop address space from actual and expected first parameter types.
15720     if (const auto *PtrTy =
15721             FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15722       FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15723 
15724     if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15725       ExpectedFirstParamType =
15726           RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15727   }
15728 
15729   // Check that the first parameter type is what we expect.
15730   if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15731       ExpectedFirstParamType) {
15732     // The first parameter type is not allowed to be dependent. As a tentative
15733     // DR resolution, we allow a dependent parameter type if it is the right
15734     // type anyway, to allow destroying operator delete in class templates.
15735     return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15736                                                    ? DependentParamTypeDiag
15737                                                    : InvalidParamTypeDiag)
15738            << FnDecl->getDeclName() << ExpectedFirstParamType;
15739   }
15740 
15741   return false;
15742 }
15743 
15744 static bool
15745 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15746   // C++ [basic.stc.dynamic.allocation]p1:
15747   //   A program is ill-formed if an allocation function is declared in a
15748   //   namespace scope other than global scope or declared static in global
15749   //   scope.
15750   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15751     return true;
15752 
15753   CanQualType SizeTy =
15754     SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15755 
15756   // C++ [basic.stc.dynamic.allocation]p1:
15757   //  The return type shall be void*. The first parameter shall have type
15758   //  std::size_t.
15759   if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15760                                   SizeTy,
15761                                   diag::err_operator_new_dependent_param_type,
15762                                   diag::err_operator_new_param_type))
15763     return true;
15764 
15765   // C++ [basic.stc.dynamic.allocation]p1:
15766   //  The first parameter shall not have an associated default argument.
15767   if (FnDecl->getParamDecl(0)->hasDefaultArg())
15768     return SemaRef.Diag(FnDecl->getLocation(),
15769                         diag::err_operator_new_default_arg)
15770       << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15771 
15772   return false;
15773 }
15774 
15775 static bool
15776 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15777   // C++ [basic.stc.dynamic.deallocation]p1:
15778   //   A program is ill-formed if deallocation functions are declared in a
15779   //   namespace scope other than global scope or declared static in global
15780   //   scope.
15781   if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15782     return true;
15783 
15784   auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15785 
15786   // C++ P0722:
15787   //   Within a class C, the first parameter of a destroying operator delete
15788   //   shall be of type C *. The first parameter of any other deallocation
15789   //   function shall be of type void *.
15790   CanQualType ExpectedFirstParamType =
15791       MD && MD->isDestroyingOperatorDelete()
15792           ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15793                 SemaRef.Context.getRecordType(MD->getParent())))
15794           : SemaRef.Context.VoidPtrTy;
15795 
15796   // C++ [basic.stc.dynamic.deallocation]p2:
15797   //   Each deallocation function shall return void
15798   if (CheckOperatorNewDeleteTypes(
15799           SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15800           diag::err_operator_delete_dependent_param_type,
15801           diag::err_operator_delete_param_type))
15802     return true;
15803 
15804   // C++ P0722:
15805   //   A destroying operator delete shall be a usual deallocation function.
15806   if (MD && !MD->getParent()->isDependentContext() &&
15807       MD->isDestroyingOperatorDelete() &&
15808       !SemaRef.isUsualDeallocationFunction(MD)) {
15809     SemaRef.Diag(MD->getLocation(),
15810                  diag::err_destroying_operator_delete_not_usual);
15811     return true;
15812   }
15813 
15814   return false;
15815 }
15816 
15817 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15818 /// of this overloaded operator is well-formed. If so, returns false;
15819 /// otherwise, emits appropriate diagnostics and returns true.
15820 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15821   assert(FnDecl && FnDecl->isOverloadedOperator() &&
15822          "Expected an overloaded operator declaration");
15823 
15824   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15825 
15826   // C++ [over.oper]p5:
15827   //   The allocation and deallocation functions, operator new,
15828   //   operator new[], operator delete and operator delete[], are
15829   //   described completely in 3.7.3. The attributes and restrictions
15830   //   found in the rest of this subclause do not apply to them unless
15831   //   explicitly stated in 3.7.3.
15832   if (Op == OO_Delete || Op == OO_Array_Delete)
15833     return CheckOperatorDeleteDeclaration(*this, FnDecl);
15834 
15835   if (Op == OO_New || Op == OO_Array_New)
15836     return CheckOperatorNewDeclaration(*this, FnDecl);
15837 
15838   // C++ [over.oper]p6:
15839   //   An operator function shall either be a non-static member
15840   //   function or be a non-member function and have at least one
15841   //   parameter whose type is a class, a reference to a class, an
15842   //   enumeration, or a reference to an enumeration.
15843   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15844     if (MethodDecl->isStatic())
15845       return Diag(FnDecl->getLocation(),
15846                   diag::err_operator_overload_static) << FnDecl->getDeclName();
15847   } else {
15848     bool ClassOrEnumParam = false;
15849     for (auto Param : FnDecl->parameters()) {
15850       QualType ParamType = Param->getType().getNonReferenceType();
15851       if (ParamType->isDependentType() || ParamType->isRecordType() ||
15852           ParamType->isEnumeralType()) {
15853         ClassOrEnumParam = true;
15854         break;
15855       }
15856     }
15857 
15858     if (!ClassOrEnumParam)
15859       return Diag(FnDecl->getLocation(),
15860                   diag::err_operator_overload_needs_class_or_enum)
15861         << FnDecl->getDeclName();
15862   }
15863 
15864   // C++ [over.oper]p8:
15865   //   An operator function cannot have default arguments (8.3.6),
15866   //   except where explicitly stated below.
15867   //
15868   // Only the function-call operator allows default arguments
15869   // (C++ [over.call]p1).
15870   if (Op != OO_Call) {
15871     for (auto Param : FnDecl->parameters()) {
15872       if (Param->hasDefaultArg())
15873         return Diag(Param->getLocation(),
15874                     diag::err_operator_overload_default_arg)
15875           << FnDecl->getDeclName() << Param->getDefaultArgRange();
15876     }
15877   }
15878 
15879   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15880     { false, false, false }
15881 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15882     , { Unary, Binary, MemberOnly }
15883 #include "clang/Basic/OperatorKinds.def"
15884   };
15885 
15886   bool CanBeUnaryOperator = OperatorUses[Op][0];
15887   bool CanBeBinaryOperator = OperatorUses[Op][1];
15888   bool MustBeMemberOperator = OperatorUses[Op][2];
15889 
15890   // C++ [over.oper]p8:
15891   //   [...] Operator functions cannot have more or fewer parameters
15892   //   than the number required for the corresponding operator, as
15893   //   described in the rest of this subclause.
15894   unsigned NumParams = FnDecl->getNumParams()
15895                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15896   if (Op != OO_Call &&
15897       ((NumParams == 1 && !CanBeUnaryOperator) ||
15898        (NumParams == 2 && !CanBeBinaryOperator) ||
15899        (NumParams < 1) || (NumParams > 2))) {
15900     // We have the wrong number of parameters.
15901     unsigned ErrorKind;
15902     if (CanBeUnaryOperator && CanBeBinaryOperator) {
15903       ErrorKind = 2;  // 2 -> unary or binary.
15904     } else if (CanBeUnaryOperator) {
15905       ErrorKind = 0;  // 0 -> unary
15906     } else {
15907       assert(CanBeBinaryOperator &&
15908              "All non-call overloaded operators are unary or binary!");
15909       ErrorKind = 1;  // 1 -> binary
15910     }
15911 
15912     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15913       << FnDecl->getDeclName() << NumParams << ErrorKind;
15914   }
15915 
15916   // Overloaded operators other than operator() cannot be variadic.
15917   if (Op != OO_Call &&
15918       FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15919     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15920       << FnDecl->getDeclName();
15921   }
15922 
15923   // Some operators must be non-static member functions.
15924   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15925     return Diag(FnDecl->getLocation(),
15926                 diag::err_operator_overload_must_be_member)
15927       << FnDecl->getDeclName();
15928   }
15929 
15930   // C++ [over.inc]p1:
15931   //   The user-defined function called operator++ implements the
15932   //   prefix and postfix ++ operator. If this function is a member
15933   //   function with no parameters, or a non-member function with one
15934   //   parameter of class or enumeration type, it defines the prefix
15935   //   increment operator ++ for objects of that type. If the function
15936   //   is a member function with one parameter (which shall be of type
15937   //   int) or a non-member function with two parameters (the second
15938   //   of which shall be of type int), it defines the postfix
15939   //   increment operator ++ for objects of that type.
15940   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15941     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15942     QualType ParamType = LastParam->getType();
15943 
15944     if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15945         !ParamType->isDependentType())
15946       return Diag(LastParam->getLocation(),
15947                   diag::err_operator_overload_post_incdec_must_be_int)
15948         << LastParam->getType() << (Op == OO_MinusMinus);
15949   }
15950 
15951   return false;
15952 }
15953 
15954 static bool
15955 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15956                                           FunctionTemplateDecl *TpDecl) {
15957   TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15958 
15959   // Must have one or two template parameters.
15960   if (TemplateParams->size() == 1) {
15961     NonTypeTemplateParmDecl *PmDecl =
15962         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15963 
15964     // The template parameter must be a char parameter pack.
15965     if (PmDecl && PmDecl->isTemplateParameterPack() &&
15966         SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15967       return false;
15968 
15969     // C++20 [over.literal]p5:
15970     //   A string literal operator template is a literal operator template
15971     //   whose template-parameter-list comprises a single non-type
15972     //   template-parameter of class type.
15973     //
15974     // As a DR resolution, we also allow placeholders for deduced class
15975     // template specializations.
15976     if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
15977         !PmDecl->isTemplateParameterPack() &&
15978         (PmDecl->getType()->isRecordType() ||
15979          PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
15980       return false;
15981   } else if (TemplateParams->size() == 2) {
15982     TemplateTypeParmDecl *PmType =
15983         dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15984     NonTypeTemplateParmDecl *PmArgs =
15985         dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15986 
15987     // The second template parameter must be a parameter pack with the
15988     // first template parameter as its type.
15989     if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15990         PmArgs->isTemplateParameterPack()) {
15991       const TemplateTypeParmType *TArgs =
15992           PmArgs->getType()->getAs<TemplateTypeParmType>();
15993       if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15994           TArgs->getIndex() == PmType->getIndex()) {
15995         if (!SemaRef.inTemplateInstantiation())
15996           SemaRef.Diag(TpDecl->getLocation(),
15997                        diag::ext_string_literal_operator_template);
15998         return false;
15999       }
16000     }
16001   }
16002 
16003   SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
16004                diag::err_literal_operator_template)
16005       << TpDecl->getTemplateParameters()->getSourceRange();
16006   return true;
16007 }
16008 
16009 /// CheckLiteralOperatorDeclaration - Check whether the declaration
16010 /// of this literal operator function is well-formed. If so, returns
16011 /// false; otherwise, emits appropriate diagnostics and returns true.
16012 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
16013   if (isa<CXXMethodDecl>(FnDecl)) {
16014     Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
16015       << FnDecl->getDeclName();
16016     return true;
16017   }
16018 
16019   if (FnDecl->isExternC()) {
16020     Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
16021     if (const LinkageSpecDecl *LSD =
16022             FnDecl->getDeclContext()->getExternCContext())
16023       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
16024     return true;
16025   }
16026 
16027   // This might be the definition of a literal operator template.
16028   FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
16029 
16030   // This might be a specialization of a literal operator template.
16031   if (!TpDecl)
16032     TpDecl = FnDecl->getPrimaryTemplate();
16033 
16034   // template <char...> type operator "" name() and
16035   // template <class T, T...> type operator "" name() are the only valid
16036   // template signatures, and the only valid signatures with no parameters.
16037   //
16038   // C++20 also allows template <SomeClass T> type operator "" name().
16039   if (TpDecl) {
16040     if (FnDecl->param_size() != 0) {
16041       Diag(FnDecl->getLocation(),
16042            diag::err_literal_operator_template_with_params);
16043       return true;
16044     }
16045 
16046     if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
16047       return true;
16048 
16049   } else if (FnDecl->param_size() == 1) {
16050     const ParmVarDecl *Param = FnDecl->getParamDecl(0);
16051 
16052     QualType ParamType = Param->getType().getUnqualifiedType();
16053 
16054     // Only unsigned long long int, long double, any character type, and const
16055     // char * are allowed as the only parameters.
16056     if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
16057         ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
16058         Context.hasSameType(ParamType, Context.CharTy) ||
16059         Context.hasSameType(ParamType, Context.WideCharTy) ||
16060         Context.hasSameType(ParamType, Context.Char8Ty) ||
16061         Context.hasSameType(ParamType, Context.Char16Ty) ||
16062         Context.hasSameType(ParamType, Context.Char32Ty)) {
16063     } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
16064       QualType InnerType = Ptr->getPointeeType();
16065 
16066       // Pointer parameter must be a const char *.
16067       if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
16068                                 Context.CharTy) &&
16069             InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
16070         Diag(Param->getSourceRange().getBegin(),
16071              diag::err_literal_operator_param)
16072             << ParamType << "'const char *'" << Param->getSourceRange();
16073         return true;
16074       }
16075 
16076     } else if (ParamType->isRealFloatingType()) {
16077       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16078           << ParamType << Context.LongDoubleTy << Param->getSourceRange();
16079       return true;
16080 
16081     } else if (ParamType->isIntegerType()) {
16082       Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
16083           << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
16084       return true;
16085 
16086     } else {
16087       Diag(Param->getSourceRange().getBegin(),
16088            diag::err_literal_operator_invalid_param)
16089           << ParamType << Param->getSourceRange();
16090       return true;
16091     }
16092 
16093   } else if (FnDecl->param_size() == 2) {
16094     FunctionDecl::param_iterator Param = FnDecl->param_begin();
16095 
16096     // First, verify that the first parameter is correct.
16097 
16098     QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
16099 
16100     // Two parameter function must have a pointer to const as a
16101     // first parameter; let's strip those qualifiers.
16102     const PointerType *PT = FirstParamType->getAs<PointerType>();
16103 
16104     if (!PT) {
16105       Diag((*Param)->getSourceRange().getBegin(),
16106            diag::err_literal_operator_param)
16107           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16108       return true;
16109     }
16110 
16111     QualType PointeeType = PT->getPointeeType();
16112     // First parameter must be const
16113     if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16114       Diag((*Param)->getSourceRange().getBegin(),
16115            diag::err_literal_operator_param)
16116           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16117       return true;
16118     }
16119 
16120     QualType InnerType = PointeeType.getUnqualifiedType();
16121     // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16122     // const char32_t* are allowed as the first parameter to a two-parameter
16123     // function
16124     if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16125           Context.hasSameType(InnerType, Context.WideCharTy) ||
16126           Context.hasSameType(InnerType, Context.Char8Ty) ||
16127           Context.hasSameType(InnerType, Context.Char16Ty) ||
16128           Context.hasSameType(InnerType, Context.Char32Ty))) {
16129       Diag((*Param)->getSourceRange().getBegin(),
16130            diag::err_literal_operator_param)
16131           << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16132       return true;
16133     }
16134 
16135     // Move on to the second and final parameter.
16136     ++Param;
16137 
16138     // The second parameter must be a std::size_t.
16139     QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16140     if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16141       Diag((*Param)->getSourceRange().getBegin(),
16142            diag::err_literal_operator_param)
16143           << SecondParamType << Context.getSizeType()
16144           << (*Param)->getSourceRange();
16145       return true;
16146     }
16147   } else {
16148     Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16149     return true;
16150   }
16151 
16152   // Parameters are good.
16153 
16154   // A parameter-declaration-clause containing a default argument is not
16155   // equivalent to any of the permitted forms.
16156   for (auto Param : FnDecl->parameters()) {
16157     if (Param->hasDefaultArg()) {
16158       Diag(Param->getDefaultArgRange().getBegin(),
16159            diag::err_literal_operator_default_argument)
16160         << Param->getDefaultArgRange();
16161       break;
16162     }
16163   }
16164 
16165   StringRef LiteralName
16166     = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16167   if (LiteralName[0] != '_' &&
16168       !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16169     // C++11 [usrlit.suffix]p1:
16170     //   Literal suffix identifiers that do not start with an underscore
16171     //   are reserved for future standardization.
16172     Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16173       << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16174   }
16175 
16176   return false;
16177 }
16178 
16179 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16180 /// linkage specification, including the language and (if present)
16181 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
16182 /// language string literal. LBraceLoc, if valid, provides the location of
16183 /// the '{' brace. Otherwise, this linkage specification does not
16184 /// have any braces.
16185 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16186                                            Expr *LangStr,
16187                                            SourceLocation LBraceLoc) {
16188   StringLiteral *Lit = cast<StringLiteral>(LangStr);
16189   if (!Lit->isAscii()) {
16190     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16191       << LangStr->getSourceRange();
16192     return nullptr;
16193   }
16194 
16195   StringRef Lang = Lit->getString();
16196   LinkageSpecDecl::LanguageIDs Language;
16197   if (Lang == "C")
16198     Language = LinkageSpecDecl::lang_c;
16199   else if (Lang == "C++")
16200     Language = LinkageSpecDecl::lang_cxx;
16201   else {
16202     Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16203       << LangStr->getSourceRange();
16204     return nullptr;
16205   }
16206 
16207   // FIXME: Add all the various semantics of linkage specifications
16208 
16209   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16210                                                LangStr->getExprLoc(), Language,
16211                                                LBraceLoc.isValid());
16212 
16213   /// C++ [module.unit]p7.2.3
16214   /// - Otherwise, if the declaration
16215   ///   - ...
16216   ///   - ...
16217   ///   - appears within a linkage-specification,
16218   ///   it is attached to the global module.
16219   ///
16220   /// If the declaration is already in global module fragment, we don't
16221   /// need to attach it again.
16222   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
16223     Module *GlobalModule =
16224         PushGlobalModuleFragment(ExternLoc, /*IsImplicit=*/true);
16225     D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16226     D->setLocalOwningModule(GlobalModule);
16227   }
16228 
16229   CurContext->addDecl(D);
16230   PushDeclContext(S, D);
16231   return D;
16232 }
16233 
16234 /// ActOnFinishLinkageSpecification - Complete the definition of
16235 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
16236 /// valid, it's the position of the closing '}' brace in a linkage
16237 /// specification that uses braces.
16238 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16239                                             Decl *LinkageSpec,
16240                                             SourceLocation RBraceLoc) {
16241   if (RBraceLoc.isValid()) {
16242     LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16243     LSDecl->setRBraceLoc(RBraceLoc);
16244   }
16245 
16246   // If the current module doesn't has Parent, it implies that the
16247   // LinkageSpec isn't in the module created by itself. So we don't
16248   // need to pop it.
16249   if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
16250       getCurrentModule()->isGlobalModule() && getCurrentModule()->Parent)
16251     PopGlobalModuleFragment();
16252 
16253   PopDeclContext();
16254   return LinkageSpec;
16255 }
16256 
16257 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16258                                   const ParsedAttributesView &AttrList,
16259                                   SourceLocation SemiLoc) {
16260   Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16261   // Attribute declarations appertain to empty declaration so we handle
16262   // them here.
16263   ProcessDeclAttributeList(S, ED, AttrList);
16264 
16265   CurContext->addDecl(ED);
16266   return ED;
16267 }
16268 
16269 /// Perform semantic analysis for the variable declaration that
16270 /// occurs within a C++ catch clause, returning the newly-created
16271 /// variable.
16272 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16273                                          TypeSourceInfo *TInfo,
16274                                          SourceLocation StartLoc,
16275                                          SourceLocation Loc,
16276                                          IdentifierInfo *Name) {
16277   bool Invalid = false;
16278   QualType ExDeclType = TInfo->getType();
16279 
16280   // Arrays and functions decay.
16281   if (ExDeclType->isArrayType())
16282     ExDeclType = Context.getArrayDecayedType(ExDeclType);
16283   else if (ExDeclType->isFunctionType())
16284     ExDeclType = Context.getPointerType(ExDeclType);
16285 
16286   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16287   // The exception-declaration shall not denote a pointer or reference to an
16288   // incomplete type, other than [cv] void*.
16289   // N2844 forbids rvalue references.
16290   if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16291     Diag(Loc, diag::err_catch_rvalue_ref);
16292     Invalid = true;
16293   }
16294 
16295   if (ExDeclType->isVariablyModifiedType()) {
16296     Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16297     Invalid = true;
16298   }
16299 
16300   QualType BaseType = ExDeclType;
16301   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16302   unsigned DK = diag::err_catch_incomplete;
16303   if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16304     BaseType = Ptr->getPointeeType();
16305     Mode = 1;
16306     DK = diag::err_catch_incomplete_ptr;
16307   } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16308     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16309     BaseType = Ref->getPointeeType();
16310     Mode = 2;
16311     DK = diag::err_catch_incomplete_ref;
16312   }
16313   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16314       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16315     Invalid = true;
16316 
16317   if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16318     Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16319     Invalid = true;
16320   }
16321 
16322   if (!Invalid && !ExDeclType->isDependentType() &&
16323       RequireNonAbstractType(Loc, ExDeclType,
16324                              diag::err_abstract_type_in_decl,
16325                              AbstractVariableType))
16326     Invalid = true;
16327 
16328   // Only the non-fragile NeXT runtime currently supports C++ catches
16329   // of ObjC types, and no runtime supports catching ObjC types by value.
16330   if (!Invalid && getLangOpts().ObjC) {
16331     QualType T = ExDeclType;
16332     if (const ReferenceType *RT = T->getAs<ReferenceType>())
16333       T = RT->getPointeeType();
16334 
16335     if (T->isObjCObjectType()) {
16336       Diag(Loc, diag::err_objc_object_catch);
16337       Invalid = true;
16338     } else if (T->isObjCObjectPointerType()) {
16339       // FIXME: should this be a test for macosx-fragile specifically?
16340       if (getLangOpts().ObjCRuntime.isFragile())
16341         Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16342     }
16343   }
16344 
16345   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16346                                     ExDeclType, TInfo, SC_None);
16347   ExDecl->setExceptionVariable(true);
16348 
16349   // In ARC, infer 'retaining' for variables of retainable type.
16350   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16351     Invalid = true;
16352 
16353   if (!Invalid && !ExDeclType->isDependentType()) {
16354     if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16355       // Insulate this from anything else we might currently be parsing.
16356       EnterExpressionEvaluationContext scope(
16357           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16358 
16359       // C++ [except.handle]p16:
16360       //   The object declared in an exception-declaration or, if the
16361       //   exception-declaration does not specify a name, a temporary (12.2) is
16362       //   copy-initialized (8.5) from the exception object. [...]
16363       //   The object is destroyed when the handler exits, after the destruction
16364       //   of any automatic objects initialized within the handler.
16365       //
16366       // We just pretend to initialize the object with itself, then make sure
16367       // it can be destroyed later.
16368       QualType initType = Context.getExceptionObjectType(ExDeclType);
16369 
16370       InitializedEntity entity =
16371         InitializedEntity::InitializeVariable(ExDecl);
16372       InitializationKind initKind =
16373         InitializationKind::CreateCopy(Loc, SourceLocation());
16374 
16375       Expr *opaqueValue =
16376         new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16377       InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16378       ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16379       if (result.isInvalid())
16380         Invalid = true;
16381       else {
16382         // If the constructor used was non-trivial, set this as the
16383         // "initializer".
16384         CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16385         if (!construct->getConstructor()->isTrivial()) {
16386           Expr *init = MaybeCreateExprWithCleanups(construct);
16387           ExDecl->setInit(init);
16388         }
16389 
16390         // And make sure it's destructable.
16391         FinalizeVarWithDestructor(ExDecl, recordType);
16392       }
16393     }
16394   }
16395 
16396   if (Invalid)
16397     ExDecl->setInvalidDecl();
16398 
16399   return ExDecl;
16400 }
16401 
16402 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16403 /// handler.
16404 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16405   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16406   bool Invalid = D.isInvalidType();
16407 
16408   // Check for unexpanded parameter packs.
16409   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16410                                       UPPC_ExceptionType)) {
16411     TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16412                                              D.getIdentifierLoc());
16413     Invalid = true;
16414   }
16415 
16416   IdentifierInfo *II = D.getIdentifier();
16417   if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16418                                              LookupOrdinaryName,
16419                                              ForVisibleRedeclaration)) {
16420     // The scope should be freshly made just for us. There is just no way
16421     // it contains any previous declaration, except for function parameters in
16422     // a function-try-block's catch statement.
16423     assert(!S->isDeclScope(PrevDecl));
16424     if (isDeclInScope(PrevDecl, CurContext, S)) {
16425       Diag(D.getIdentifierLoc(), diag::err_redefinition)
16426         << D.getIdentifier();
16427       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16428       Invalid = true;
16429     } else if (PrevDecl->isTemplateParameter())
16430       // Maybe we will complain about the shadowed template parameter.
16431       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16432   }
16433 
16434   if (D.getCXXScopeSpec().isSet() && !Invalid) {
16435     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16436       << D.getCXXScopeSpec().getRange();
16437     Invalid = true;
16438   }
16439 
16440   VarDecl *ExDecl = BuildExceptionDeclaration(
16441       S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16442   if (Invalid)
16443     ExDecl->setInvalidDecl();
16444 
16445   // Add the exception declaration into this scope.
16446   if (II)
16447     PushOnScopeChains(ExDecl, S);
16448   else
16449     CurContext->addDecl(ExDecl);
16450 
16451   ProcessDeclAttributes(S, ExDecl, D);
16452   return ExDecl;
16453 }
16454 
16455 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16456                                          Expr *AssertExpr,
16457                                          Expr *AssertMessageExpr,
16458                                          SourceLocation RParenLoc) {
16459   StringLiteral *AssertMessage =
16460       AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16461 
16462   if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16463     return nullptr;
16464 
16465   return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16466                                       AssertMessage, RParenLoc, false);
16467 }
16468 
16469 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16470                                          Expr *AssertExpr,
16471                                          StringLiteral *AssertMessage,
16472                                          SourceLocation RParenLoc,
16473                                          bool Failed) {
16474   assert(AssertExpr != nullptr && "Expected non-null condition");
16475   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16476       !Failed) {
16477     // In a static_assert-declaration, the constant-expression shall be a
16478     // constant expression that can be contextually converted to bool.
16479     ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16480     if (Converted.isInvalid())
16481       Failed = true;
16482 
16483     ExprResult FullAssertExpr =
16484         ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16485                             /*DiscardedValue*/ false,
16486                             /*IsConstexpr*/ true);
16487     if (FullAssertExpr.isInvalid())
16488       Failed = true;
16489     else
16490       AssertExpr = FullAssertExpr.get();
16491 
16492     llvm::APSInt Cond;
16493     if (!Failed && VerifyIntegerConstantExpression(
16494                        AssertExpr, &Cond,
16495                        diag::err_static_assert_expression_is_not_constant)
16496                        .isInvalid())
16497       Failed = true;
16498 
16499     if (!Failed && !Cond) {
16500       SmallString<256> MsgBuffer;
16501       llvm::raw_svector_ostream Msg(MsgBuffer);
16502       if (AssertMessage)
16503         AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16504 
16505       Expr *InnerCond = nullptr;
16506       std::string InnerCondDescription;
16507       std::tie(InnerCond, InnerCondDescription) =
16508         findFailedBooleanCondition(Converted.get());
16509       if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16510         // Drill down into concept specialization expressions to see why they
16511         // weren't satisfied.
16512         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16513           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16514         ConstraintSatisfaction Satisfaction;
16515         if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16516           DiagnoseUnsatisfiedConstraint(Satisfaction);
16517       } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16518                            && !isa<IntegerLiteral>(InnerCond)) {
16519         Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16520           << InnerCondDescription << !AssertMessage
16521           << Msg.str() << InnerCond->getSourceRange();
16522       } else {
16523         Diag(StaticAssertLoc, diag::err_static_assert_failed)
16524           << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16525       }
16526       Failed = true;
16527     }
16528   } else {
16529     ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16530                                                     /*DiscardedValue*/false,
16531                                                     /*IsConstexpr*/true);
16532     if (FullAssertExpr.isInvalid())
16533       Failed = true;
16534     else
16535       AssertExpr = FullAssertExpr.get();
16536   }
16537 
16538   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16539                                         AssertExpr, AssertMessage, RParenLoc,
16540                                         Failed);
16541 
16542   CurContext->addDecl(Decl);
16543   return Decl;
16544 }
16545 
16546 /// Perform semantic analysis of the given friend type declaration.
16547 ///
16548 /// \returns A friend declaration that.
16549 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16550                                       SourceLocation FriendLoc,
16551                                       TypeSourceInfo *TSInfo) {
16552   assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16553 
16554   QualType T = TSInfo->getType();
16555   SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16556 
16557   // C++03 [class.friend]p2:
16558   //   An elaborated-type-specifier shall be used in a friend declaration
16559   //   for a class.*
16560   //
16561   //   * The class-key of the elaborated-type-specifier is required.
16562   if (!CodeSynthesisContexts.empty()) {
16563     // Do not complain about the form of friend template types during any kind
16564     // of code synthesis. For template instantiation, we will have complained
16565     // when the template was defined.
16566   } else {
16567     if (!T->isElaboratedTypeSpecifier()) {
16568       // If we evaluated the type to a record type, suggest putting
16569       // a tag in front.
16570       if (const RecordType *RT = T->getAs<RecordType>()) {
16571         RecordDecl *RD = RT->getDecl();
16572 
16573         SmallString<16> InsertionText(" ");
16574         InsertionText += RD->getKindName();
16575 
16576         Diag(TypeRange.getBegin(),
16577              getLangOpts().CPlusPlus11 ?
16578                diag::warn_cxx98_compat_unelaborated_friend_type :
16579                diag::ext_unelaborated_friend_type)
16580           << (unsigned) RD->getTagKind()
16581           << T
16582           << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16583                                         InsertionText);
16584       } else {
16585         Diag(FriendLoc,
16586              getLangOpts().CPlusPlus11 ?
16587                diag::warn_cxx98_compat_nonclass_type_friend :
16588                diag::ext_nonclass_type_friend)
16589           << T
16590           << TypeRange;
16591       }
16592     } else if (T->getAs<EnumType>()) {
16593       Diag(FriendLoc,
16594            getLangOpts().CPlusPlus11 ?
16595              diag::warn_cxx98_compat_enum_friend :
16596              diag::ext_enum_friend)
16597         << T
16598         << TypeRange;
16599     }
16600 
16601     // C++11 [class.friend]p3:
16602     //   A friend declaration that does not declare a function shall have one
16603     //   of the following forms:
16604     //     friend elaborated-type-specifier ;
16605     //     friend simple-type-specifier ;
16606     //     friend typename-specifier ;
16607     if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16608       Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16609   }
16610 
16611   //   If the type specifier in a friend declaration designates a (possibly
16612   //   cv-qualified) class type, that class is declared as a friend; otherwise,
16613   //   the friend declaration is ignored.
16614   return FriendDecl::Create(Context, CurContext,
16615                             TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16616                             FriendLoc);
16617 }
16618 
16619 /// Handle a friend tag declaration where the scope specifier was
16620 /// templated.
16621 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16622                                     unsigned TagSpec, SourceLocation TagLoc,
16623                                     CXXScopeSpec &SS, IdentifierInfo *Name,
16624                                     SourceLocation NameLoc,
16625                                     const ParsedAttributesView &Attr,
16626                                     MultiTemplateParamsArg TempParamLists) {
16627   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16628 
16629   bool IsMemberSpecialization = false;
16630   bool Invalid = false;
16631 
16632   if (TemplateParameterList *TemplateParams =
16633           MatchTemplateParametersToScopeSpecifier(
16634               TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16635               IsMemberSpecialization, Invalid)) {
16636     if (TemplateParams->size() > 0) {
16637       // This is a declaration of a class template.
16638       if (Invalid)
16639         return nullptr;
16640 
16641       return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16642                                 NameLoc, Attr, TemplateParams, AS_public,
16643                                 /*ModulePrivateLoc=*/SourceLocation(),
16644                                 FriendLoc, TempParamLists.size() - 1,
16645                                 TempParamLists.data()).get();
16646     } else {
16647       // The "template<>" header is extraneous.
16648       Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16649         << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16650       IsMemberSpecialization = true;
16651     }
16652   }
16653 
16654   if (Invalid) return nullptr;
16655 
16656   bool isAllExplicitSpecializations = true;
16657   for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16658     if (TempParamLists[I]->size()) {
16659       isAllExplicitSpecializations = false;
16660       break;
16661     }
16662   }
16663 
16664   // FIXME: don't ignore attributes.
16665 
16666   // If it's explicit specializations all the way down, just forget
16667   // about the template header and build an appropriate non-templated
16668   // friend.  TODO: for source fidelity, remember the headers.
16669   if (isAllExplicitSpecializations) {
16670     if (SS.isEmpty()) {
16671       bool Owned = false;
16672       bool IsDependent = false;
16673       return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16674                       Attr, AS_public,
16675                       /*ModulePrivateLoc=*/SourceLocation(),
16676                       MultiTemplateParamsArg(), Owned, IsDependent,
16677                       /*ScopedEnumKWLoc=*/SourceLocation(),
16678                       /*ScopedEnumUsesClassTag=*/false,
16679                       /*UnderlyingType=*/TypeResult(),
16680                       /*IsTypeSpecifier=*/false,
16681                       /*IsTemplateParamOrArg=*/false);
16682     }
16683 
16684     NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16685     ElaboratedTypeKeyword Keyword
16686       = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16687     QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16688                                    *Name, NameLoc);
16689     if (T.isNull())
16690       return nullptr;
16691 
16692     TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16693     if (isa<DependentNameType>(T)) {
16694       DependentNameTypeLoc TL =
16695           TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16696       TL.setElaboratedKeywordLoc(TagLoc);
16697       TL.setQualifierLoc(QualifierLoc);
16698       TL.setNameLoc(NameLoc);
16699     } else {
16700       ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16701       TL.setElaboratedKeywordLoc(TagLoc);
16702       TL.setQualifierLoc(QualifierLoc);
16703       TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16704     }
16705 
16706     FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16707                                             TSI, FriendLoc, TempParamLists);
16708     Friend->setAccess(AS_public);
16709     CurContext->addDecl(Friend);
16710     return Friend;
16711   }
16712 
16713   assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16714 
16715 
16716 
16717   // Handle the case of a templated-scope friend class.  e.g.
16718   //   template <class T> class A<T>::B;
16719   // FIXME: we don't support these right now.
16720   Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16721     << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16722   ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16723   QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16724   TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16725   DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16726   TL.setElaboratedKeywordLoc(TagLoc);
16727   TL.setQualifierLoc(SS.getWithLocInContext(Context));
16728   TL.setNameLoc(NameLoc);
16729 
16730   FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16731                                           TSI, FriendLoc, TempParamLists);
16732   Friend->setAccess(AS_public);
16733   Friend->setUnsupportedFriend(true);
16734   CurContext->addDecl(Friend);
16735   return Friend;
16736 }
16737 
16738 /// Handle a friend type declaration.  This works in tandem with
16739 /// ActOnTag.
16740 ///
16741 /// Notes on friend class templates:
16742 ///
16743 /// We generally treat friend class declarations as if they were
16744 /// declaring a class.  So, for example, the elaborated type specifier
16745 /// in a friend declaration is required to obey the restrictions of a
16746 /// class-head (i.e. no typedefs in the scope chain), template
16747 /// parameters are required to match up with simple template-ids, &c.
16748 /// However, unlike when declaring a template specialization, it's
16749 /// okay to refer to a template specialization without an empty
16750 /// template parameter declaration, e.g.
16751 ///   friend class A<T>::B<unsigned>;
16752 /// We permit this as a special case; if there are any template
16753 /// parameters present at all, require proper matching, i.e.
16754 ///   template <> template \<class T> friend class A<int>::B;
16755 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16756                                 MultiTemplateParamsArg TempParams) {
16757   SourceLocation Loc = DS.getBeginLoc();
16758 
16759   assert(DS.isFriendSpecified());
16760   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16761 
16762   // C++ [class.friend]p3:
16763   // A friend declaration that does not declare a function shall have one of
16764   // the following forms:
16765   //     friend elaborated-type-specifier ;
16766   //     friend simple-type-specifier ;
16767   //     friend typename-specifier ;
16768   //
16769   // Any declaration with a type qualifier does not have that form. (It's
16770   // legal to specify a qualified type as a friend, you just can't write the
16771   // keywords.)
16772   if (DS.getTypeQualifiers()) {
16773     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16774       Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16775     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16776       Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16777     if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16778       Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16779     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16780       Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16781     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16782       Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16783   }
16784 
16785   // Try to convert the decl specifier to a type.  This works for
16786   // friend templates because ActOnTag never produces a ClassTemplateDecl
16787   // for a TUK_Friend.
16788   Declarator TheDeclarator(DS, DeclaratorContext::Member);
16789   TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16790   QualType T = TSI->getType();
16791   if (TheDeclarator.isInvalidType())
16792     return nullptr;
16793 
16794   if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16795     return nullptr;
16796 
16797   // This is definitely an error in C++98.  It's probably meant to
16798   // be forbidden in C++0x, too, but the specification is just
16799   // poorly written.
16800   //
16801   // The problem is with declarations like the following:
16802   //   template <T> friend A<T>::foo;
16803   // where deciding whether a class C is a friend or not now hinges
16804   // on whether there exists an instantiation of A that causes
16805   // 'foo' to equal C.  There are restrictions on class-heads
16806   // (which we declare (by fiat) elaborated friend declarations to
16807   // be) that makes this tractable.
16808   //
16809   // FIXME: handle "template <> friend class A<T>;", which
16810   // is possibly well-formed?  Who even knows?
16811   if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16812     Diag(Loc, diag::err_tagless_friend_type_template)
16813       << DS.getSourceRange();
16814     return nullptr;
16815   }
16816 
16817   // C++98 [class.friend]p1: A friend of a class is a function
16818   //   or class that is not a member of the class . . .
16819   // This is fixed in DR77, which just barely didn't make the C++03
16820   // deadline.  It's also a very silly restriction that seriously
16821   // affects inner classes and which nobody else seems to implement;
16822   // thus we never diagnose it, not even in -pedantic.
16823   //
16824   // But note that we could warn about it: it's always useless to
16825   // friend one of your own members (it's not, however, worthless to
16826   // friend a member of an arbitrary specialization of your template).
16827 
16828   Decl *D;
16829   if (!TempParams.empty())
16830     D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16831                                    TempParams,
16832                                    TSI,
16833                                    DS.getFriendSpecLoc());
16834   else
16835     D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16836 
16837   if (!D)
16838     return nullptr;
16839 
16840   D->setAccess(AS_public);
16841   CurContext->addDecl(D);
16842 
16843   return D;
16844 }
16845 
16846 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16847                                         MultiTemplateParamsArg TemplateParams) {
16848   const DeclSpec &DS = D.getDeclSpec();
16849 
16850   assert(DS.isFriendSpecified());
16851   assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16852 
16853   SourceLocation Loc = D.getIdentifierLoc();
16854   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16855 
16856   // C++ [class.friend]p1
16857   //   A friend of a class is a function or class....
16858   // Note that this sees through typedefs, which is intended.
16859   // It *doesn't* see through dependent types, which is correct
16860   // according to [temp.arg.type]p3:
16861   //   If a declaration acquires a function type through a
16862   //   type dependent on a template-parameter and this causes
16863   //   a declaration that does not use the syntactic form of a
16864   //   function declarator to have a function type, the program
16865   //   is ill-formed.
16866   if (!TInfo->getType()->isFunctionType()) {
16867     Diag(Loc, diag::err_unexpected_friend);
16868 
16869     // It might be worthwhile to try to recover by creating an
16870     // appropriate declaration.
16871     return nullptr;
16872   }
16873 
16874   // C++ [namespace.memdef]p3
16875   //  - If a friend declaration in a non-local class first declares a
16876   //    class or function, the friend class or function is a member
16877   //    of the innermost enclosing namespace.
16878   //  - The name of the friend is not found by simple name lookup
16879   //    until a matching declaration is provided in that namespace
16880   //    scope (either before or after the class declaration granting
16881   //    friendship).
16882   //  - If a friend function is called, its name may be found by the
16883   //    name lookup that considers functions from namespaces and
16884   //    classes associated with the types of the function arguments.
16885   //  - When looking for a prior declaration of a class or a function
16886   //    declared as a friend, scopes outside the innermost enclosing
16887   //    namespace scope are not considered.
16888 
16889   CXXScopeSpec &SS = D.getCXXScopeSpec();
16890   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16891   assert(NameInfo.getName());
16892 
16893   // Check for unexpanded parameter packs.
16894   if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16895       DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16896       DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16897     return nullptr;
16898 
16899   // The context we found the declaration in, or in which we should
16900   // create the declaration.
16901   DeclContext *DC;
16902   Scope *DCScope = S;
16903   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16904                         ForExternalRedeclaration);
16905 
16906   // There are five cases here.
16907   //   - There's no scope specifier and we're in a local class. Only look
16908   //     for functions declared in the immediately-enclosing block scope.
16909   // We recover from invalid scope qualifiers as if they just weren't there.
16910   FunctionDecl *FunctionContainingLocalClass = nullptr;
16911   if ((SS.isInvalid() || !SS.isSet()) &&
16912       (FunctionContainingLocalClass =
16913            cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16914     // C++11 [class.friend]p11:
16915     //   If a friend declaration appears in a local class and the name
16916     //   specified is an unqualified name, a prior declaration is
16917     //   looked up without considering scopes that are outside the
16918     //   innermost enclosing non-class scope. For a friend function
16919     //   declaration, if there is no prior declaration, the program is
16920     //   ill-formed.
16921 
16922     // Find the innermost enclosing non-class scope. This is the block
16923     // scope containing the local class definition (or for a nested class,
16924     // the outer local class).
16925     DCScope = S->getFnParent();
16926 
16927     // Look up the function name in the scope.
16928     Previous.clear(LookupLocalFriendName);
16929     LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16930 
16931     if (!Previous.empty()) {
16932       // All possible previous declarations must have the same context:
16933       // either they were declared at block scope or they are members of
16934       // one of the enclosing local classes.
16935       DC = Previous.getRepresentativeDecl()->getDeclContext();
16936     } else {
16937       // This is ill-formed, but provide the context that we would have
16938       // declared the function in, if we were permitted to, for error recovery.
16939       DC = FunctionContainingLocalClass;
16940     }
16941     adjustContextForLocalExternDecl(DC);
16942 
16943     // C++ [class.friend]p6:
16944     //   A function can be defined in a friend declaration of a class if and
16945     //   only if the class is a non-local class (9.8), the function name is
16946     //   unqualified, and the function has namespace scope.
16947     if (D.isFunctionDefinition()) {
16948       Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16949     }
16950 
16951   //   - There's no scope specifier, in which case we just go to the
16952   //     appropriate scope and look for a function or function template
16953   //     there as appropriate.
16954   } else if (SS.isInvalid() || !SS.isSet()) {
16955     // C++11 [namespace.memdef]p3:
16956     //   If the name in a friend declaration is neither qualified nor
16957     //   a template-id and the declaration is a function or an
16958     //   elaborated-type-specifier, the lookup to determine whether
16959     //   the entity has been previously declared shall not consider
16960     //   any scopes outside the innermost enclosing namespace.
16961     bool isTemplateId =
16962         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16963 
16964     // Find the appropriate context according to the above.
16965     DC = CurContext;
16966 
16967     // Skip class contexts.  If someone can cite chapter and verse
16968     // for this behavior, that would be nice --- it's what GCC and
16969     // EDG do, and it seems like a reasonable intent, but the spec
16970     // really only says that checks for unqualified existing
16971     // declarations should stop at the nearest enclosing namespace,
16972     // not that they should only consider the nearest enclosing
16973     // namespace.
16974     while (DC->isRecord())
16975       DC = DC->getParent();
16976 
16977     DeclContext *LookupDC = DC->getNonTransparentContext();
16978     while (true) {
16979       LookupQualifiedName(Previous, LookupDC);
16980 
16981       if (!Previous.empty()) {
16982         DC = LookupDC;
16983         break;
16984       }
16985 
16986       if (isTemplateId) {
16987         if (isa<TranslationUnitDecl>(LookupDC)) break;
16988       } else {
16989         if (LookupDC->isFileContext()) break;
16990       }
16991       LookupDC = LookupDC->getParent();
16992     }
16993 
16994     DCScope = getScopeForDeclContext(S, DC);
16995 
16996   //   - There's a non-dependent scope specifier, in which case we
16997   //     compute it and do a previous lookup there for a function
16998   //     or function template.
16999   } else if (!SS.getScopeRep()->isDependent()) {
17000     DC = computeDeclContext(SS);
17001     if (!DC) return nullptr;
17002 
17003     if (RequireCompleteDeclContext(SS, DC)) return nullptr;
17004 
17005     LookupQualifiedName(Previous, DC);
17006 
17007     // C++ [class.friend]p1: A friend of a class is a function or
17008     //   class that is not a member of the class . . .
17009     if (DC->Equals(CurContext))
17010       Diag(DS.getFriendSpecLoc(),
17011            getLangOpts().CPlusPlus11 ?
17012              diag::warn_cxx98_compat_friend_is_member :
17013              diag::err_friend_is_member);
17014 
17015     if (D.isFunctionDefinition()) {
17016       // C++ [class.friend]p6:
17017       //   A function can be defined in a friend declaration of a class if and
17018       //   only if the class is a non-local class (9.8), the function name is
17019       //   unqualified, and the function has namespace scope.
17020       //
17021       // FIXME: We should only do this if the scope specifier names the
17022       // innermost enclosing namespace; otherwise the fixit changes the
17023       // meaning of the code.
17024       SemaDiagnosticBuilder DB
17025         = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
17026 
17027       DB << SS.getScopeRep();
17028       if (DC->isFileContext())
17029         DB << FixItHint::CreateRemoval(SS.getRange());
17030       SS.clear();
17031     }
17032 
17033   //   - There's a scope specifier that does not match any template
17034   //     parameter lists, in which case we use some arbitrary context,
17035   //     create a method or method template, and wait for instantiation.
17036   //   - There's a scope specifier that does match some template
17037   //     parameter lists, which we don't handle right now.
17038   } else {
17039     if (D.isFunctionDefinition()) {
17040       // C++ [class.friend]p6:
17041       //   A function can be defined in a friend declaration of a class if and
17042       //   only if the class is a non-local class (9.8), the function name is
17043       //   unqualified, and the function has namespace scope.
17044       Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
17045         << SS.getScopeRep();
17046     }
17047 
17048     DC = CurContext;
17049     assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
17050   }
17051 
17052   if (!DC->isRecord()) {
17053     int DiagArg = -1;
17054     switch (D.getName().getKind()) {
17055     case UnqualifiedIdKind::IK_ConstructorTemplateId:
17056     case UnqualifiedIdKind::IK_ConstructorName:
17057       DiagArg = 0;
17058       break;
17059     case UnqualifiedIdKind::IK_DestructorName:
17060       DiagArg = 1;
17061       break;
17062     case UnqualifiedIdKind::IK_ConversionFunctionId:
17063       DiagArg = 2;
17064       break;
17065     case UnqualifiedIdKind::IK_DeductionGuideName:
17066       DiagArg = 3;
17067       break;
17068     case UnqualifiedIdKind::IK_Identifier:
17069     case UnqualifiedIdKind::IK_ImplicitSelfParam:
17070     case UnqualifiedIdKind::IK_LiteralOperatorId:
17071     case UnqualifiedIdKind::IK_OperatorFunctionId:
17072     case UnqualifiedIdKind::IK_TemplateId:
17073       break;
17074     }
17075     // This implies that it has to be an operator or function.
17076     if (DiagArg >= 0) {
17077       Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
17078       return nullptr;
17079     }
17080   }
17081 
17082   // FIXME: This is an egregious hack to cope with cases where the scope stack
17083   // does not contain the declaration context, i.e., in an out-of-line
17084   // definition of a class.
17085   Scope FakeDCScope(S, Scope::DeclScope, Diags);
17086   if (!DCScope) {
17087     FakeDCScope.setEntity(DC);
17088     DCScope = &FakeDCScope;
17089   }
17090 
17091   bool AddToScope = true;
17092   NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
17093                                           TemplateParams, AddToScope);
17094   if (!ND) return nullptr;
17095 
17096   assert(ND->getLexicalDeclContext() == CurContext);
17097 
17098   // If we performed typo correction, we might have added a scope specifier
17099   // and changed the decl context.
17100   DC = ND->getDeclContext();
17101 
17102   // Add the function declaration to the appropriate lookup tables,
17103   // adjusting the redeclarations list as necessary.  We don't
17104   // want to do this yet if the friending class is dependent.
17105   //
17106   // Also update the scope-based lookup if the target context's
17107   // lookup context is in lexical scope.
17108   if (!CurContext->isDependentContext()) {
17109     DC = DC->getRedeclContext();
17110     DC->makeDeclVisibleInContext(ND);
17111     if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
17112       PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
17113   }
17114 
17115   FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
17116                                        D.getIdentifierLoc(), ND,
17117                                        DS.getFriendSpecLoc());
17118   FrD->setAccess(AS_public);
17119   CurContext->addDecl(FrD);
17120 
17121   if (ND->isInvalidDecl()) {
17122     FrD->setInvalidDecl();
17123   } else {
17124     if (DC->isRecord()) CheckFriendAccess(ND);
17125 
17126     FunctionDecl *FD;
17127     if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
17128       FD = FTD->getTemplatedDecl();
17129     else
17130       FD = cast<FunctionDecl>(ND);
17131 
17132     // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17133     // default argument expression, that declaration shall be a definition
17134     // and shall be the only declaration of the function or function
17135     // template in the translation unit.
17136     if (functionDeclHasDefaultArgument(FD)) {
17137       // We can't look at FD->getPreviousDecl() because it may not have been set
17138       // if we're in a dependent context. If the function is known to be a
17139       // redeclaration, we will have narrowed Previous down to the right decl.
17140       if (D.isRedeclaration()) {
17141         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17142         Diag(Previous.getRepresentativeDecl()->getLocation(),
17143              diag::note_previous_declaration);
17144       } else if (!D.isFunctionDefinition())
17145         Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17146     }
17147 
17148     // Mark templated-scope function declarations as unsupported.
17149     if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17150       Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17151         << SS.getScopeRep() << SS.getRange()
17152         << cast<CXXRecordDecl>(CurContext);
17153       FrD->setUnsupportedFriend(true);
17154     }
17155   }
17156 
17157   warnOnReservedIdentifier(ND);
17158 
17159   return ND;
17160 }
17161 
17162 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17163   AdjustDeclIfTemplate(Dcl);
17164 
17165   FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17166   if (!Fn) {
17167     Diag(DelLoc, diag::err_deleted_non_function);
17168     return;
17169   }
17170 
17171   // Deleted function does not have a body.
17172   Fn->setWillHaveBody(false);
17173 
17174   if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17175     // Don't consider the implicit declaration we generate for explicit
17176     // specializations. FIXME: Do not generate these implicit declarations.
17177     if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17178          Prev->getPreviousDecl()) &&
17179         !Prev->isDefined()) {
17180       Diag(DelLoc, diag::err_deleted_decl_not_first);
17181       Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17182            Prev->isImplicit() ? diag::note_previous_implicit_declaration
17183                               : diag::note_previous_declaration);
17184       // We can't recover from this; the declaration might have already
17185       // been used.
17186       Fn->setInvalidDecl();
17187       return;
17188     }
17189 
17190     // To maintain the invariant that functions are only deleted on their first
17191     // declaration, mark the implicitly-instantiated declaration of the
17192     // explicitly-specialized function as deleted instead of marking the
17193     // instantiated redeclaration.
17194     Fn = Fn->getCanonicalDecl();
17195   }
17196 
17197   // dllimport/dllexport cannot be deleted.
17198   if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17199     Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17200     Fn->setInvalidDecl();
17201   }
17202 
17203   // C++11 [basic.start.main]p3:
17204   //   A program that defines main as deleted [...] is ill-formed.
17205   if (Fn->isMain())
17206     Diag(DelLoc, diag::err_deleted_main);
17207 
17208   // C++11 [dcl.fct.def.delete]p4:
17209   //  A deleted function is implicitly inline.
17210   Fn->setImplicitlyInline();
17211   Fn->setDeletedAsWritten();
17212 }
17213 
17214 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17215   if (!Dcl || Dcl->isInvalidDecl())
17216     return;
17217 
17218   auto *FD = dyn_cast<FunctionDecl>(Dcl);
17219   if (!FD) {
17220     if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17221       if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17222         Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17223         return;
17224       }
17225     }
17226 
17227     Diag(DefaultLoc, diag::err_default_special_members)
17228         << getLangOpts().CPlusPlus20;
17229     return;
17230   }
17231 
17232   // Reject if this can't possibly be a defaultable function.
17233   DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17234   if (!DefKind &&
17235       // A dependent function that doesn't locally look defaultable can
17236       // still instantiate to a defaultable function if it's a constructor
17237       // or assignment operator.
17238       (!FD->isDependentContext() ||
17239        (!isa<CXXConstructorDecl>(FD) &&
17240         FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17241     Diag(DefaultLoc, diag::err_default_special_members)
17242         << getLangOpts().CPlusPlus20;
17243     return;
17244   }
17245 
17246   // Issue compatibility warning. We already warned if the operator is
17247   // 'operator<=>' when parsing the '<=>' token.
17248   if (DefKind.isComparison() &&
17249       DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17250     Diag(DefaultLoc, getLangOpts().CPlusPlus20
17251                          ? diag::warn_cxx17_compat_defaulted_comparison
17252                          : diag::ext_defaulted_comparison);
17253   }
17254 
17255   FD->setDefaulted();
17256   FD->setExplicitlyDefaulted();
17257 
17258   // Defer checking functions that are defaulted in a dependent context.
17259   if (FD->isDependentContext())
17260     return;
17261 
17262   // Unset that we will have a body for this function. We might not,
17263   // if it turns out to be trivial, and we don't need this marking now
17264   // that we've marked it as defaulted.
17265   FD->setWillHaveBody(false);
17266 
17267   if (DefKind.isComparison()) {
17268     // If this comparison's defaulting occurs within the definition of its
17269     // lexical class context, we have to do the checking when complete.
17270     if (auto const *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()))
17271       if (!RD->isCompleteDefinition())
17272         return;
17273   }
17274 
17275   // If this member fn was defaulted on its first declaration, we will have
17276   // already performed the checking in CheckCompletedCXXClass. Such a
17277   // declaration doesn't trigger an implicit definition.
17278   if (isa<CXXMethodDecl>(FD)) {
17279     const FunctionDecl *Primary = FD;
17280     if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17281       // Ask the template instantiation pattern that actually had the
17282       // '= default' on it.
17283       Primary = Pattern;
17284     if (Primary->getCanonicalDecl()->isDefaulted())
17285       return;
17286   }
17287 
17288   if (DefKind.isComparison()) {
17289     if (CheckExplicitlyDefaultedComparison(nullptr, FD, DefKind.asComparison()))
17290       FD->setInvalidDecl();
17291     else
17292       DefineDefaultedComparison(DefaultLoc, FD, DefKind.asComparison());
17293   } else {
17294     auto *MD = cast<CXXMethodDecl>(FD);
17295 
17296     if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
17297       MD->setInvalidDecl();
17298     else
17299       DefineDefaultedFunction(*this, MD, DefaultLoc);
17300   }
17301 }
17302 
17303 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17304   for (Stmt *SubStmt : S->children()) {
17305     if (!SubStmt)
17306       continue;
17307     if (isa<ReturnStmt>(SubStmt))
17308       Self.Diag(SubStmt->getBeginLoc(),
17309                 diag::err_return_in_constructor_handler);
17310     if (!isa<Expr>(SubStmt))
17311       SearchForReturnInStmt(Self, SubStmt);
17312   }
17313 }
17314 
17315 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17316   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17317     CXXCatchStmt *Handler = TryBlock->getHandler(I);
17318     SearchForReturnInStmt(*this, Handler);
17319   }
17320 }
17321 
17322 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17323                                              const CXXMethodDecl *Old) {
17324   const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17325   const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17326 
17327   if (OldFT->hasExtParameterInfos()) {
17328     for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17329       // A parameter of the overriding method should be annotated with noescape
17330       // if the corresponding parameter of the overridden method is annotated.
17331       if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17332           !NewFT->getExtParameterInfo(I).isNoEscape()) {
17333         Diag(New->getParamDecl(I)->getLocation(),
17334              diag::warn_overriding_method_missing_noescape);
17335         Diag(Old->getParamDecl(I)->getLocation(),
17336              diag::note_overridden_marked_noescape);
17337       }
17338   }
17339 
17340   // Virtual overrides must have the same code_seg.
17341   const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17342   const auto *NewCSA = New->getAttr<CodeSegAttr>();
17343   if ((NewCSA || OldCSA) &&
17344       (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17345     Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17346     Diag(Old->getLocation(), diag::note_previous_declaration);
17347     return true;
17348   }
17349 
17350   CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17351 
17352   // If the calling conventions match, everything is fine
17353   if (NewCC == OldCC)
17354     return false;
17355 
17356   // If the calling conventions mismatch because the new function is static,
17357   // suppress the calling convention mismatch error; the error about static
17358   // function override (err_static_overrides_virtual from
17359   // Sema::CheckFunctionDeclaration) is more clear.
17360   if (New->getStorageClass() == SC_Static)
17361     return false;
17362 
17363   Diag(New->getLocation(),
17364        diag::err_conflicting_overriding_cc_attributes)
17365     << New->getDeclName() << New->getType() << Old->getType();
17366   Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17367   return true;
17368 }
17369 
17370 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17371                                              const CXXMethodDecl *Old) {
17372   QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17373   QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17374 
17375   if (Context.hasSameType(NewTy, OldTy) ||
17376       NewTy->isDependentType() || OldTy->isDependentType())
17377     return false;
17378 
17379   // Check if the return types are covariant
17380   QualType NewClassTy, OldClassTy;
17381 
17382   /// Both types must be pointers or references to classes.
17383   if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17384     if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17385       NewClassTy = NewPT->getPointeeType();
17386       OldClassTy = OldPT->getPointeeType();
17387     }
17388   } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17389     if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17390       if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17391         NewClassTy = NewRT->getPointeeType();
17392         OldClassTy = OldRT->getPointeeType();
17393       }
17394     }
17395   }
17396 
17397   // The return types aren't either both pointers or references to a class type.
17398   if (NewClassTy.isNull()) {
17399     Diag(New->getLocation(),
17400          diag::err_different_return_type_for_overriding_virtual_function)
17401         << New->getDeclName() << NewTy << OldTy
17402         << New->getReturnTypeSourceRange();
17403     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17404         << Old->getReturnTypeSourceRange();
17405 
17406     return true;
17407   }
17408 
17409   if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17410     // C++14 [class.virtual]p8:
17411     //   If the class type in the covariant return type of D::f differs from
17412     //   that of B::f, the class type in the return type of D::f shall be
17413     //   complete at the point of declaration of D::f or shall be the class
17414     //   type D.
17415     if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17416       if (!RT->isBeingDefined() &&
17417           RequireCompleteType(New->getLocation(), NewClassTy,
17418                               diag::err_covariant_return_incomplete,
17419                               New->getDeclName()))
17420         return true;
17421     }
17422 
17423     // Check if the new class derives from the old class.
17424     if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17425       Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17426           << New->getDeclName() << NewTy << OldTy
17427           << New->getReturnTypeSourceRange();
17428       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17429           << Old->getReturnTypeSourceRange();
17430       return true;
17431     }
17432 
17433     // Check if we the conversion from derived to base is valid.
17434     if (CheckDerivedToBaseConversion(
17435             NewClassTy, OldClassTy,
17436             diag::err_covariant_return_inaccessible_base,
17437             diag::err_covariant_return_ambiguous_derived_to_base_conv,
17438             New->getLocation(), New->getReturnTypeSourceRange(),
17439             New->getDeclName(), nullptr)) {
17440       // FIXME: this note won't trigger for delayed access control
17441       // diagnostics, and it's impossible to get an undelayed error
17442       // here from access control during the original parse because
17443       // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17444       Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17445           << Old->getReturnTypeSourceRange();
17446       return true;
17447     }
17448   }
17449 
17450   // The qualifiers of the return types must be the same.
17451   if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17452     Diag(New->getLocation(),
17453          diag::err_covariant_return_type_different_qualifications)
17454         << New->getDeclName() << NewTy << OldTy
17455         << New->getReturnTypeSourceRange();
17456     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17457         << Old->getReturnTypeSourceRange();
17458     return true;
17459   }
17460 
17461 
17462   // The new class type must have the same or less qualifiers as the old type.
17463   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17464     Diag(New->getLocation(),
17465          diag::err_covariant_return_type_class_type_more_qualified)
17466         << New->getDeclName() << NewTy << OldTy
17467         << New->getReturnTypeSourceRange();
17468     Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17469         << Old->getReturnTypeSourceRange();
17470     return true;
17471   }
17472 
17473   return false;
17474 }
17475 
17476 /// Mark the given method pure.
17477 ///
17478 /// \param Method the method to be marked pure.
17479 ///
17480 /// \param InitRange the source range that covers the "0" initializer.
17481 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17482   SourceLocation EndLoc = InitRange.getEnd();
17483   if (EndLoc.isValid())
17484     Method->setRangeEnd(EndLoc);
17485 
17486   if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17487     Method->setPure();
17488     return false;
17489   }
17490 
17491   if (!Method->isInvalidDecl())
17492     Diag(Method->getLocation(), diag::err_non_virtual_pure)
17493       << Method->getDeclName() << InitRange;
17494   return true;
17495 }
17496 
17497 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17498   if (D->getFriendObjectKind())
17499     Diag(D->getLocation(), diag::err_pure_friend);
17500   else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17501     CheckPureMethod(M, ZeroLoc);
17502   else
17503     Diag(D->getLocation(), diag::err_illegal_initializer);
17504 }
17505 
17506 /// Determine whether the given declaration is a global variable or
17507 /// static data member.
17508 static bool isNonlocalVariable(const Decl *D) {
17509   if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17510     return Var->hasGlobalStorage();
17511 
17512   return false;
17513 }
17514 
17515 /// Invoked when we are about to parse an initializer for the declaration
17516 /// 'Dcl'.
17517 ///
17518 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17519 /// static data member of class X, names should be looked up in the scope of
17520 /// class X. If the declaration had a scope specifier, a scope will have
17521 /// been created and passed in for this purpose. Otherwise, S will be null.
17522 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17523   // If there is no declaration, there was an error parsing it.
17524   if (!D || D->isInvalidDecl())
17525     return;
17526 
17527   // We will always have a nested name specifier here, but this declaration
17528   // might not be out of line if the specifier names the current namespace:
17529   //   extern int n;
17530   //   int ::n = 0;
17531   if (S && D->isOutOfLine())
17532     EnterDeclaratorContext(S, D->getDeclContext());
17533 
17534   // If we are parsing the initializer for a static data member, push a
17535   // new expression evaluation context that is associated with this static
17536   // data member.
17537   if (isNonlocalVariable(D))
17538     PushExpressionEvaluationContext(
17539         ExpressionEvaluationContext::PotentiallyEvaluated, D);
17540 }
17541 
17542 /// Invoked after we are finished parsing an initializer for the declaration D.
17543 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17544   // If there is no declaration, there was an error parsing it.
17545   if (!D || D->isInvalidDecl())
17546     return;
17547 
17548   if (isNonlocalVariable(D))
17549     PopExpressionEvaluationContext();
17550 
17551   if (S && D->isOutOfLine())
17552     ExitDeclaratorContext(S);
17553 }
17554 
17555 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17556 /// C++ if/switch/while/for statement.
17557 /// e.g: "if (int x = f()) {...}"
17558 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17559   // C++ 6.4p2:
17560   // The declarator shall not specify a function or an array.
17561   // The type-specifier-seq shall not contain typedef and shall not declare a
17562   // new class or enumeration.
17563   assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17564          "Parser allowed 'typedef' as storage class of condition decl.");
17565 
17566   Decl *Dcl = ActOnDeclarator(S, D);
17567   if (!Dcl)
17568     return true;
17569 
17570   if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17571     Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17572       << D.getSourceRange();
17573     return true;
17574   }
17575 
17576   return Dcl;
17577 }
17578 
17579 void Sema::LoadExternalVTableUses() {
17580   if (!ExternalSource)
17581     return;
17582 
17583   SmallVector<ExternalVTableUse, 4> VTables;
17584   ExternalSource->ReadUsedVTables(VTables);
17585   SmallVector<VTableUse, 4> NewUses;
17586   for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17587     llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17588       = VTablesUsed.find(VTables[I].Record);
17589     // Even if a definition wasn't required before, it may be required now.
17590     if (Pos != VTablesUsed.end()) {
17591       if (!Pos->second && VTables[I].DefinitionRequired)
17592         Pos->second = true;
17593       continue;
17594     }
17595 
17596     VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17597     NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17598   }
17599 
17600   VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17601 }
17602 
17603 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17604                           bool DefinitionRequired) {
17605   // Ignore any vtable uses in unevaluated operands or for classes that do
17606   // not have a vtable.
17607   if (!Class->isDynamicClass() || Class->isDependentContext() ||
17608       CurContext->isDependentContext() || isUnevaluatedContext())
17609     return;
17610   // Do not mark as used if compiling for the device outside of the target
17611   // region.
17612   if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17613       !isInOpenMPDeclareTargetContext() &&
17614       !isInOpenMPTargetExecutionDirective()) {
17615     if (!DefinitionRequired)
17616       MarkVirtualMembersReferenced(Loc, Class);
17617     return;
17618   }
17619 
17620   // Try to insert this class into the map.
17621   LoadExternalVTableUses();
17622   Class = Class->getCanonicalDecl();
17623   std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17624     Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17625   if (!Pos.second) {
17626     // If we already had an entry, check to see if we are promoting this vtable
17627     // to require a definition. If so, we need to reappend to the VTableUses
17628     // list, since we may have already processed the first entry.
17629     if (DefinitionRequired && !Pos.first->second) {
17630       Pos.first->second = true;
17631     } else {
17632       // Otherwise, we can early exit.
17633       return;
17634     }
17635   } else {
17636     // The Microsoft ABI requires that we perform the destructor body
17637     // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17638     // the deleting destructor is emitted with the vtable, not with the
17639     // destructor definition as in the Itanium ABI.
17640     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17641       CXXDestructorDecl *DD = Class->getDestructor();
17642       if (DD && DD->isVirtual() && !DD->isDeleted()) {
17643         if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17644           // If this is an out-of-line declaration, marking it referenced will
17645           // not do anything. Manually call CheckDestructor to look up operator
17646           // delete().
17647           ContextRAII SavedContext(*this, DD);
17648           CheckDestructor(DD);
17649         } else {
17650           MarkFunctionReferenced(Loc, Class->getDestructor());
17651         }
17652       }
17653     }
17654   }
17655 
17656   // Local classes need to have their virtual members marked
17657   // immediately. For all other classes, we mark their virtual members
17658   // at the end of the translation unit.
17659   if (Class->isLocalClass())
17660     MarkVirtualMembersReferenced(Loc, Class);
17661   else
17662     VTableUses.push_back(std::make_pair(Class, Loc));
17663 }
17664 
17665 bool Sema::DefineUsedVTables() {
17666   LoadExternalVTableUses();
17667   if (VTableUses.empty())
17668     return false;
17669 
17670   // Note: The VTableUses vector could grow as a result of marking
17671   // the members of a class as "used", so we check the size each
17672   // time through the loop and prefer indices (which are stable) to
17673   // iterators (which are not).
17674   bool DefinedAnything = false;
17675   for (unsigned I = 0; I != VTableUses.size(); ++I) {
17676     CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17677     if (!Class)
17678       continue;
17679     TemplateSpecializationKind ClassTSK =
17680         Class->getTemplateSpecializationKind();
17681 
17682     SourceLocation Loc = VTableUses[I].second;
17683 
17684     bool DefineVTable = true;
17685 
17686     // If this class has a key function, but that key function is
17687     // defined in another translation unit, we don't need to emit the
17688     // vtable even though we're using it.
17689     const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17690     if (KeyFunction && !KeyFunction->hasBody()) {
17691       // The key function is in another translation unit.
17692       DefineVTable = false;
17693       TemplateSpecializationKind TSK =
17694           KeyFunction->getTemplateSpecializationKind();
17695       assert(TSK != TSK_ExplicitInstantiationDefinition &&
17696              TSK != TSK_ImplicitInstantiation &&
17697              "Instantiations don't have key functions");
17698       (void)TSK;
17699     } else if (!KeyFunction) {
17700       // If we have a class with no key function that is the subject
17701       // of an explicit instantiation declaration, suppress the
17702       // vtable; it will live with the explicit instantiation
17703       // definition.
17704       bool IsExplicitInstantiationDeclaration =
17705           ClassTSK == TSK_ExplicitInstantiationDeclaration;
17706       for (auto R : Class->redecls()) {
17707         TemplateSpecializationKind TSK
17708           = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17709         if (TSK == TSK_ExplicitInstantiationDeclaration)
17710           IsExplicitInstantiationDeclaration = true;
17711         else if (TSK == TSK_ExplicitInstantiationDefinition) {
17712           IsExplicitInstantiationDeclaration = false;
17713           break;
17714         }
17715       }
17716 
17717       if (IsExplicitInstantiationDeclaration)
17718         DefineVTable = false;
17719     }
17720 
17721     // The exception specifications for all virtual members may be needed even
17722     // if we are not providing an authoritative form of the vtable in this TU.
17723     // We may choose to emit it available_externally anyway.
17724     if (!DefineVTable) {
17725       MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17726       continue;
17727     }
17728 
17729     // Mark all of the virtual members of this class as referenced, so
17730     // that we can build a vtable. Then, tell the AST consumer that a
17731     // vtable for this class is required.
17732     DefinedAnything = true;
17733     MarkVirtualMembersReferenced(Loc, Class);
17734     CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17735     if (VTablesUsed[Canonical])
17736       Consumer.HandleVTable(Class);
17737 
17738     // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17739     // no key function or the key function is inlined. Don't warn in C++ ABIs
17740     // that lack key functions, since the user won't be able to make one.
17741     if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17742         Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
17743         ClassTSK != TSK_ExplicitInstantiationDefinition) {
17744       const FunctionDecl *KeyFunctionDef = nullptr;
17745       if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17746                            KeyFunctionDef->isInlined()))
17747         Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
17748     }
17749   }
17750   VTableUses.clear();
17751 
17752   return DefinedAnything;
17753 }
17754 
17755 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17756                                                  const CXXRecordDecl *RD) {
17757   for (const auto *I : RD->methods())
17758     if (I->isVirtual() && !I->isPure())
17759       ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17760 }
17761 
17762 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17763                                         const CXXRecordDecl *RD,
17764                                         bool ConstexprOnly) {
17765   // Mark all functions which will appear in RD's vtable as used.
17766   CXXFinalOverriderMap FinalOverriders;
17767   RD->getFinalOverriders(FinalOverriders);
17768   for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17769                                             E = FinalOverriders.end();
17770        I != E; ++I) {
17771     for (OverridingMethods::const_iterator OI = I->second.begin(),
17772                                            OE = I->second.end();
17773          OI != OE; ++OI) {
17774       assert(OI->second.size() > 0 && "no final overrider");
17775       CXXMethodDecl *Overrider = OI->second.front().Method;
17776 
17777       // C++ [basic.def.odr]p2:
17778       //   [...] A virtual member function is used if it is not pure. [...]
17779       if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17780         MarkFunctionReferenced(Loc, Overrider);
17781     }
17782   }
17783 
17784   // Only classes that have virtual bases need a VTT.
17785   if (RD->getNumVBases() == 0)
17786     return;
17787 
17788   for (const auto &I : RD->bases()) {
17789     const auto *Base =
17790         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17791     if (Base->getNumVBases() == 0)
17792       continue;
17793     MarkVirtualMembersReferenced(Loc, Base);
17794   }
17795 }
17796 
17797 /// SetIvarInitializers - This routine builds initialization ASTs for the
17798 /// Objective-C implementation whose ivars need be initialized.
17799 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17800   if (!getLangOpts().CPlusPlus)
17801     return;
17802   if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17803     SmallVector<ObjCIvarDecl*, 8> ivars;
17804     CollectIvarsToConstructOrDestruct(OID, ivars);
17805     if (ivars.empty())
17806       return;
17807     SmallVector<CXXCtorInitializer*, 32> AllToInit;
17808     for (unsigned i = 0; i < ivars.size(); i++) {
17809       FieldDecl *Field = ivars[i];
17810       if (Field->isInvalidDecl())
17811         continue;
17812 
17813       CXXCtorInitializer *Member;
17814       InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17815       InitializationKind InitKind =
17816         InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17817 
17818       InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17819       ExprResult MemberInit =
17820         InitSeq.Perform(*this, InitEntity, InitKind, None);
17821       MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17822       // Note, MemberInit could actually come back empty if no initialization
17823       // is required (e.g., because it would call a trivial default constructor)
17824       if (!MemberInit.get() || MemberInit.isInvalid())
17825         continue;
17826 
17827       Member =
17828         new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17829                                          SourceLocation(),
17830                                          MemberInit.getAs<Expr>(),
17831                                          SourceLocation());
17832       AllToInit.push_back(Member);
17833 
17834       // Be sure that the destructor is accessible and is marked as referenced.
17835       if (const RecordType *RecordTy =
17836               Context.getBaseElementType(Field->getType())
17837                   ->getAs<RecordType>()) {
17838         CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17839         if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17840           MarkFunctionReferenced(Field->getLocation(), Destructor);
17841           CheckDestructorAccess(Field->getLocation(), Destructor,
17842                             PDiag(diag::err_access_dtor_ivar)
17843                               << Context.getBaseElementType(Field->getType()));
17844         }
17845       }
17846     }
17847     ObjCImplementation->setIvarInitializers(Context,
17848                                             AllToInit.data(), AllToInit.size());
17849   }
17850 }
17851 
17852 static
17853 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17854                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17855                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17856                            llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17857                            Sema &S) {
17858   if (Ctor->isInvalidDecl())
17859     return;
17860 
17861   CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17862 
17863   // Target may not be determinable yet, for instance if this is a dependent
17864   // call in an uninstantiated template.
17865   if (Target) {
17866     const FunctionDecl *FNTarget = nullptr;
17867     (void)Target->hasBody(FNTarget);
17868     Target = const_cast<CXXConstructorDecl*>(
17869       cast_or_null<CXXConstructorDecl>(FNTarget));
17870   }
17871 
17872   CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17873                      // Avoid dereferencing a null pointer here.
17874                      *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17875 
17876   if (!Current.insert(Canonical).second)
17877     return;
17878 
17879   // We know that beyond here, we aren't chaining into a cycle.
17880   if (!Target || !Target->isDelegatingConstructor() ||
17881       Target->isInvalidDecl() || Valid.count(TCanonical)) {
17882     Valid.insert(Current.begin(), Current.end());
17883     Current.clear();
17884   // We've hit a cycle.
17885   } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17886              Current.count(TCanonical)) {
17887     // If we haven't diagnosed this cycle yet, do so now.
17888     if (!Invalid.count(TCanonical)) {
17889       S.Diag((*Ctor->init_begin())->getSourceLocation(),
17890              diag::warn_delegating_ctor_cycle)
17891         << Ctor;
17892 
17893       // Don't add a note for a function delegating directly to itself.
17894       if (TCanonical != Canonical)
17895         S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17896 
17897       CXXConstructorDecl *C = Target;
17898       while (C->getCanonicalDecl() != Canonical) {
17899         const FunctionDecl *FNTarget = nullptr;
17900         (void)C->getTargetConstructor()->hasBody(FNTarget);
17901         assert(FNTarget && "Ctor cycle through bodiless function");
17902 
17903         C = const_cast<CXXConstructorDecl*>(
17904           cast<CXXConstructorDecl>(FNTarget));
17905         S.Diag(C->getLocation(), diag::note_which_delegates_to);
17906       }
17907     }
17908 
17909     Invalid.insert(Current.begin(), Current.end());
17910     Current.clear();
17911   } else {
17912     DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17913   }
17914 }
17915 
17916 
17917 void Sema::CheckDelegatingCtorCycles() {
17918   llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17919 
17920   for (DelegatingCtorDeclsType::iterator
17921          I = DelegatingCtorDecls.begin(ExternalSource),
17922          E = DelegatingCtorDecls.end();
17923        I != E; ++I)
17924     DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17925 
17926   for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17927     (*CI)->setInvalidDecl();
17928 }
17929 
17930 namespace {
17931   /// AST visitor that finds references to the 'this' expression.
17932   class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17933     Sema &S;
17934 
17935   public:
17936     explicit FindCXXThisExpr(Sema &S) : S(S) { }
17937 
17938     bool VisitCXXThisExpr(CXXThisExpr *E) {
17939       S.Diag(E->getLocation(), diag::err_this_static_member_func)
17940         << E->isImplicit();
17941       return false;
17942     }
17943   };
17944 }
17945 
17946 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17947   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17948   if (!TSInfo)
17949     return false;
17950 
17951   TypeLoc TL = TSInfo->getTypeLoc();
17952   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17953   if (!ProtoTL)
17954     return false;
17955 
17956   // C++11 [expr.prim.general]p3:
17957   //   [The expression this] shall not appear before the optional
17958   //   cv-qualifier-seq and it shall not appear within the declaration of a
17959   //   static member function (although its type and value category are defined
17960   //   within a static member function as they are within a non-static member
17961   //   function). [ Note: this is because declaration matching does not occur
17962   //  until the complete declarator is known. - end note ]
17963   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17964   FindCXXThisExpr Finder(*this);
17965 
17966   // If the return type came after the cv-qualifier-seq, check it now.
17967   if (Proto->hasTrailingReturn() &&
17968       !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17969     return true;
17970 
17971   // Check the exception specification.
17972   if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17973     return true;
17974 
17975   // Check the trailing requires clause
17976   if (Expr *E = Method->getTrailingRequiresClause())
17977     if (!Finder.TraverseStmt(E))
17978       return true;
17979 
17980   return checkThisInStaticMemberFunctionAttributes(Method);
17981 }
17982 
17983 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17984   TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17985   if (!TSInfo)
17986     return false;
17987 
17988   TypeLoc TL = TSInfo->getTypeLoc();
17989   FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17990   if (!ProtoTL)
17991     return false;
17992 
17993   const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17994   FindCXXThisExpr Finder(*this);
17995 
17996   switch (Proto->getExceptionSpecType()) {
17997   case EST_Unparsed:
17998   case EST_Uninstantiated:
17999   case EST_Unevaluated:
18000   case EST_BasicNoexcept:
18001   case EST_NoThrow:
18002   case EST_DynamicNone:
18003   case EST_MSAny:
18004   case EST_None:
18005     break;
18006 
18007   case EST_DependentNoexcept:
18008   case EST_NoexceptFalse:
18009   case EST_NoexceptTrue:
18010     if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
18011       return true;
18012     LLVM_FALLTHROUGH;
18013 
18014   case EST_Dynamic:
18015     for (const auto &E : Proto->exceptions()) {
18016       if (!Finder.TraverseType(E))
18017         return true;
18018     }
18019     break;
18020   }
18021 
18022   return false;
18023 }
18024 
18025 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
18026   FindCXXThisExpr Finder(*this);
18027 
18028   // Check attributes.
18029   for (const auto *A : Method->attrs()) {
18030     // FIXME: This should be emitted by tblgen.
18031     Expr *Arg = nullptr;
18032     ArrayRef<Expr *> Args;
18033     if (const auto *G = dyn_cast<GuardedByAttr>(A))
18034       Arg = G->getArg();
18035     else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
18036       Arg = G->getArg();
18037     else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
18038       Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
18039     else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
18040       Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
18041     else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
18042       Arg = ETLF->getSuccessValue();
18043       Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
18044     } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
18045       Arg = STLF->getSuccessValue();
18046       Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
18047     } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
18048       Arg = LR->getArg();
18049     else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
18050       Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
18051     else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
18052       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18053     else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
18054       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18055     else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
18056       Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
18057     else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
18058       Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
18059 
18060     if (Arg && !Finder.TraverseStmt(Arg))
18061       return true;
18062 
18063     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
18064       if (!Finder.TraverseStmt(Args[I]))
18065         return true;
18066     }
18067   }
18068 
18069   return false;
18070 }
18071 
18072 void Sema::checkExceptionSpecification(
18073     bool IsTopLevel, ExceptionSpecificationType EST,
18074     ArrayRef<ParsedType> DynamicExceptions,
18075     ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
18076     SmallVectorImpl<QualType> &Exceptions,
18077     FunctionProtoType::ExceptionSpecInfo &ESI) {
18078   Exceptions.clear();
18079   ESI.Type = EST;
18080   if (EST == EST_Dynamic) {
18081     Exceptions.reserve(DynamicExceptions.size());
18082     for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
18083       // FIXME: Preserve type source info.
18084       QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
18085 
18086       if (IsTopLevel) {
18087         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
18088         collectUnexpandedParameterPacks(ET, Unexpanded);
18089         if (!Unexpanded.empty()) {
18090           DiagnoseUnexpandedParameterPacks(
18091               DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
18092               Unexpanded);
18093           continue;
18094         }
18095       }
18096 
18097       // Check that the type is valid for an exception spec, and
18098       // drop it if not.
18099       if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
18100         Exceptions.push_back(ET);
18101     }
18102     ESI.Exceptions = Exceptions;
18103     return;
18104   }
18105 
18106   if (isComputedNoexcept(EST)) {
18107     assert((NoexceptExpr->isTypeDependent() ||
18108             NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
18109             Context.BoolTy) &&
18110            "Parser should have made sure that the expression is boolean");
18111     if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
18112       ESI.Type = EST_BasicNoexcept;
18113       return;
18114     }
18115 
18116     ESI.NoexceptExpr = NoexceptExpr;
18117     return;
18118   }
18119 }
18120 
18121 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
18122              ExceptionSpecificationType EST,
18123              SourceRange SpecificationRange,
18124              ArrayRef<ParsedType> DynamicExceptions,
18125              ArrayRef<SourceRange> DynamicExceptionRanges,
18126              Expr *NoexceptExpr) {
18127   if (!MethodD)
18128     return;
18129 
18130   // Dig out the method we're referring to.
18131   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18132     MethodD = FunTmpl->getTemplatedDecl();
18133 
18134   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18135   if (!Method)
18136     return;
18137 
18138   // Check the exception specification.
18139   llvm::SmallVector<QualType, 4> Exceptions;
18140   FunctionProtoType::ExceptionSpecInfo ESI;
18141   checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18142                               DynamicExceptionRanges, NoexceptExpr, Exceptions,
18143                               ESI);
18144 
18145   // Update the exception specification on the function type.
18146   Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18147 
18148   if (Method->isStatic())
18149     checkThisInStaticMemberFunctionExceptionSpec(Method);
18150 
18151   if (Method->isVirtual()) {
18152     // Check overrides, which we previously had to delay.
18153     for (const CXXMethodDecl *O : Method->overridden_methods())
18154       CheckOverridingFunctionExceptionSpec(Method, O);
18155   }
18156 }
18157 
18158 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18159 ///
18160 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18161                                        SourceLocation DeclStart, Declarator &D,
18162                                        Expr *BitWidth,
18163                                        InClassInitStyle InitStyle,
18164                                        AccessSpecifier AS,
18165                                        const ParsedAttr &MSPropertyAttr) {
18166   IdentifierInfo *II = D.getIdentifier();
18167   if (!II) {
18168     Diag(DeclStart, diag::err_anonymous_property);
18169     return nullptr;
18170   }
18171   SourceLocation Loc = D.getIdentifierLoc();
18172 
18173   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18174   QualType T = TInfo->getType();
18175   if (getLangOpts().CPlusPlus) {
18176     CheckExtraCXXDefaultArguments(D);
18177 
18178     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18179                                         UPPC_DataMemberType)) {
18180       D.setInvalidType();
18181       T = Context.IntTy;
18182       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18183     }
18184   }
18185 
18186   DiagnoseFunctionSpecifiers(D.getDeclSpec());
18187 
18188   if (D.getDeclSpec().isInlineSpecified())
18189     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18190         << getLangOpts().CPlusPlus17;
18191   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18192     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18193          diag::err_invalid_thread)
18194       << DeclSpec::getSpecifierName(TSCS);
18195 
18196   // Check to see if this name was declared as a member previously
18197   NamedDecl *PrevDecl = nullptr;
18198   LookupResult Previous(*this, II, Loc, LookupMemberName,
18199                         ForVisibleRedeclaration);
18200   LookupName(Previous, S);
18201   switch (Previous.getResultKind()) {
18202   case LookupResult::Found:
18203   case LookupResult::FoundUnresolvedValue:
18204     PrevDecl = Previous.getAsSingle<NamedDecl>();
18205     break;
18206 
18207   case LookupResult::FoundOverloaded:
18208     PrevDecl = Previous.getRepresentativeDecl();
18209     break;
18210 
18211   case LookupResult::NotFound:
18212   case LookupResult::NotFoundInCurrentInstantiation:
18213   case LookupResult::Ambiguous:
18214     break;
18215   }
18216 
18217   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18218     // Maybe we will complain about the shadowed template parameter.
18219     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18220     // Just pretend that we didn't see the previous declaration.
18221     PrevDecl = nullptr;
18222   }
18223 
18224   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18225     PrevDecl = nullptr;
18226 
18227   SourceLocation TSSL = D.getBeginLoc();
18228   MSPropertyDecl *NewPD =
18229       MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18230                              MSPropertyAttr.getPropertyDataGetter(),
18231                              MSPropertyAttr.getPropertyDataSetter());
18232   ProcessDeclAttributes(TUScope, NewPD, D);
18233   NewPD->setAccess(AS);
18234 
18235   if (NewPD->isInvalidDecl())
18236     Record->setInvalidDecl();
18237 
18238   if (D.getDeclSpec().isModulePrivateSpecified())
18239     NewPD->setModulePrivate();
18240 
18241   if (NewPD->isInvalidDecl() && PrevDecl) {
18242     // Don't introduce NewFD into scope; there's already something
18243     // with the same name in the same scope.
18244   } else if (II) {
18245     PushOnScopeChains(NewPD, S);
18246   } else
18247     Record->addDecl(NewPD);
18248 
18249   return NewPD;
18250 }
18251 
18252 void Sema::ActOnStartFunctionDeclarationDeclarator(
18253     Declarator &Declarator, unsigned TemplateParameterDepth) {
18254   auto &Info = InventedParameterInfos.emplace_back();
18255   TemplateParameterList *ExplicitParams = nullptr;
18256   ArrayRef<TemplateParameterList *> ExplicitLists =
18257       Declarator.getTemplateParameterLists();
18258   if (!ExplicitLists.empty()) {
18259     bool IsMemberSpecialization, IsInvalid;
18260     ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18261         Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18262         Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18263         ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18264         /*SuppressDiagnostic=*/true);
18265   }
18266   if (ExplicitParams) {
18267     Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18268     for (NamedDecl *Param : *ExplicitParams)
18269       Info.TemplateParams.push_back(Param);
18270     Info.NumExplicitTemplateParams = ExplicitParams->size();
18271   } else {
18272     Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18273     Info.NumExplicitTemplateParams = 0;
18274   }
18275 }
18276 
18277 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18278   auto &FSI = InventedParameterInfos.back();
18279   if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18280     if (FSI.NumExplicitTemplateParams != 0) {
18281       TemplateParameterList *ExplicitParams =
18282           Declarator.getTemplateParameterLists().back();
18283       Declarator.setInventedTemplateParameterList(
18284           TemplateParameterList::Create(
18285               Context, ExplicitParams->getTemplateLoc(),
18286               ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18287               ExplicitParams->getRAngleLoc(),
18288               ExplicitParams->getRequiresClause()));
18289     } else {
18290       Declarator.setInventedTemplateParameterList(
18291           TemplateParameterList::Create(
18292               Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18293               SourceLocation(), /*RequiresClause=*/nullptr));
18294     }
18295   }
18296   InventedParameterInfos.pop_back();
18297 }
18298